ValueError:使用a.any()或a.all()和AttributeError:“bool”对象没有“all”python属性

2024-05-12 18:29:37 发布

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

我试图运行以下代码:

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]

但我有个错误:

Traceback (most recent call last):
File "C:\opencv2.4.8\sources\samples\python2\Work.py", line 120, in <module>
trackObj(threshold,hsv,frame)
File "C:\opencv2.4.8\sources\samples\python2\Work.py", line 84, in trackObj
while i >= 0:
ValueError: The truth value of an array with more than one element is ambiguous. Use       a.any() or a.all()

当我在特定行中添加all()或any()时,会出现以下错误:

AttributeError: 'bool' object has no attribute 'all'

有人能解释吗?!!


Tags: pyobjif错误lineareaallfile
2条回答

i是一个list。我们没有关于它所包含内容的信息,但是错误和解决方案仍然很清楚。

对于参数,假设i是:

i = [1, 0, 1, 2, 3]

不能将列表与>=进行比较。相反,您要做的是比较列表中的每个元素。因为你比较的是>= 0,用any()all()来检查它的真实性就足够简单了:

>>> 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):

只有您知道应该是哪一个,这取决于您是否要检查它们是否全部>;=0,或者只检查一个就足够了。

^{}

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

^{}

Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return 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

相关问题 更多 >