cv2.imread: checking if image is being read

Question:

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 ?

Asked By: Яois

||

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

Answered By: loopbackbee

If you want to write the contents as soon as the image file is being generated then you can use os.path.isfile() which return a bool value depending upon the presence of a file in the given directory.

import cv2 
import os.path

while not os.path.isfile("myImage.jpg"):
    #ignore if no such file is present.
    pass

img = cv2.imread("myImage.jpg", 0)

cv2.imwrite("result.jpg", img)

You can also refer to docs for detailed implementation of each method and basic image operations.

Answered By: ZdaR

from documentation, we may use

retval  =   cv.haveImageReader (filename)

source https://docs.opencv.org/master/d4/da8/group__imgcodecs.html

Answered By: AlexRe
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.