cv2.imread:检查是否正在读取图像 [英] cv2.imread: checking if image is being read

查看:764
本文介绍了cv2.imread:检查是否正在读取图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用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.

请注意,NoneFalse的值不同.但是,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆