将matlab中的find()转换为python

2024-04-18 21:23:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将一段代码从Matlab转换成Python。Matlab中的代码是:

x = find(sEdgepoints > 0 & sNorm < lowT);
sEdgepoints(x)=0;

两个数组的大小相同,我基本上是在创建一个掩码。在

我读到herenumpy中的nonzero()等同于find(),所以我使用了它。在Python中,我有用于sEdgepoints的dstc和用于sNorm的dst。我也直接输入了lowT=60。所以,密码是

^{pr2}$

但是,我得到以下错误:

Traceback (most recent call last):
File "C:\Python27\Sheet Counter\customsobel.py", line 32, in <module>
    x = np.nonzero(dstc > 0 and dst < 60)
ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()

我读过a.any()/a.all()in this post的用法,但我不确定这将如何工作。所以,我有两个问题: 1如果是,使用哪个数组? 2如果我是正确的,它不能工作,如何转换代码?在


Tags: 代码inany数组allfinddstmatlab
3条回答

你可以自己实现,比如:

x = [[i,j] for i, j in zip(sEdgepoints , sNorm ) if i > 0 and j < lowT]

将为您提供与匹配约束相对应的列表列表。 我想这可能不是你想要的。

也许看看pandas模块,它使掩蔽比普通python或numpy更舒服: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html

尝试^{} (注意()在不等式中的重要性):

>>X=np.array([1,2,3,4,5])
>>Y=np.array([7,6,5,4,3])
>>ans = np.argwhere((X>3) & (Y<7))
>>ans 

array([[3],
   [4]])

and执行布尔运算,numpy希望您执行按位运算,因此您必须使用&,即

x = np.nonzero((dstc > 0) & ( dst < 60))

相关问题 更多 >