[英]ValueError when using image == None
I'm creating a fail-safe for my program so whenever the image is not there or image = None
it will display a message and terminate the program. 我正在为我的程序创建故障保护,因此无论何时不存在
image = None
或image = None
,它将显示一条消息并终止程序。 I am using the code below as a way to do this: 我正在使用以下代码作为执行此操作的方法:
src_img = cv2.imread('/home/nazar/Downloads/img_4.png', 1)
if src_img == None:
exit('No such file or direcory!')
copy = src_img.copy()
This works if there is no image but when there is an image, it will give an error: 如果没有图像,这会起作用,但是当有图像时,会出现错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I tried following the error's suggestion and tried if src_img.all == None:
and now when there is no image it gives the error: 我尝试按照错误的建议进行操作,并尝试
if src_img.all == None:
现在没有图像时出现错误:
AttributeError: 'NoneType' object has no attribute 'all'
is there a way to actually do this without getting these error messages and work if an image is given or there is no image given. 有没有一种方法可以在不获取这些错误消息的情况下实际执行此操作,并且在给出图像或没有给出图像的情况下也可以工作。
You are getting the first ValueError
because NoneType
does not define an equality comparison against numpy arrays, so the array's comparison method is used instead. 您将收到第一个
ValueError
因为NoneType
没有定义对numpy数组的相等比较,因此使用了数组的比较方法。 Numpy converts None into an object array and broadcasts it to the size of your image. Numpy将None转换为对象数组,并将其广播为图像的大小。 The result of
==
is an element-wise comparison, ie, a boolean array of the same size as your image. ==
的结果是逐元素比较,即与图像大小相同的布尔数组。
Instead of all that, you should do 除了这些,您应该做
if src_img is None:
is
compares the raw references. is
比较原始参考。 It is the recommended way to check for None since it is much faster and None is a singleton. 建议您检查“无”,因为它更快并且“无”是一个单例。
The second AttributeError
comes from the fact that when src_img
is None, it doesn't have a method named all
. 第二个
AttributeError
来自以下事实:当src_img
为None时,它没有名为all
的方法。 Even when it is a proper array, src_img.all
is just a reference to that method, not the result of calling it. 即使是适当的数组,
src_img.all
也只是对该方法的引用,而不是调用它的结果。
Strangely enough, you could have totally gotten away with doing if np.all(src_img == None):
, but you really shouldn't because it's a complete travesty in this case. 奇怪的是,
if np.all(src_img == None):
您本可以完全放弃的,但是您实际上不应该这样做,因为在这种情况下,这是完全的琐事。 When src_img
is None, the comparison is scalar True, so np.all
would return True. 当
src_img
为None时,比较标量为True,因此np.all
将返回True。 If src_img
is a numeric array, every element would compare False, and np.all
would return False. 如果
src_img
是一个数字数组,则每个元素将比较False,而np.all
将返回False。 The only time this world give the wrong result is if you had an src_img
that was an object array all of whose elements were None. 这个世界唯一的错误结果是,如果您有一个
src_img
,它是一个对象数组,其所有元素均为None。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.