Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

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

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 

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

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()

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.

My solution so far involves using the type of the returned value as follows:

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

But I was wondering: isn't there a nicer solution, closer to the initial check if(img): #do stuff ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Note that None and False are not the same value. However, bool(None)==False, which is why if None fails.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...