cv2.imread: checking if image is being read

后端 未结 3 817
萌比男神i
萌比男神i 2020-12-03 14:03

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         


        
相关标签:
3条回答
  • 2020-12-03 14:25

    from documentation, we may use

    retval  =   cv.haveImageReader (filename)
    

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

    0 讨论(0)
  • 2020-12-03 14:29

    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

    0 讨论(0)
  • 2020-12-03 14:38

    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.

    0 讨论(0)
提交回复
热议问题