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

Why doesn't this OpenCV masking function iterate?

我在 Python OpenCV 中写了一个算法来找到某些目标,但有时这些目标很难找到,所以我做了这个 if-else 语句,当找不到时只输出 'target not found'目标。我正在迭代 1000 多张图像并对它们调用算法,但出现此错误:

'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

我明白这意味着它没有找到图像,但为什么它不继续到下一张图像并打印错误声明?

因为您正试图将 None 分配给值列表。

>>> 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 returns 一个正确的值,它将被分配给 cent 和 MOI。如果它 returns a None,None 将同时分配给 cent 和 MOI。

你的函数有时 returns 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

解包前检查return值是否为None:

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