Search code examples
pythonubuntucomputer-visionopencv

Cannot read image using cv2.imread()


I am trying to read an image and show it using OpenCV in Ubuntu, But for some reason it doesn't works. The file I am reading is placed in the same directory where the code resides but still it doesn't works. Can anybody tell me whats going on, Thank you

Error

None
Traceback (most recent call last):
  File "code.py", line 10, in <module>
    cv2.imshow('image', img)
cv2.error: OpenCV(3.4.2) /io/opencv/modules/highgui/src/window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'

code.py

img = cv2.imread('sample1.jpg')
print(img)
cv2.imshow('image', img)

Solution

  • Apparently, no image has been loaded as print(img) printed None, thus you cannot use cv2.imshow on a None object.

    img = cv2.imread('sample1.jpg')
    if img != None:
         cv2.imshow('image', img)
    

    You could also check if there is a file by using:

    import os
    os.path.isfile('sample1.jpg')