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
(布尔值).
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屋!