Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV only showing a black image when cv.imshow is used

Tags:

python

opencv

Hi whenever I use the cv2.imshow function all I get is a black rectangle like this:

enter image description here

My code is here, I am using python:

from cv2 import cv2
image = cv2.imread("scren.png")
cv2.imshow("image2", image)

I have tried using different file types as well as restarting my computer. Does anyone know how to fix this? Thanks.

like image 216
Redmaus Avatar asked Sep 06 '25 15:09

Redmaus


1 Answers

According to the documentation the imshow function requires a subsequent command to waitKey or else the image will not show. I believe this functionality has to do with how highgui works. So to display an image in Python using opencv you will always have to do something like this:

import cv2

image = cv2.imread(r"path\to\image")
cv2.imshow("image", image)
cv2.waitKey(0)

Note about imshow

This function should be followed by a call to cv::waitKey or cv::pollKey to perform GUI housekeeping tasks that are necessary to actually show the given image and make the window respond to mouse and keyboard events. Otherwise, it won't display the image and the window might lock up. For example, waitKey(0) will display the window infinitely until any keypress (it is suitable for image display). waitKey(25) will display a frame and wait approximately 25 ms for a key press (suitable for displaying a video frame-by-frame). To remove the window, use cv::destroyWindow.

See also.

like image 115
Isaac Berrios Avatar answered Sep 09 '25 18:09

Isaac Berrios