How to Fix the OpenCV Error: (-215:Assertion failed)size.width>0 & size.height>0 in function imshow Error in Python

posted 6 min read

OpenCV is a popular open source framework in Python that can perform computer vison and image processing tasks like resizing, detecting, cropping, and transformation of texts or objects within images.

It is common to encounter the "OpenCV Error: (-215:Assertion failed)size.width>0 & size.height>0 in function imshow" in Python. Specifically, the error will happen using the cv2.imshow function which is used to display images. The error is presented to imply that the image set for display must have a width and height.

This tutorial shows how the error happens and how it is solved through providing images with the ideal dimensions for display.

Understanding the error "OpenCV Error: (-215:Assertion failed)size.width>0 & size.height>0 in function imshow"

Generally, OpenCV is a crucial and common library in Python for processing images and performing computer vision tasks. The library has various methods and functions to deal with various tasks in images such as cropping, resizing, transforming, reading, detecting, and recognizing. In the library, cv2.imshow is common and used for showing images in a named window, and it closes when a key is pressed.

There are two parameters in the cv2.imshow function; that is the image and window name.

Window name is a string that names the window that the image is shown. The specific image is normally stored like a numpy array that has specific pixel values for the images. And depending on the number of channels, the image is shown as either colored or grayscale.

Here is an example of how the error is generated:

import cv2
import numpy as np
image = cv2.imread('image.jpg')

cv2.imshow('image', image)

cv2.waitKey(0)

The code above entails reading the file called 'image.jpg' with the help of the function cv2.imread. The function is integral in taking the name of the file as an argument and then returning the numpy array which in turn possesses the pixels of the image. At times, when the image file is non-existent or did not load as anticipated then we get a None value.

After that, we attempt to display the image in a window called 'image' with the help of a cv2.imshow function. The function creates a window with the said name and proceeds on to display. It also waits for a key to get pressed so as to close with the help of cv2.waitKey. We've set the wait time as 0 seconds.

However, we at times encounter the OpenCV Error: (-215:Assertion failed)size.width>0 & size.height>0 in function imshow as with the code above:

cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:967: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

The main reason for encountering the error is because the image we want displayed lacks a width and height, hence presenting zero values in terms of the display. Ideally, the cv2.imshow function expects an image with dimensions, and failure to which a window for displaying the image is not created.

Working Solutions for OpenCV Error: (-215:Assertion failed)size.width>0 & size.height>0 in function imshow

As mentioned earlier, an image with a non-zero width and height is needed for pixels to display.

Functions like the numpy.ones and numpy.zeros functions can be used to create images with any size or loading them from image files with the help of a cv2.imread function.

Alternatively, we can opt to check the shape of the image first before displaying it under the cv2.imshow function to manage the error effectively. That can be achieved with the use of the functions image.shape or numpy.shape. That provides us with the dimensions of the array which can then be compared with the first two elements in the tuple with zero using or. If the ultimate result is zero for either then the image is zero and hence prompts the warning; otherwise, the image is displayed.

Here are some examples of how to fix this error using different approaches:

Solution 1: Verify the Image Path

import cv2
import numpy as np

width, height = 640, 480
image = np.zeros((height, width, 3), dtype=np.uint8)

image[:] = (0, 0, 255)  # This sets the image color to red 

cv2.imshow('image', image)
cv2.waitKey(0)

The code involves the numpy.zeros function to create an image with a height of 480 pixels and a width of 640 pixels. The function outputs a numpy array with zeros that has the given data type and shape.

In the code, we use height, width,3 to specify a three-channeled color image as an argument specifying the shape and np.uint8 as the data type.

After that, we fill the image with the color red through assigning (0, 0, 255) to all pixels with the help of [:] notation.

Tip: OpenCV uses the blue, green, and red (BGR) format to display colored images so we start with passing blue, then green and finally red.

Solution 2: Upload then verify the image.

import cv2
import os
import numpy as np

filename = 'image.jpg'
image = cv2.imread(filename)

if not os.path.exists(filename):
    print(f'The file {filename} does not exist')
elif image is None:
    print(f'There was an error when loading the file {filename}')
else:
    cv2.imshow('image', image)
    cv2.waitKey(0)

Alternatively, we can check for the existence of an image file as shown through the code above. We use the function cv2.imread to load an image named 'image.jpg'. It takes the name of the function as an argument and then returns a numpy array that has got pixels of the images. The os.path.exists checks the existence of the file and either alerts of its absence or continues to display the said image.

Solution 3: Check Dimensions of the Image

import cv2
import numpy as np

image = np.zeros((0, 0, 3), dtype=np.uint8)

if image.shape[0] == 0 or image.shape[1] == 0:
    print('The image is empty and cannot be displayed')
else:
    cv2.imshow('image', image)
    cv2.waitKey(0)

The code entails creating an image with zero width and height with the help of numpy.zeros function. We then use the shape attribute to check the shape attribute of the image and hence determine whether it's empty. The shape attribute does so by returning tuples that have got the dimensions of the array.

An example case is with height, width, channels for the color of the image. We countercheck the first two elements with the value zero with 0, and if it is 0 then we cannot display and hence we display.

Solution 4: Opt for Try/Except statement to Check Image Validity

import cv2
filename = 'image.jpg'
try:
   image = cv2.imread(filename)
   if image is None:
       raise FileNotFoundError(f'Error: Can\'t upload image from file {filename}')
   cv2.imshow('image', image)
   cv2.waitKey(0)
except FileNotFoundError as e:
   print(str(e))
except Exception as e:
   print(f'An unexpected error occurred: {str(e)}')

The solution entail checking the image first, that if there are any errors in it, or they actually exist. When either of the cases is true then a apppropriate message is prompted from your code. Using the code will pinpoint the exact cause of the error.

Note: Creating and loading images that have big dimensions can take up significant memory and make your program slow. Use resize functions like cv2.resize to make the sizes of your images smaller when required.

Conclusion

The guide showed you the ways of solving the error "OpenCV Error: (-215:Assertion failed)size.width>0 & size.height>0 in function imshow". You can use the if else statement to check the image presence before displaying, load an image from a file, or use a valid image. Now at the end of the guide, hope you now have a clear understanding of how to fix the "OpenCV Error: (-215:Assertion failed)size.width>0 & size.height>0 in function imshow".

Enjoy your programming endeavors!

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Error: (-215:assertion failed) !ssize.empty() in function 'cv::resize'

Mark Thompson - Nov 30, 2023

How to Fix the TypeError: cannot use a string pattern on a bytes-like object Error in Python

Cornel Chirchir - Oct 29, 2023

How to fix the Taberror: inconsistent use of tabs and spaces

prince yadav - Sep 12, 2023

How to read a file and search specific word locations in Python

Brando - Nov 8, 2023

How to Fix 'jupyter' is Not Recognized as an Internal or External Command

mouyuan123 - May 26
chevron_left