cv2.imshow command doesn't work properly in opencv-python
Asked Answered
G

20

173

I'm using opencv 2.4.2, python 2.7 The following simple code created a window of the correct name, but its content is just blank and doesn't show the image:

import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('ImageWindow',img)

does anyone knows about this issue?

Gibson answered 16/2, 2014 at 11:24 Comment(3)
Your file path may be wrong. Windows uses \ not /. I am not sure if OpenCV tolerates / on Windows? If fixing that does not help, then be sure your image is in the correct location and is a valid image.Skullcap
There is a tutorial with the basics of reading/displaying images in docs.opencv.org/master/dc/d2e/tutorial_py_image_display.htmlAssociative
Be sure to add cv2.waitKey(0) after cv2.imshow()Skullcap
I
328

imshow() only works with waitKey():

import cv2
img = cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('ImageWindow', img)
cv2.waitKey()

(The whole message-loop necessary for updating the window is hidden in there.)

Imaret answered 16/2, 2014 at 11:27 Comment(7)
check print img prints a correct numpy array, not a NoneType object.Liger
Just to be clear for posterity, under normal circumstances this would be the correct answer. Omitting the waitKey will (usually) result in exactly the behavior described in the question.Hibernal
Great. Now, how do I close it from the console?Neptunium
@Neptunium - Try cv2.destroyAllWindows()Nonrigid
If you are using jupyter notebook and trying this...found another answer in stackoverflow which works... # matplotlib interprets images in RGB format, but OpenCV uses BGR format # so to convert the image so that it's properly loaded, convert it before loadingObovoid
img = cv2.imread(path) # this is read in BGR format rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # this converts it into RGB plt.imshow(rgb_img) plt.show()Obovoid
I used this exact same code from terminal in python (just changed the path of the image), a python process is started but not image is displayed (and no error message neither). I posted a similar question there: #73576092 . Does someone have any idea about what goes wrong?Wheatear
H
57

I found the answer that worked for me here: http://txt.arboreus.com/2012/07/11/highgui-opencv-window-from-ipython.html

If you run an interactive ipython session, and want to use highgui windows, do cv2.startWindowThread() first.

In detail: HighGUI is a simplified interface to display images and video from OpenCV code. It should be as easy as:

import cv2
img = cv2.imread("image.jpg")
cv2.startWindowThread()
cv2.namedWindow("preview")
cv2.imshow("preview", img)
Halvorsen answered 11/4, 2015 at 23:7 Comment(2)
You can close it afterwards by cv2.destroyAllWindows()Ethelind
For the QT implementation of highgui, startWindowThread() does nothing. github.com/opencv/opencv/blob/…Chard
T
27

You must use cv2.waitKey(0) after cv2.imshow("window",img). Only then will it work.

import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0)
Trinia answered 28/10, 2015 at 11:8 Comment(1)
I would add you might need to install the python IDE to display the image and you also should look for the window sometimes does it not display it in front. The parenthesis in cv2.waitKey() I would assume is in milsecond and if you left blank it will display the image for ever.Aerosol
S
22

If you are running inside a Python console, do this:

img = cv2.imread("yourimage.jpg")

cv2.imshow("img", img); cv2.waitKey(0); cv2.destroyAllWindows()

Then if you press Enter on the image, it will successfully close the image and you can proceed running other commands.

Sew answered 10/8, 2018 at 3:0 Comment(2)
using semicolon in python is like blasphemy, but thanks. this worked for me in December 2021Mishmash
You can remove the semicolon and write them in different lines to produce the same effect.Sew
H
10

Method 1:

The following code worked for me. Just adding the destroyAllWindows() didn't close the window. Adding another cv2.waitKey(1) at the end did the job.

im = cv2.imread("./input.jpg")
cv2.imshow("image", im)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)

credit : https://mcmap.net/q/144672/-cv2-imshow-function-is-opening-a-window-that-always-says-not-responding-python-opencv

Note for beginners:

  • This will open the image in a separate window, instead of displaying inline on the notebook. That is why we have to use the destroyAllWindows() to close it later.
  • So if you don't see a separate window pop up, check if it is behind your current window.
  • After you view the image press a key to close the popped up window.

Method 2:

If you want to display on the Jupyter notebook.

from matplotlib import pyplot as plt
import cv2

im = cv2.imread("./input.jpg")
color = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
plt.imshow(color)
plt.title('Image')
plt.show()
Hyponitrite answered 21/8, 2020 at 8:50 Comment(1)
Good suggestion above. For me, it was hidden behind the web client. It didn't pop up. Thanks uSolipsism
G
9

add cv2.waitKey(0) in the end.

Glorygloryofthesnow answered 20/6, 2018 at 11:32 Comment(0)
M
8

I faced the same issue. I tried to read an image from IDLE and tried to display it using cv2.imshow(), but the display window freezes and shows pythonw.exe is not responding when trying to close the window.

The post below gives a possible explanation for why this is happening

pythonw.exe is not responding

"Basically, don't do this from IDLE. Write a script and run it from the shell or the script directly if in windows, by naming it with a .pyw extension and double clicking it. There is apparently a conflict between IDLE's own event loop and the ones from GUI toolkits."

When I used imshow() in a script and execute it rather than running it directly over IDLE, it worked.

Monophagous answered 11/6, 2014 at 20:54 Comment(2)
Please add the explanation provided at the link (a minimum at least) because links can go stale... Thanks :)Trumaine
Bump since this is the problem that I have but... "don't do this" is not the answer I am looking for =)Tims
B
8

This is how I solved it:

import cv2
from matplotlib import pyplot
    
img = cv2.imread('path')
pyplot.imshow(img)
pyplot.show()
Bilection answered 4/12, 2020 at 8:6 Comment(1)
This will show RGB images with the blue and red channels swapped (because OpenCV uses a bonkers definition or RGB that nobody else uses).Fibroma
F
5

For me waitKey() with number greater than 0 worked

    cv2.waitKey(1)
Finley answered 7/4, 2019 at 17:36 Comment(1)
This worked for me. In my case, I'm streaming from a Sony camera. Data is streamed as packets containing in image, rather than a continuous video stream, so each image is displayed one at a time. cv2.waitKey(1) (inside a while loop) displays each image until the next one is available.Freberg
M
3

You've got all the necessary pieces somewhere in this thread:

if cv2.waitKey(): cv2.destroyAllWindows()

works fine for me in IDLE.

Munich answered 21/4, 2017 at 20:5 Comment(0)
G
2

If you have not made this working, you better put

import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0)

into one file and run it.

Gullett answered 7/7, 2017 at 18:27 Comment(1)
(The actual answer here is the addition of cv2.waitKey(0) statement)Quintin
B
1

Doesn't need any additional methods after waitKey(0) (reply for above code)

import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('ImageWindow',img)
cv2.waitKey(0)

Window appears -> Click on the Window & Click on Enter. Window will close.

Blalock answered 28/3, 2020 at 14:47 Comment(0)
J
0

I also had a -215 error. I thought imshow was the issue, but when I changed imread to read in a non-existent file I got no error there. So I put the image file in the working folder and added cv2.waitKey(0) and it worked.

Janeenjanek answered 16/12, 2019 at 1:49 Comment(0)
B
0

this solved it for me, import pyautogui

Bergeron answered 3/3, 2021 at 13:40 Comment(0)
S
0

For 64-bit systems to prevent errors, use this end cv2.waitKey(1) add 0xFF.

example:

import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0) & 0xFF 
cv2.destroyAllwindows()

You can also use the following command for more control by stopping the program by pressing the Q button.

import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
if cv2.waitKey(0) & 0xFF == ord('Q'):
    break
cv2.destroyAllwindows()
Sparry answered 5/6, 2021 at 15:8 Comment(2)
& 0xFF has no effect in your first code block.Deshabille
And the break in the second code block doesn’t have any effect either.Fibroma
F
-1

If you choose to use "cv2.waitKey(0)", be sure that you have written "cv2.waitKey(0)" instead of "cv2.waitkey(0)", because that lowercase "k" might freeze your program too.

Fandango answered 24/7, 2017 at 14:55 Comment(1)
The method with the lowercase key doesn't exist in the API. The code would throw an error as the method doesn't exist.Kotz
D
-1

error: (-215) size.width>0 && size.height>0 in function imshow

This error is produced because the image is not found. So it's not an error of imshow function.

Dionnadionne answered 30/3, 2018 at 14:4 Comment(1)
Not relevant to this question.Kotz
H
-1

I had the same 215 error, which I was able to overcome by giving the full path to the image, as in, C:\Folder1\Folder2\filename.ext

Hanker answered 14/9, 2019 at 16:5 Comment(1)
What "same 215 error"? Nowhere in OPs question is any error mentioned. Also OP is using a full path to the image, so I don't see how this answers the question.Tamqrah
K
-1
import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0)
cv2.destroyAllwindows()

you can try this code :)

Kurdistan answered 19/5, 2021 at 17:49 Comment(0)
B
-1

If you still want to have access to the console while looking at the pictures. You can also pass a list of images which will be shown one after another.

from threading import Thread
from typing import Union
import numpy as np
import cv2
from time import sleep


def imshow_thread(
    image: Union[list, np.ndarray],
    window_name: str = "",
    sleep_time: Union[float, int, None] = None,
    quit_key: str = "q",
) -> None:
    r"""
    Usage:

    import glob
    import os
    from z_imshow import add_imshow_thread_to_cv2 #if you saved this file as z_imshow.py
    add_imshow_thread_to_cv2() #monkey patching
    import cv2
    image_background_folder=r'C:\yolovtest\backgroundimages'
    pics=[cv2.imread(x) for x in glob.glob(f'{image_background_folder}{os.sep}*.png')]
    cv2.imshow_thread( image=pics[0], window_name='screen1',sleep_time=None, quit_key='q') #single picture
    cv2.imshow_thread( image=pics, window_name='screen1',sleep_time=.2, quit_key='e') #sequence of pics like a video clip

        Parameters:
            image: Union[list, np.ndarray]
                You can pass a list of images or a single image
            window_name: str
                Window title
                (default = "")
            sleep_time: Union[float, int, None] = None
                Useful if you have an image sequence.
                If you pass None, you will have to press the quit_key to continue
                (default = None)
            quit_key: str = "q"
                key to close the window
        Returns:
            None

    """
    t = Thread(target=_cv_imshow, args=(image, window_name, sleep_time, quit_key))
    t.start()


def _cv_imshow(
    cvimages: Union[list, np.ndarray],
    title: str = "",
    sleep_time: Union[float, int, None] = None,
    quit_key: str = "q",
) -> None:

    if not isinstance(cvimages, list):
        cvimages = [cvimages]

    if sleep_time is not None:
        for cvimage in cvimages:
            cv2.imshow(title, cvimage)
            if cv2.waitKey(1) & 0xFF == ord(quit_key):
                break
            sleep(sleep_time)
    else:
        for cvimage in cvimages:
            cv2.imshow(title, cvimage)
            cv2.waitKey(0)
            cv2.destroyAllWindows()
            cv2.waitKey(1)
    cv2.destroyAllWindows()


def add_imshow_thread_to_cv2():
    cv2.imshow_thread = imshow_thread  # cv2 monkey patching
    # You can also use imshow_thread(window_name, image, sleep_time=None)
    # if you dont like monkey patches
Bombsight answered 16/10, 2022 at 2:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.