我在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
我理解这意味着它没有找到图像,但为什么不继续下一个图像并打印错误声明?
答案 0 :(得分:1)
因为您尝试将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返回正确的值,它将被分配给cent和MOI。如果它返回None,则None将分配给cent和MOI。
答案 1 :(得分:1)
您的函数有时会返回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')