Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 393
Яois Avatar asked May 13 '14 10:05

Яois


People also ask

How can you tell if an image is empty?

Use the getAttribute() method to check if an image src is empty, e.g. img. getAttribute('src') . If the src attribute does not exist, the method returns either null or empty string, depending on the browser's implementation.

What does cv2 Imread return?

cv2. imread() method loads an image from the specified file. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format) then this method returns an empty matrix.

Can Imread read JPG?

imread does not read jpg files.

How do I read Imread images?

A = imread( filename ) reads the image from the file specified by filename , inferring the format of the file from its contents. If filename is a multi-image file, then imread reads the first image in the file.


1 Answers

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

like image 101
loopbackbee Avatar answered Sep 18 '22 02:09

loopbackbee