opencv: cv2.imshow() freezes

When I call for imshow() from python it automatically freeze… it always happen when i try for reading video file or using VideoCapture()… please try to help me… this is my code

import numpy as np
import cv2

cap = cv2.VideoCapture(0)


while cap.isOpened():
    flags, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('img', gray)
    if cv2.waitKey(0):
        break

cap.release()
cv2.destroyAllWindows()

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 48 (4 by maintainers)

Most upvoted comments

Nope, it is just incorrect usage of OpenCV. To make window “alive”, we should handle events from OS (usually in waitKey()). For example, Python IDE just blocks our code to execute (like any other Python/C++ debuggers).

Usage questions should go to Users OpenCV Q/A forum: http://answers.opencv.org This tracker is for issues and bugs that needs fix in OpenCV.

cv2.waitKey(0) will display the window infinitely until any keypress. Maybe that is why it is freezing. Try cv2.waitkey(1): It should wait for 1 millisecond and then display the next image. https://docs.opencv.org/2.4/modules/highgui/doc/user_interface.html?highlight=waitkey

maybe cv2.waitKey(0) waits for a key stroke. what about cv2.waitKey(1)

your code freezes when camera gets on. There is some mistake in line 11 where you made the break condition. This is not the right way fr breaking video read loop in opencv it will not work . The following you can use to do your task:

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while cap.isOpened():
    flags, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('img', gray)
    key = cv2.waitKey(0) & 0xFF
    if key == ord("q"):
        break
cap.release()
cv2.destroyAllWindows() 

Hope it helps. Feel free to report if you encounter any mistake

Solved (sort of, sometimes)

It seems the issue is isolated to the Notebook’s iffy interaction with the Python GUI. Note, its not actually frozen because if you attempt to run again, or add more code below and continue execution, it will work fine and new calls to imshow will work, replacing the hung window. It almost seems like its a natural byproduct of the “live” nature of notebook, essentially putting in a breakpoint after your last code block as if awaiting more instruction.

The fix that worked for me is adding a cv2.waitKey(1) after the call to destroy the windows.

cv2.imshow(window_name, image)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)

Sourced from Stack Overflow

It works if not using ipython notebook. Otherwise freezes no matter.

Sent from my iPhone

On Jun 13, 2018, at 5:33 AM, Harsh Thaker notifications@github.com wrote:

@benedictchen try this way:

cv2.imshow(‘image’, im) cv2.waitKey(0) cv2.destroyAllWindows()

hit key to exit then. Closing the window will keep it still running and eventually, on quitting python kernel will die.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub, or mute the thread.

Nope, it is just incorrect usage of OpenCV. To make window “alive”, we should handle events from OS (usually in waitKey()). For example, Python IDE just blocks our code to execute (like any other Python/C++ debuggers).

Usage questions should go to Users OpenCV Q/A forum: http://answers.opencv.org This tracker is for issues and bugs that needs fix in OpenCV.

Yeah this issue most definitely IS a bug. No rational user would ever expect an innocent command like cv2.imshow() to totally crash their Jupyter session and freeze their OS. To expect otherwise is the sign of a deranged contributor. The dreaded cv2.imshow() freezing your system can only be fixed by preemptively adding cv2.waitKey(0). I’m not sure which is more ridiculous: the nature of this bug, or the guy who thinks this is legitimately not a bug.

No solution I’ve seen works, including all mentioned here.

Python: 3.6.3 OpenCV: 4.1.0 Mac: High Sierra

I’m having the same problem with the code posted by propellerhat. I’m using MacOS 10.12.5, Anaconda 4.4.0, and installed OpenCV 3 based on instructions from http://www.pyimagesearch.com/2016/11/28/macos-install-opencv-3-and-python-2-7/ . Everything works fine except I get title-bar-only windows.

Actually in the documentation its already specified that to use cv2.waitKey() after each call or cv2.imshow… It works for me…

Can not reproduce with latest master version in Ubuntu 16.04 with GTK 3.18.9 highgui backend and ffmpeg video capture backend.

the below code waits for user to press any key and then closes the image window:

cv2.imshow( ‘title’ , img) cv2.waitKey(0)
cv2.destroyAllWindows()

Sample from issue’s description is not applicable for video streams - it works well for static images, but as mentioned @sturkmen72 @sarveshkhandu waitKey() call should have non-zero parameter to avoid “freezing”.

Sample by @propellerhat with “window with no content” problem probably related to empty imshow() input (from PIL.ImageGrab). Need to validate this case and/or to check this sample with some generated input (try generating input via np.array with different colors) without external dependencies (PIL).

this solved it for me, import pyautogui

@alalek why ‘question invalid’ label? seems more like a ‘bug’

screen shot 2017-05-26 at 23 30 55 I'm having the same issue. I'm following along with "Python plays GTA V" video series. I have the call to waitkey() after imshow(). I'm copying his code exactly. I get a window with no content, just the titlebar. The only difference is that he is developing his code on Windows and it works fine.

macOS 10.12.5 (Sierra) Mid 2012 Retina 8GB RAM launching from iTerm2 I followed this guide to get my env working: http://www.pyimagesearch.com/2016/11/28/macos-install-opencv-3-and-python-2-7/ Here is the code I’m running:

import numpy as np
from PIL import ImageGrab
import cv2
import time

last_time = time.time()
while(True):
  screen = np.array(ImageGrab.grab(bbox=(0, 40, 800, 640)))

  print('Loop took {} seconds'.format(time.time() - last_time))
  last_time = time.time()
  cv2.imshow('window', screen)
  if cv2.waitKey(25) & 0xFF == ord('q'):
    cv2.destroyAllWindows()
    break

I tried toying around with a few things (like having no bbox, calling imshow and waitKey() just once, etc.).

Thanks in advance for any help or comments. I appreciate the opencv work

@benedictchen try this way:

cv2.imshow(‘image’, im) cv2.waitKey(0) cv2.destroyAllWindows()

hit key to exit then. Closing the window will keep it still running and eventually, on quitting python kernel will die.