Closed jagannath-sahoo closed 6 years ago
Can not reproduce with latest master version in Ubuntu 16.04 with GTK 3.18.9 highgui backend and ffmpeg video capture backend.
maybe cv2.waitKey(0)
waits for a key stroke. what about cv2.waitKey(1)
Actually in the documentation its already specified that to use cv2.waitKey() after each call or cv2.imshow... It works for me.....
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
@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!
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
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.
Any progress on this ?
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
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).
As increase in waitKey() parameter with natural numbers , it freezes(Waits) for number of milliseconds to display next frame. Thank you @sarveshkhandu , @alalek
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).
I have the same issue in macOSX HighSierra. A friend with Ubuntu has the same problem.
@alalek why 'question invalid' label? seems more like a 'bug'
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.
When in MacOSX High Sierra, when running iPython notebook and opening image in cv2.imshow()
, the screen freezes.
@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.
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.
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()
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.
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()
`
I had this problem,too. Until I add cv2.destroyAllWindows()
in my code and it works.
Environment: python 3.7 on windows 10 family.
No solution I've seen works, including all mentioned here.
Python: 3.6.3 OpenCV: 4.1.0 Mac: High Sierra
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
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.
- 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
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.
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()
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. :)
- 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.
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.
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
Facing the same issue. After cv2.resize and cv2.cvtColor, cv2.imshow freezes but matplotlib.pyplot.imshow is working though grayscale still shows colors
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
this solved it for me,
import pyautogui
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!!
It's not only m1 notebooks. Also, I doubt anybody is gonna put in a fix because it's been several years now.
On Thu, May 6, 2021 at 10:28 PM Akella Niranjan @.***> wrote:
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!!
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/opencv/opencv/issues/7343#issuecomment-834077986, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAJPSZ5Q2XTYJU4SQGVYMWLTMN26BANCNFSM4CQ2YBWA .
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
Nice try, but no.
On Wed, Sep 8, 2021 at 3:55 AM ADI @.***> wrote:
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
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/opencv/opencv/issues/7343#issuecomment-915132551, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAJPSZ5YVO47FTWR72WNXDDUA46KNANCNFSM4CQ2YBWA .
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
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.
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
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?
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
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.
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)
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.
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.
I realize this isn't a support forum, but it was the first result Google search gave me. Try this:
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.
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