171

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?

top.eng
  • 1,828
  • 2
  • 13
  • 21
  • 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. – fmw42 Sep 14 '19 at 17:34
  • There is a tutorial with the basics of reading/displaying images in https://docs.opencv.org/master/dc/d2e/tutorial_py_image_display.html – kon psych Dec 23 '19 at 19:44
  • 1
    Be sure to add `cv2.waitKey(0)` after `cv2.imshow()` – fmw42 May 19 '21 at 18:53

20 Answers20

323

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.)

Falko
  • 17,076
  • 13
  • 60
  • 105
berak
  • 39,159
  • 9
  • 91
  • 89
  • 3
    check `print img` prints a correct numpy array, not a `NoneType` object. – Abid Rahman K Feb 17 '14 at 07:26
  • 7
    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. – Snesticle Oct 09 '15 at 20:35
  • Great. Now, how do I close it from the console? – hans Feb 02 '21 at 12:49
  • @hans - Try cv2.destroyAllWindows() – Pawel Kranzberg Mar 08 '21 at 09:13
  • 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 loading – Binu Nov 27 '21 at 01:22
  • 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() – Binu Nov 27 '21 at 01:25
  • 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: https://stackoverflow.com/questions/73575592/code-with-open-cv-in-python-process-is-launched-in-terminal-but-nothing-happens?noredirect=1#comment129927279_73575592 . Does someone have any idea about what goes wrong? – ecjb Sep 01 '22 at 22:07
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)
Akhorus
  • 2,233
  • 20
  • 24
  • 9
    You can close it afterwards by cv2.destroyAllWindows() – Zuza Jul 29 '15 at 10:39
  • For the QT implementation of highgui, startWindowThread() does nothing. https://github.com/opencv/opencv/blob/332c37f332733e5a2d717fc6eb4d605a304cda70/modules/highgui/src/window_QT.cpp#L621 – kusi Jan 04 '20 at 18:51
26

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)
Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
AdityaIntwala
  • 2,536
  • 1
  • 17
  • 17
  • 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. – Ahmadiah Oct 25 '19 at 20:19
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.

gandreadis
  • 3,004
  • 2
  • 26
  • 38
Dharma
  • 2,425
  • 3
  • 26
  • 40
9

add cv2.waitKey(0) in the end.

Pygirl
  • 12,969
  • 5
  • 30
  • 43
9

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://stackoverflow.com/a/50091712/8109630

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()
blue-zircon
  • 186
  • 1
  • 7
  • Good suggestion above. For me, it was hidden behind the web client. It didn't pop up. Thanks u – Pramit Apr 24 '22 at 20:12
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.

Community
  • 1
  • 1
rkdasari
  • 181
  • 3
  • 5
  • Please add the explanation provided at the link (a minimum at least) because links can go stale... Thanks :) – achedeuzot Jun 11 '14 at 21:11
  • Bump since this is the problem that I have but... "don't do this" is not the answer I am looking for =) – Eric Apr 26 '15 at 07:56
7

This is how I solved it:

import cv2
from matplotlib import pyplot
    
img = cv2.imread('path')
pyplot.imshow(img)
pyplot.show()
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Itay Guy
  • 111
  • 1
  • 6
  • This will show RGB images with the blue and red channels swapped (because OpenCV uses a bonkers definition or RGB that nobody else uses). – Cris Luengo Jul 02 '23 at 16:25
5

For me waitKey() with number greater than 0 worked

    cv2.waitKey(1)
Rambod
  • 2,355
  • 1
  • 14
  • 14
  • 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. – G.H. Jul 24 '23 at 01:37
3

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

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

works fine for me in IDLE.

iamchriskelley
  • 33
  • 1
  • 1
  • 4
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.

Joseph
  • 73
  • 10
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.

David Buck
  • 3,752
  • 35
  • 31
  • 35
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.

0

this solved it for me, import pyautogui

Bob Bobster
  • 95
  • 1
  • 9
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()
Salio
  • 1,058
  • 10
  • 21
-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.

  • 4
    The method with the lowercase key doesn't exist in the API. The code would throw an error as the method doesn't exist. – rayryeng Feb 14 '19 at 13:48
-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.

Ru Chern Chong
  • 3,692
  • 13
  • 33
  • 43
-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

  • 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. – Max Vollmer Sep 14 '19 at 16:27
-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 :)

FATEGH
  • 51
  • 1
  • 6
-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
Hans
  • 148
  • 2
  • 7