Assertion failure : size.width>0 && size.height>0 in function imshow

Question:

i am using opencv2 and python on raspberry pi. and i am new with python and opencv. i tried to read a jpeg image and display image it shows the following error:

/home/pi/opencv-2.4.9/modules/highgui/src/window.cpp:269: 
  error: (-215) size.width>0 &&  size.height>0 in function imshow.

and the code is:

import cv2
# windows to display image
cv2.namedWindow("Image")
# read image
image = cv2.imread('home/pi/bibek/book/test_set/bbb.jpeg')
# show image
cv2.imshow("Image", image)
# exit at closing of window
cv2.waitKey(0)
cv2.destroyAllWindows()
Asked By: Bibek Ghimire

||

Answers:

The image fails to load (probably because you forgot the leading / in the path). imread then returns None. Passing None to imshow causes it to try to create a window of size 0x0, which fails.

The poor error handling in cv probably owes to its quite thin wrapper layer on the C++ implementation (where returning NULL on error is a common practice).

Answered By: Krumelur

While using Raspbian in Rpi 3 I had the same problem when trying to read qrcodes. The error is because cv2 was not able to read the image. If using png image install pypng module.

sudo pip install pypng
Answered By: Mohammad Yasir K P

it’s the path which is causing the problem, i had the same problem but when i gave the full path of the image it was working perfectly.

Answered By: malware_656

One of the reasons, this error is caused is when there is no file at the path specified. So, a good practice will be to verify the path like this ( If you are on a linux based machine ):

ls <path-provided-in-imread-function>

You will get an error if the path is incorrect or the file is missing.

Answered By: Rahul Singal

In my case, I had forgotten to change the working directory of my terminal to that of my code+testImage. Hence, it failed to find the image there.

Finally, this is what worked for me:

I saved the image and Python file on Desktop. I changed my cmd directory to it,

cd Desktop

And then checked for my file:

ls

And this was my code that worked:

import cv2
import numpy as np

im = cv2.imread('unnamed.jpg')
#Display the image
cv2.imshow('im',im)
cv2.waitKey(2000) #Milliseconds
Answered By: Pe Dro

While reading the image file, specifying the color option should solve this,
for example:

image=cv2.imread('img.jpg',cv2.IMREAD_COLOR)

adding the cv2.IMREAD_COLOR should solve this

Answered By: aayush

Use r in the code where you specified the file address.
For Example:

import cv2
img = cv2.imread(r'D:StudyGitOpenCVresourceslena.png')
cv2.imshow('output', img)
cv2.waitKey(0)

r stands for "raw" and will cause backslashes in the string to be interpreted as actual backslashes rather than special characters.

Answered By: AYUSH KUMAR

This problem happened to me when i just failed to write the extension of the image.
Please check if you forgot to write the extension or any other part of the full path to the image.

Remember, extension is required whether you are printing image using OpenCV or Mathplotlib.

Answered By: Anmol K.

I am also getting a similar error, so instead of opening a new question, I thought maybe it would be a good idea to gather it all here since there’s already some helpful answers…

My code (textbook code to open a video using OpenCV in Python):

import cv2 as cv
import os

path = 'C:/Users/username/Google Drive/Master/THESIS/uva_nemo_db/videos/'
os.chdir(path)
video_file = '001_deliberate_smile_2.mp4'
cap = cv.VideoCapture(video_file) 


if not cap.isOpened():
    print("Error opening Video File.")

while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    cv.imshow('frame',frame)

    if cv.waitKey(1) & 0xFF == ord('q'):
        break

    # if frame is read correctly, ret is True
    if not ret:
        print("Can't retrieve frame - stream may have ended. Exiting..")
        break

# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

The reason why I am dumbfounded is that I am getting the same error – BUT – the video is actually played… When running the code the Python interpreter opens up an instance of Python running the video. Once the video ends, it breaks out of the loop, closes the video and throws the error:

Traceback (most recent call last):
File "C:/Users/username/Documents/smile-main/video-testing.py", line 24, in
cv.imshow(‘frame’,frame)
cv2.error: OpenCV(4.4.0) C:UsersappveyorAppDataLocalTemp1pip-req-build-wwma2wneopencvmoduleshighguisrcwindow.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function ‘cv::imshow’

I’d appreciate any input!

**

EDIT: How I fixed my error!

**

I encased my code in a try/except like this:

# Import required libraries
import cv2 as cv
import os

path = 'C:/Users/username/Google Drive/Master/THESIS/uva_nemo_db/videos/'
# test_path = 'C:/Users/username/Downloads'
os.chdir(path)
os.getcwd()
video_file = '001_deliberate_smile_2.mp4'

cap = cv.VideoCapture(video_file) #cap for "Video Capture Object"
   

if not cap.isOpened():
    print("Error opening Video File.")
try:
    while True:
        # Capture frame-by-frame
        ret, frame = cap.read()
        cv.imshow('frame',frame)

        if cv.waitKey(1) & 0xFF == ord('q'):
            break

        # if frame is read correctly, ret is True
        if not ret:
            print("Can't retrieve frame - stream may have ended. Exiting..")
            break
except:
    print("Video has ended.")


# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

I’d still appreciate any input on why this error popped up even though the video played fine, and why the try/except eliminated it.

Thank you!

Answered By: Dkoded

I solve it by using this code

    os.chdir(f"{folder_path}")
Answered By: 민서김

It is because the image is not loaded. For me at VScode the relative path was problem but after copying the file path from VSCode itself the problem was solved.

Answered By: Sam-Dar

I had the same problem too, on VSCode. Tried running the same code on Notepad++ and it worked. To fix this issue on VSCode, don’t forget to open the folder that you’re working in on the left pane. This solved my issue.

Answered By: CingirakliDumbelek

make sure that the code which your running and the image both together should be in one single folder if not then using cd command go to that folder and then run it again this worked for me…

Answered By: IronMan
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.