Window freezing even after using waitKey() and destroyAllwindows() in Opencv - python

ENVIRONMENT
OS- mint Linux,
using opencv3.1,using spyder through anaconda
ISSUE
The code mentioned below opens a window of name frame and display the video captured through laptop camera.But when I press 'q', as mentioned in code, it should stop and terminate the window. But,here the window stops to display any further frames captured and do not terminates.then manually I force Quit the process.
What is the problem, why is it not terminating the window?
CODE:-
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

There is an open bug with this issue:
https://github.com/opencv/opencv/issues/7343
There are also similar questions without a good solution:
opencv videocapture hangs/freeze when camera disconnected instead of returning "False"
Try the solutions here: DestroyWindow does not close window on Mac using Python and OpenCV Calling several times waitKey seems to work for many people. You can try without the release() as well

I use macOS BigSur and also had this issue, I ended my code with the lines below and had no problem later:
video = cv.VideoCapture("your_video.mp4") # or 0 for your camera
while(video.isOpened()):
ret, frame = video.read()
if ret:
# Your frame manipulations
if cv.waitKey(1) & 0xFF == ord('q'):
video.release()
cv.waitKey(0)
cv.destroyAllWindows()
break
else:
break
video.release()
cv.waitKey(0)
cv.destroyAllWindows()
This will destroy the freezed window of the video but you have to press 3 times Q. One por stopping the video, one more for closing the window and one last for releasing the kernel if you're running on the Jupiter Notebook.
I also recommend to restart and clear all outputs in the kernel tab after applying the code because it could not work if so.

apparently this solves the issue, just include this line on top:
import pyautogui

Related

why doesn't python give me the option to close openCV window?

I have the following code that prints the following image. Why don't I have the option to close the window (small Red Cross missing in top left corner)?
import cv2
img = cv2.imread('/Users/natashabustnes/Desktop/geeks14.png')
cv2.imshow('image', img)
cv2.waitKey(0)
Your code displays window and waits for a keypress.
When you pressed a key, waitKey returned and the GUI froze because there's was no more instructions.
Do something like this instead.
import cv2
img = cv2.imread('/Users/natashabustnes/Desktop/geeks14.png')
cv2.imshow('image', img)
while True:
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
This code waits until you press the 'q' button before closing.
OpenCV by default does not support closing windows using the normal close button.

python opencv display gstreamer videotestsrc

I need to use GStreamer to deliver data to some OpenCV/Cuda classification and deep-learning systems.
The problem is that I'm new to the GStreamer and the Cuda, so I need to make some simple examples that combine as few elements as possible - here OpenCV and Gstreamer.
Now I only want GStreamer to deliver the "videotestsrc pattern=ball" to a cv.imshow() frame by frame in a loop
The problem is that I don't seem to be able to open the cv.VideoCapture() element - Properly because pipeline is wrong
I have spent several hours now and have "given up"
OpenCV is v3.4.0 - Compiled with GStreamer support
Python is 3.6.8
This is the code I have now -
I have googled and googled and tried many pipeline combination, but nothing enables me to open the videocapture element
#!/usr/bin/env python3
import cv2 as cv
cap = cv.VideoCapture("videotestsrc ! video/x-raw,framerate=20/1 ! appsink", cv.CAP_GSTREAMER)
# Commented out to continue to capture
# Evaluates true => app closes
#if not cap.isOpened():
# print('VideoCapture not opened')
# exit(0)
while(True):
ret, frame = cap.read()
print(ret) # 'False' when run
print(frame) # 'None' when run
cv.imshow('frame',frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv.destroyAllWindows()
cap.isOpened() returns False
cap.read() returns False, None

OpenCV freezes while trying to run VideoCapture(0)

I am playing around with OpenCV. I am following the documentation example (link)
I installed GTK webcam application on Ubuntu to validate that my webcam works. I am able to start the webcam and see the video feedback in GTK.
I added some print message in the tutorial code to see where I get.
I added a print before and after this line: cap = cv2.VideoCapture(0)
All I get, when running the Python file, is the print that I added before the cap = cv2.VideoCapture(0) and nothing else.
I tried increasing the waitKey to 20, 40, 100 but it didn't help.
Does anyone know why it does not get further and display the frame?
My code:
import numpy as np
import cv2
videoFeed = cv2.VideoCapture(0)
while (True):
ret, frame = videoFeed.read()
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('Feed', frame_gray)
if cv2.waitKey(10) & 0xFF = ord("q"):
break
videoFeed.release()
cv2.destroyAllWindows()
My setup:
Windows 10 host
Ubuntu 18.04 guest host
Integrated Webcam
Using PIP to install python module (numpy, scipi, pillow, open_cv, etc.)
Using venv python
You have a bug in your code at if cv2.waitKey(10) & 0xFF = ord("q"):. You should've gotten a syntax error here though.
import numpy as np
import cv2
videoFeed = cv2.VideoCapture(0)
while (True):
ret, frame = videoFeed.read()
if ret == False:
print("Failed to retrieve frame")
break
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('Feed', frame_gray)
if cv2.waitKey(10) & 0xFF == ord("q"):
break
videoFeed.release()
cv2.destroyAllWindows()
Tested your code. Works fine. Only other suggestion is to check whether your Ubuntu guest has permission to access your webcam. If you're using VirtualBox I remember seeing an option for this in the interface

What is the use of function destroyAllWindows() if the window automatically gets destroyed using waitKey() function?

#!/usr/bin/python3
import cv2
cam=cv2.VideoCapture(0)
checking if camera is working!!
cam.isOpened():
print("Working")
while(cam.isOpened()):
status,frame=cam.read()
cv2.imshow('camera1',frame)
if cv2.waitKey(1) & 0xFF==ord('q') :
break
Removing windows by calling below function
If i dont write this function then also it will run properly!!
cv2.destroyAllWindows()
cam.release()
Closes all the open GUI windows.

Python OpenCV - waitKey(0) does not respond?

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?
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
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)
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.
click on the image window(active) and then press and key, don't write in the terminal window.
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.
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.
Solved in Spyder under Ubuntu by following [Run]->[Configuration per file]->[Execute in an external system terminal].
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
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
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
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
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.

Categories