python - cv2.imread : checking if image is being read

标签 python opencv numpy

我正在用 python 编写一个 OpenCV 程序,在某些时候我有类似的东西

import cv2
import numpy as np
... 
img = cv2.imread("myImage.jpg")

# do stuff with image here 

问题是我必须在继续之前检测图像文件是否被正确读取。如果无法打开图像,cv2.imread 返回 False,所以我想做类似的事情:

if (img):
   #continue doing stuff

如果图像未打开(例如,如果文件不存在),img 将等于 None(如预期)。但是,当 imread 起作用时,条件中断:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

即返回的 numpy.ndarray 不能用作 bool 值。问题似乎是 imread 如果成功则返回 numpy.ndarray ,否则返回 False ( bool 值)。

到目前为止,我的解决方案涉及使用返回值的 type,如下所示:

if (type(img) is np.ndarray): 
     #do stuff with image

但我想知道:难道没有更好的解决方案,更接近初始检查 if(img): #do stuff 吗?

最佳答案

如果你确定 img 的值在你的情况下是 None,你可以简单地使用 if not img is None,或者,等效地,如果 img 不是 None。您不需要明确检查类型。

请注意,NoneFalse 不是相同的值。但是,bool(None)==False,这就是 if None 失败的原因。

不过,OpenCV 2 和 3 的 imread 文档指出,出错时应返回空矩阵。您可以使用 if img.size ==0

检查它

关于python - cv2.imread : checking if image is being read,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23628325/

相关文章:

image - 调整图像中的 ROI 大小

python - 如何更改包含字符串的日期时间格式列

python - 将ndarray从float64转换为整数

python - 分组后折叠数据框 pandas

image - 奇怪的OpenCV代码

python - 如何使用特定规则在 Python 中按元素比较两个数组?

python - 如何在python中使用opencv读取图像的掩码

python - pandas.Panel(data=list_of_dfs) 坏了?

python - 将 .xlsb 转换为 .xlsx - 多表 Microsoft Excel 文件

python - PyVISA 未在 Linux 上列出 USB 仪器