Python OpenCV - waitKey(0) does not respond?
Asked Answered
H

13

44

I'm using opencv 2.4.7 on ubuntu 12.04. I'm programming with python and I have a problem when i run this script:

import cv2

img = cv2.imread('347620923614738322_233985812.jpg')
cv2.namedWindow("window")
cv2.imshow("window", img)
cv2.waitKey(0)

The problem is that the script doesn't stop when I close the image. I searched information about waitKey and I found that using cv2.waitKey(0) is correct.

I don't understand, where is the problem?

Hussy answered 12/12, 2013 at 9:24 Comment(6)
"script don't stop " - what do you mean ? it should stop, if you press a key ( but probably not when you click the 'close' button )Pinpoint
I press a key and the script don't stopHussy
Did you close the window, then press a key? Or did you press the key while the window was open?Greece
I close the windows and then I press a key.Hussy
@Pinpoint I am on MacOS, i just press a key and script is not continuing execution. why ? According to the documentation, waitKey(0) will wait for any key press, there is no need to close the window manually.Bestow
I've been having the exact same issue. Windows 10 with VS Code. The picture window just stops responding and then python crashes. Then I can't run the code any more in VS Code. Have to shut down VS Code and repopen.Strontium
P
15

This code works for me from IDLE:

# -*- coding: utf-8 -*-

# Objectif : découvrir le fonctionnement d'opencv-python
# http://opencv-python-tutroals.readthedocs.org/en/latest/index.html


import numpy as np
import cv2

# Load an color image in grayscale
img = cv2.imread('Lena.tiff',0)
WINDOW_NAME = 'Image de Lena'
cv2.namedWindow(WINDOW_NAME, cv2.CV_WINDOW_AUTOSIZE)
cv2.startWindowThread()

# Display an image
cv2.imshow(WINDOW_NAME,img)
cv2.waitKey(0) 


cv2.destroyAllWindows()

Hope this helps for future readers.

Paleoecology answered 28/4, 2014 at 1:9 Comment(3)
If you are a Mac user, follow Teng Long's answer and add cv2.waitKey(1) after cv2.destroyAllWindows()Aft
cv2.destroyAllWindows() worked fine. Thank you for your answer.Tema
what if imshow is commented out and we want to save the video on exiting using ctrl+c or any other key ?Alien
S
59

I found that it works if i press the key whilst the window is in focus. If the command line is in focus then nothing happens

Sydel answered 4/2, 2015 at 13:43 Comment(3)
This certainly works...when u run the program from command line promptSue
Anyone know how to stop from the CLI? Ctrl + C does nothing there.Drollery
I've already closed the image window, but the python shell is not respondingCiro
B
18

Adding a cv2.waitKey(1) after you destroy the window should work in this case.

cv2.imshow('imgae',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
Brunswick answered 28/7, 2016 at 10:3 Comment(2)
You saved my day! Thank you so much!Aft
Thank you!, This worked on Python 3.11 with MacOS Sonoma!Urban
P
15

This code works for me from IDLE:

# -*- coding: utf-8 -*-

# Objectif : découvrir le fonctionnement d'opencv-python
# http://opencv-python-tutroals.readthedocs.org/en/latest/index.html


import numpy as np
import cv2

# Load an color image in grayscale
img = cv2.imread('Lena.tiff',0)
WINDOW_NAME = 'Image de Lena'
cv2.namedWindow(WINDOW_NAME, cv2.CV_WINDOW_AUTOSIZE)
cv2.startWindowThread()

# Display an image
cv2.imshow(WINDOW_NAME,img)
cv2.waitKey(0) 


cv2.destroyAllWindows()

Hope this helps for future readers.

Paleoecology answered 28/4, 2014 at 1:9 Comment(3)
If you are a Mac user, follow Teng Long's answer and add cv2.waitKey(1) after cv2.destroyAllWindows()Aft
cv2.destroyAllWindows() worked fine. Thank you for your answer.Tema
what if imshow is commented out and we want to save the video on exiting using ctrl+c or any other key ?Alien
C
14

click on the image window(active) and then press and key, don't write in the terminal window.

Concinnous answered 4/3, 2019 at 20:44 Comment(0)
K
7

Here a minimalistic code for best performance on all platforms:

import cv2

img = cv2.imread("image.jpg")
cv2.imshow("Window", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

And now some observations:

When the user wants to close the window through the press of the 0 key, he/she has to make sure that the 0 key is pressed whilst the window is in focus. Because as stated above, if the terminal is in focus nothing happens and code execution stucks at the cv2.waitKey(0) until the 0 key is pressed properly whilst the window is in focus.

Pressing the 0 key whilst the window is in focus is the right way to close the window and make sure that, once the window is destroyed in line cv2.destroyAllWindows() and the program ends, the user can get back the control of the terminal.

If the window is exited by mouse click, the window will be destroyed yes, but the user will very much end up in the situation of not being able to get back the control of the terminal. In this kind of situation the user may want to shut down the unresponsive terminal and open a new one.

Koeppel answered 4/1, 2019 at 21:27 Comment(0)
D
1

Try to execute the script directly from the Terminal works 100% for me but not from an IDE for example , i explain : I'm using fedora 20 and got the same problem, copying the first example from official opencv python tutorial, i'm using :

  • Fedora 20 64bit
  • Spyder IDE for python
  • Python Version 2.7.5
  • Fedora 64 bit
  • OpenCV 2.4.7

Here is the code for test

import cv2
img = cv2.imread('/path/image1.jpeg',0)
cv2.imshow('Display',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

When running this script using F5 from Spyder, it runs it using the embedded python terminal with this line :

runfile('/home/user/Workspace/test.py', wdir=r'/home/user/Workspace')

In this instance, cv2.waitKey(0) or cv2.waitKey(-1) are not working and windows remains opened after pressing keys with the code of the example Trying to close the windows will result in a "Not Responding , Force to Quit" Alert But when executing the script from Terminal , it works 100%

didn't found the problem origin , will update if i find it.

Descend answered 24/1, 2014 at 16:51 Comment(0)
E
1

Solved in Spyder under Ubuntu by following [Run]->[Configuration per file]->[Execute in an external system terminal].

Easterner answered 4/1, 2019 at 12:41 Comment(1)
you saved me! ThankssLiebman
B
1

Well the use cv2.waitKeyEx(0).

It runs in the same way and waits for your response until you revoke it.

I hope it helps. Nithesh varmma

Bellabelladonna answered 16/6, 2020 at 16:19 Comment(0)
G
0

cv2.waitKey(0) means that script is in infinity loop with 0 miliseconds wait after loop .only specified key can stop it.

you did not specified end of app condition.

Try this code: Using other keys for the waitKey() function of opencv

Got answered 12/12, 2013 at 10:21 Comment(0)
M
0

There is a problem with unix based system running opencv programs from python notebooks.

Check this alternate method My suggestion is to run code in python in terminal. You will not face any kind of problem

Copy the same code and save with filename.py

import cv2
input = cv2.imread('path_to_image.png')
cv2.imshow('Hello World', input)
cv2.waitKey(0)
cv2.destroyAllWindows()

then open specific directory and then open terminal

Steps:

Open Terminal
cd path/to/filename.py
source activate YOURPROFILE 
python filename.py

This will solve problem

https://youtu.be/8O-FW4Wm10s

Martinet answered 26/9, 2017 at 8:15 Comment(0)
R
0

This will work even if you close the window using the cross button on the window.

import numpy as np
import cv2

img = cv2.imread('arvid.jpg', 0)
cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.imshow('image', img)

while True:
    k = cv2.waitKey(30) & 0xFF
    if k == 27:         # wait for ESC key to exit
        cv2.destroyAllWindows()
    elif k == ord('s'):  # wait for 's' key to save and exit
        cv2.imwrite('arvid2.jpg', img)
        cv2.destroyAllWindows()
    if cv2.getWindowProperty("image", 0) == -1:
        break
Ressler answered 2/5, 2019 at 10:23 Comment(2)
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From ReviewQuietus
@RumitPatel fixedRessler
E
0

This problem occurs in some earlier version of opencv. So you just need to update opencv to the latest version. Version 4.0.0.21 worked for me. Use the command below.

update opencv to version 4.0.0.21.

Encage answered 2/6, 2020 at 12:27 Comment(0)
J
-1

There is nothing wrong with the code. It could be that the image file has been displayed. The * sign on the left of the JB cell will stay on till you click off the displayed image.

Jannet answered 6/3, 2023 at 19:7 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Footstool

© 2022 - 2024 — McMap. All rights reserved.