python - ValueError :use a. any() or a.all() and AttributeError: 'bool' object has no attribute 'all' python

标签 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
            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'

谁能解释一下?!!

最佳答案

i 是一个列表。我们没有关于它包含什么的信息,但是错误和解决方案是清楚的。

对于参数,假设 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,还是只需要一个就足够了。

Any :

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

All :

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

关于python - ValueError :use a. any() or a.all() and AttributeError: 'bool' object has no attribute 'all' python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23767926/

相关文章:

python unittest 在测试之间共享对象实例

python - Django 1.11 自定义用户模型与组

python - 如何将 2D 边界框像素坐标 (x, y, w, h) 转换为相对坐标(Yolo 格式)?

image - 从图像中检测和裁剪文本 block (段落)的简单方法?

image-processing - 如何从图像中消除运动引起的失真

c++ - OpenCV : libopencv_core. so.2.4:无法打开共享对象文件:没有这样的文件或目录

python - Scrapy: 在一个请求失败时(例如404,500),如何请求另一个备选请求?

python - 尝试使用目录和子目录中的 glob 进行排序

c++ - 打开CV : CUDA context initialization for different methods

python - OpenCV restorePose相机坐标系