为什么这个OpenCV掩蔽函数不迭代?

2024-04-29 11:53:31 发布

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

我在Python OpenCV中编写了一个算法来查找特定的目标,但是有时这些目标很难找到,所以我做了这个if else语句,在找不到目标时只输出'target not found'。我迭代了1000个图像并调用了它们的algo,但是我得到了一个错误:

'NoneType' object is not iterable

在下面代码的第6行:

def image_data(img):
    img3 = masking (img)
    if img3 is None:
        print "target not found"
    else:
        cent, MOI = find_center(img3)
        if cent == 0 or MOI == 0:
        print 'target not found'
        else:
        return cent[0],cent[1],MOI

我明白这意味着它没有找到图像,但为什么不直接转到下一个图像并打印错误声明呢?你知道吗


Tags: 图像target目标imgifis错误not
2条回答

因为您正在尝试将“无”赋值给值列表。你知道吗

>>> a, b = None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable

要正确执行此操作,请尝试:

cent, MOI = find_center(img3) or (None, None)

这样,如果find_center返回正确的值,它将被分配给cent和MOI。如果返回None,则会将None分配给cent和MOI。你知道吗

函数有时返回None,因此无法从None中解压变量:

In [1]: def f(i):
   ...:     if i > 2:
   ...:         return "foo","bar"
   ...:     

In [2]: a,b = f(3)

In [3]: a,b
Out[3]: ('foo', 'bar')

In [4]: a,b = f(1)
                                     -
TypeError                                 Traceback (most recent call last)
<ipython-input-4-54f2476b15d0> in <module>()
  > 1 a,b = f(1)

TypeError: 'NoneType' object is not iterable

开箱前检查返回值是否为无:

def image_data(img):
    img3 = masking (img)
    if img3 is None:
        print("target not found")
    else:
        val = find_center(img3)
        if val:
            cent, MOI = val
            return cent[0],cent[1],MOI
        else:
            print('target not found')

或者使用try/except

def image_data(img):
    img3 = masking (img)
    if img3 is None:
        print("target not found")
    else:
        try:
            cent, MOI = find_center(img3)
            return cent[0], cent[1], MOI
        except TypeError:
            print('target not found')

相关问题 更多 >