cv2.imread:检查图像是否正在被读取 [英] cv2.imread: checking if image is being read
问题描述
我正在用 python 编写 OpenCV 程序,在某些时候我有类似的东西
I'm writing an OpenCV program in python, and at some point I have something like
import cv2
import numpy as np
...
img = cv2.imread("myImage.jpg")
# do stuff with image here
问题是我必须在继续之前检测图像文件是否被正确读取.cv2.imread
返回 False
如果无法打开图像,所以我想这样做:
The problem is that I have to detect if the image file is being correctly read before continuing. cv2.imread
returns False
if not able to open the image, so I think of doing something like:
if (img):
#continue doing stuff
如果图像没有打开(例如,如果文件不存在)img
等于 None
(正如预期的那样),会发生什么情况.但是,当 imread
工作时,条件会中断:
What happens is that if the image is not opened (e.g. if the file does not exist) img
is equal to None
(as expected). However, when imread
works, the condition, breaks:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
即返回的 numpy.ndarray
不能用作布尔值.问题似乎是 imread
如果成功则返回 numpy.ndarray,否则返回 False
(boolean).
i.e. the returned numpy.ndarray
cannot be used as a boolean. The problem seems to be that imread
returns numpy.ndarray if success and False
(boolean) otherwise.
到目前为止,我的解决方案涉及使用返回值的 type
如下:
My solution so far involves using the type
of the returned value as follows:
if (type(img) is np.ndarray):
#do stuff with image
但我想知道:没有更好的解决方案,更接近初始检查 if(img): #do stuff
吗?
But I was wondering: isn't there a nicer solution, closer to the initial check if(img): #do stuff
?
推荐答案
如果您确定 img
的值为 None
在您的情况下,您可以简单地使用 if not img is None
,或者等效地,if img is not None
.您不需要显式检查类型.
If you're sure that the value of img
is None
in your case, you can simply use if not img is None
, or, equivalently, if img is not None
. You don't need to check the type explicitly.
请注意,None
和 False
是不同的值.但是,bool(None)==False
,这就是 if None
失败的原因.
Note that None
and False
are not the same value. However, bool(None)==False
, which is why if None
fails.
imread
的文档(包括 OpenCV 2 和 3)指出,在出错时应该返回一个空矩阵.您可以使用 if img.size ==0
The documentation for imread
, both for OpenCV 2 and 3, states, however, that a empty matrix should be returned on error. You can check for that using if img.size ==0
这篇关于cv2.imread:检查图像是否正在被读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!