Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cv2.imshow() freezes #7343

Closed
jagannath-sahoo opened this issue Sep 26, 2016 · 48 comments
Closed

cv2.imshow() freezes #7343

jagannath-sahoo opened this issue Sep 26, 2016 · 48 comments
Labels
category: highgui-gui category: python bindings platform: ios/osx question (invalid tracker) ask questions and other "no action" items here: https://forum.opencv.org

Comments

@jagannath-sahoo
Copy link

jagannath-sahoo commented Sep 26, 2016

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()
@mshabunin
Copy link
Contributor

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

@sturkmen72
Copy link
Contributor

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

@jagannath-sahoo
Copy link
Author

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

@arpit1997
Copy link

arpit1997 commented Sep 30, 2016

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

@BelalC
Copy link

BelalC commented Mar 7, 2017

@arpit1997 + others - I'm getting a similar issue when trying to run the example code from the OpenCV documentation for capturing video from camera, in an interactive python session (ipython/jupyter notebook). The window displaying video pops up normally, but when I press 'q' to exit it freezes. There is no problem when running a script from terminal so I'm thinking it's an issue with interactivity.

I'm running:
macOS Sierra 10.12.2
Python 3.5.2
OpenCV 3.1.0

Example code from OpenCV

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

I tried inserting this line too but no difference:
cv2.startWindowThread()

Would really appreciate any advice/help!

@propellerhat
Copy link

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

@dcm5458521
Copy link

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.

@BernhardSchlegel
Copy link

Any progress on this ?

@sarveshkhandu
Copy link

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

@alalek
Copy link
Member

alalek commented Dec 13, 2017

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

@ntirupathirao18
Copy link

ntirupathirao18 commented Feb 14, 2018

As increase in waitKey() parameter with natural numbers , it freezes(Waits) for number of milliseconds to display next frame. Thank you @sarveshkhandu , @alalek

@surajsirohi1008
Copy link

surajsirohi1008 commented Feb 24, 2018

Which IDE are you using? I was facing the same problem when I was using the default IDE (IDLE) but then I installed PyCharm, it works perfectly now, the image window closes instantly, also use waitkey(0).

@fredguth
Copy link

I have the same issue in macOSX HighSierra. A friend with Ubuntu has the same problem.

@fredguth
Copy link

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

@alalek
Copy link
Member

alalek commented Mar 28, 2018

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.

@benedictchen
Copy link

When in MacOSX High Sierra, when running iPython notebook and opening image in cv2.imshow(), the screen freezes.

@harshthaker
Copy link

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

@benedictchen
Copy link

benedictchen commented Jun 13, 2018 via email

@yinglinglow
Copy link

As @benedictchen mentioned, nothing worked for me if I run it on Jupyter Notebook (the window hangs when closing and you need to force quit Python to close the window).

I am on macOS High Sierra 10.13.4, Python 3.6.5, OpenCV 3.4.1.

The below code works if you run it as a .py file (source: https://www.learnopencv.com/read-write-and-display-a-video-using-opencv-cpp-python/). It opens the camera, records the video, closes the window successfully upon pressing 'q', and saves the video in .avi format.

    import cv2
    import numpy as np
     
    # Create a VideoCapture object
    cap = cv2.VideoCapture(0)
     
    # Check if camera opened successfully
    if (cap.isOpened() == False): 
      print("Unable to read camera feed")
     
    # Default resolutions of the frame are obtained.The default resolutions are system dependent.
    # We convert the resolutions from float to integer.
    frame_width = int(cap.get(3))
    frame_height = int(cap.get(4))
     
    # Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
    out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))
     
    while(True):
      ret, frame = cap.read()
     
      if ret == True: 
         
        # Write the frame into the file 'output.avi'
        out.write(frame)
     
        # Display the resulting frame    
        cv2.imshow('frame',frame)
     
        # Press Q on keyboard to stop recording
        if cv2.waitKey(1) & 0xFF == ord('q'):
          break
     
      # Break the loop
      else:
        break 
     
    # When everything done, release the video capture and video write objects
    cap.release()
    out.release()
     
    # Closes all the frames
    cv2.destroyAllWindows() 

@ganesh-ms
Copy link

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

Worked for me as well.

@shivamshukl4
Copy link

Hey please help me, I am facing problem while running my program.
The camera indicator lights up but no camera window popped up.
I am using python 3.7 on windows 10 pro.

`
import cv2
import sys

faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
video_capture = cv2.VideoCapture(0)

while True:

retval, frame = video_capture.read()

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(35, 35)
)

for (x, y, w, h) in faces:
    cv2.rectangle(frame, (x, y), (x+w, y+h), (50, 50, 200), 2)

cv2.imshow('Video', frame)

if cv2.waitKey(1) & 0xFF == ord('q'):
   sys.exit() 

`

@Nomiracle
Copy link

I had this problem,too. Until I add cv2.destroyAllWindows() in my code and it works.
Environment: python 3.7 on windows 10 family.

@sdcharle
Copy link

sdcharle commented Sep 1, 2019

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

Python: 3.6.3
OpenCV: 4.1.0
Mac: High Sierra

@chamarthi-ks
Copy link

I have been working on opencv with
python:3.6.9
opencv: 4.1.1
jupyter notebook
I have tried all the possible solutions nothing works.
whenever i use imshow() it open and freeze I had to re-start the kernel.
can you help me with the solution in mac

@pcgeek86
Copy link

  • MacBook Pro 2018 w/ i7 CPU
  • MacOS Catalina
  • Python 3.7.4
  • OpenCV 4.1.1
  • Visual Studio Code (VSCode) September 2019 release (1.39.2)

cv2.imshow() is causing the system to hang and use up tons of CPU in the Python process. It's nearly impossible to work with.

@chamarthi-ks
Copy link

  • MacBook Pro 2018 w/ i7 CPU
  • MacOS Catalina
  • Python 3.7.4
  • OpenCV 4.1.1
  • Visual Studio Code (VSCode) September 2019 release (1.39.2)

cv2.imshow() is causing the system to hang and use up tons of CPU in the Python process. It's nearly impossible to work with.

you can use "import matplotlib.pyplot as plt"
instead of cv2.imshow() use "plt.imshow()"
this should work

@cpoptic
Copy link

cpoptic commented Nov 18, 2019

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.

@Hafsa1992
Copy link

Hafsa1992 commented Jan 20, 2020

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

@kanitmann
Copy link

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

Just make sure your other instances of python are closed. cv2.imshow uses your IDLE window to give output of your camera/video player feed. So, if any other instance/window is open, python(or jupyter notebook will run into a priority error and crash. Also if you want to close your output window, don't close it using the red cross button, but instead press any key on the keyboard. Hope these little tips solve your error. :)

@kanitmann
Copy link

  • MacBook Pro 2018 w/ i7 CPU
  • MacOS Catalina
  • Python 3.7.4
  • OpenCV 4.1.1
  • Visual Studio Code (VSCode) September 2019 release (1.39.2)

cv2.imshow() is causing the system to hang and use up tons of CPU in the Python process. It's nearly impossible to work with.

you can use "import matplotlib.pyplot as plt"
instead of cv2.imshow() use "plt.imshow()"
this should work

But it won't work if you are changing the image presets, like changing it into Grayscale. The image would still show greenish color in output for grescaled images.

@Youlenda
Copy link

Youlenda commented Mar 2, 2020

hi, I had some problem with cv2.imshow() too and with plt.imshow() the problem solved. but my task is hand detection and it should detect hand in a real-time video not separated frames.

@akrsrivastava
Copy link

How come cv2.imshow() does not freeze on PyCharm, but freezes on VS Code? On Pycharm, cv2.imshow() opens in a new window without freezing Pycharm console

@Tannishak
Copy link

Facing the same issue. After cv2.resize and cv2.cvtColor, cv2.imshow freezes but matplotlib.pyplot.imshow is working though grayscale still shows colors

@Darshan-20310597
Copy link

How come cv2.imshow() does not freeze on PyCharm, but freezes on VS Code? On Pycharm, cv2.imshow() opens in a new window without freezing Pycharm console

Try the same on Jupyter Notebook? It hangs

@RubenBenBen
Copy link

this solved it for me,
import pyautogui

@niranjanakella
Copy link

The cv2.imshow() only tends to freeze when I use Jupyter (ipynb) notebooks on my M1 MacBook Air. But where are if I run the complete code as a .py script in any IDE it is running perfectly fine.

img = cv2.imread('img.png')
# cv2.imshow('image',img)
while(1):
    cv2.imshow('img',img)
    k = cv2.waitKey(33)
    if k==27:    # Esc key to stop
        break
    elif k==-1:  # normally -1 returned,so don't print it
        continue

The above code is running perfectly fine!!

@benedictchen
Copy link

benedictchen commented May 7, 2021 via email

@totallynotadi
Copy link

your video playback probably freezes because you have 0 in your waitkey call. the cv2 docs say that 0 means it will wait infinitely until any keypress occurs, so you should try having 32 in your waitkey function as a value i have deduced that works well. the use of the waitkey call is to take any key input while showing the frames. 0 means waiting infinitely until any event occurs and anything above zero means waiting for that many miliseconds. hope that helped

@benedictchen
Copy link

benedictchen commented Sep 9, 2021 via email

@seguri
Copy link

seguri commented Sep 24, 2021

At least I'm glad it's not just me. I couldn't understand why my code, which runs perfectly from shell or from PyCharm, is always freezing my Jupyter notebook. All the code suggestions in this thread did not help. How can this still be a thing after 5 years, in such a famous project?

macOS 11.6
python 3.9.7
opencv 4.5.3

@sleeptil3
Copy link

sleeptil3 commented Oct 24, 2021

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

@kriti-banka
Copy link

OpenCV(4.5.4-dev) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:1274: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage

In line cv2.imshow(" ", img)

how should I overcome this error?

@MhdKAT
Copy link

MhdKAT commented Apr 15, 2022

OpenCV(4.5.4-dev) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:1274: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage

In line cv2.imshow(" ", img)

how should I overcome this error?
@kriti-banka
If you have opencv-python-headless installed try this :

  • pip uninstall opencv-python-headless -y
  • pip install opencv-python

@Aasimkhurshid
Copy link

I am running system:
Macbook pro M1,
macOS Monterey,
OpenCV 4.6.0,
Python 3.9.13
This solved for me.
You may also try importing the matplotlib and using the matplotlib.use('TkAgg'), if you have all the libraries installed:
import numpy as np
import cv2
import matplotlib
cap = cv2.VideoCapture(0)
while cap.isOpened():
flags, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
matplotlib.use('TkAgg')
cv2.imshow('img', gray)
if cv2.waitKey(0):
break

cap.release()
cv2.destroyAllWindows()

This worked for me after I installed opencv-python, opencv-python-headless.
I hope this helps.

@yash7251
Copy link

yash7251 commented Nov 5, 2022

it worked for me.
code:

cv2.namedWindow("image")
cv2.imshow('image', img)
cv2.waitKey(0) # close window when a key press is detected
cv2.destroyWindow('image')
cv2.waitKey(1)

@leo002
Copy link

leo002 commented Nov 12, 2022

I realized opencv was installed twice on my machine, one coming from apt-get and the other from pip3 (python package manager). What worked for me is to uninstall the pip3 opencv package.

@puntofisso
Copy link

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

This solved it for me too.

I understand it's not a "bug bug", but I think it's still something that should be treated as such or documented, in that to be pragmatic many users are likely try this code in a jupyter/ipython environment first.

@robertlugg
Copy link

I realize this isn't a support forum, but it was the first result Google search gave me. Try this:

  • Do not close the new window using the X button
  • Click on the new window to activate it. Then press bar.
  • Use:
cv2.waitKey(0)
cv2.destroyAllWindows()

, as others have suggested.

My guess is the problem during interactive sessions is the python prompt forces focus to it, so hitting a key is directed towards the frozen command line and not the new imshow window.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
category: highgui-gui category: python bindings platform: ios/osx question (invalid tracker) ask questions and other "no action" items here: https://forum.opencv.org
Projects
None yet
Development

No branches or pull requests