ValueError:使用a.any()或a.all()和AttributeError:';布尔';对象没有属性';全部';python
我正在尝试运行以下代码:ValueError:使用a.any()或a.all()和AttributeError:';布尔';对象没有属性';全部';python,python,opencv,Python,Opencv,我正在尝试运行以下代码: if (numObj<Max_DetObj): i=0 while (i >= 0).all(): Moment = cv2.moments(contours[i]) area = Moment['m00'] if (area >Min_ObjArea): x=Moment['m10']/area y=Moment['m01']/area
if (numObj<Max_DetObj):
i=0
while (i >= 0).all():
Moment = cv2.moments(contours[i])
area = Moment['m00']
if (area >Min_ObjArea):
x=Moment['m10']/area
y=Moment['m01']/area
found_Obj=True
else:
found_Obj=False
i=hierarchy[i][0]
谁能解释一下
i
是一个列表
。我们没有关于它包含什么的信息,但是错误和解决方案是清楚的
对于参数,我们假设i
是:
i = [1, 0, 1, 2, 3]
您无法将列表与=
进行比较。相反,您要做的是比较列表中的每个元素。因为与=0
相比,只需使用any()
和all()
检查其真实性就足够简单了:
因此,在您的代码中,它将是:
while any(i):
或
只有您知道它应该是哪一个,这取决于您是否要检查它们是否都>=0,或者只有一个就足够了
:
如果iterable的任何元素为True,则返回True。如果iterable为空,则返回False。相当于:
:
如果iterable的所有元素都为True(或者iterable为空),则返回True。相当于:
我猜你在秘密使用numpy数组,所以你应该使用numpy函数 请参阅复制stacktrace的以下代码:
Python 2.7.6 (default, Mar 22 2014, 15:40:47)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> i = np.zeros(2)
>>> if i:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> if not i.any():
... print "OK"
...
OK
Python 2.7.6(默认,2014年3月22日,15:40:47)
[GCC 4.8.2]关于linux2
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>将numpy作为np导入
>>>i=np.零(2)
>>>如果我:
... 通过
...
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
ValueError:包含多个元素的数组的真值不明确。使用a.any()或a.all()
>>>如果不是的话,我会的
... 打印“确定”
...
好啊
您想做什么i
只是一个数字,因此它没有all
。为什么不在i>=0时执行?当出现错误时,向我们显示完整的堆栈跟踪,而不仅仅是exception@BrenBarn我做了,但我得到了同样的错误,我没有真正理解你的解释,因为“我这里不是一个列表,它只是一个变量,第一个值是0,在每次迭代中它变成了I=hierarchy[I][0](实际循环是用C++编写的,我试图把它转换成Python),显然不是。打印出来<代码> i>代码>每个循环之后,验证我打印出来的I和I发现在每个循环的结尾,它变成列表(示例i=[1,-1,1,1]),当我将它改为任何(i)或全部(i)时它说“int”对象是不可编辑的!!!!因为在第一个循环中,您创建了i=0
。将其更改为列表,例如[1]
非常感谢您,现在它可以工作了(如果有关于代码的任何其他通知,我将非常感谢)
>>> any(i) # Are any of the elements of i true?
True
>>> all(i) # Are all of the elements of i true?
False
while any(i):
while all(i):
def any(iterable):
for element in iterable:
if element:
return True
return False
def all(iterable):
for element in iterable:
if not element:
return False
return True
Python 2.7.6 (default, Mar 22 2014, 15:40:47)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> i = np.zeros(2)
>>> if i:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> if not i.any():
... print "OK"
...
OK