I'm on lubuntu 16.04, using OpenCV 3.2.0, Python 2.7 and encountering this error after a brief moment of imshow() displaying a window with my camera stream.
This error occurs randomly - the stream can run fine for half a minute before this happens, or it can happen right at the start when I first run the script.
ASSERT: "false" in file qasciikey.cpp, line 495
Aborted (core dumped)
My code appended below:
import numpy as np
import cv2
redcross_cascade = cv2.CascadeClassifier('rcrosscascade.xml')
cap = cv2.VideoCapture(2)
cv2.namedWindow('Haar', cv2.WINDOW_NORMAL)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
redcross = redcross_cascade.detectMultiScale(gray, 50, 50)
for (x,y,w,h) in redcross:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2)
cv2.imshow('Haar',img)
key = cv2.waitKey(1) & 0xff
if key == 27:
break
cap.release()
cv2.destroyAllWindows()
Would appreciate any assistance on this matter, thank you!
EDIT: I have identified the trigger for this error - movement from my usb optical mouse. Disconnecting the mouse prevents the error from resurfacing but I've yet to find a reason for this occurrence.
I was receiving this error when I was running my python program (which used cv2) via an SSH terminal. When I ran the program from the machine itself, the error went away. I assume this is due to some X11 issue.
I was receiving this error before. Different webcam has different performance.
My method is to write the cv2.waitKey function after cv2.imshow function.
I have encountered the same issue. My app is similar to yours. None of the fixes suggested here have worked for me. I found that if I start single stepping in debug mode through the cap.read(), I can continue running a full speed and the problem will go away, although this is not a good fix.
Related
I was using my cam through opencv and suddenly after restarting I ran my code it shows below error:
[ WARN:0] global /io/opencv/modules/videoio/src/cap_v4l.cpp (802) open VIDEOIO ERROR: V4L: can't open camera by index 0
Traceback (most recent call last):
File "test.py", line 20, in <module>
retval, buffer_img = cv2.imencode('.jpg', frame)
cv2.error: OpenCV(4.1.2) /io/opencv/modules/imgcodecs/src/loadsave.cpp:877: error: (-215:Assertion failed) !image.empty() in function 'imencode'
cap = cv2.VideoCapture(0) # here it throws an error
import json
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
retval, buffer_img = cv2.imencode('.jpg', frame)
resdata = base64.b64encode(buffer_img)
resdata = "data:image/png;base64,"+ str(resdata.decode("utf-8"))
PARAMS = {'image': resdata}
# Our operations on the frame come here
#gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
I also tried with cap = cv2.VideoCapture(1) but then it shows can't find camera
How can I fix this issue?
I got the same error. Try changing 0 to -1
cap = cv2.VideoCapture(-1)
This solved the issue.
I got the same problem when I created more than one instance of the cv2.VideoCapture(0). So check if your code contains multiple initializations or sections which call cv2.VideoCapture(0) more than once. I was facing this problem while running the flask server in debug mode because it called cv2.VideoCapture(0) twice.
import cv2
cap = cv2.VideoCapture(0)
cap2 = 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()
Error:
python3 debugCamera.py
[ WARN:0] global /io/opencv/modules/videoio/src/cap_v4l.cpp (887) open VIDEOIO(V4L2:/dev/video0): can't open camera by index
Most likely a permission issue on /dev/video0.
Check if you are part of "video" group.
id -a
if you don't see video in your group list add
sudo usermod -a -G video
for Ubuntu users:(20.04)
sudo usermod -a -G video $LOGNAME
Logout and log back in and try it.
I've encountered the same issue and attempted several methods like cv2.VideoCapture(-1) or cv2.VideoCapture(1) but without much success.
I succeeded after reading this article and disabling debug-mode
I had the same problem,
Just change 0 to 1,then to -1 and back again to 0.
Don't know why this worked for me.
I found a solution in https://github.com/opencv/opencv/issues/19527 where the video capture is inside the function instead of outside. That worked for me (ubuntu)
def frame_generation():
camera = cv2.VideoCapture(0) #resolved, correct position
while(True):
I will not go to that part What you are trying to do, here is just a block of code that can open your camera every time you run it,
python: 3.7.3
OpenCV: 4.1.0
import cv2
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()
In my case, I just reconnected cam to the usb port, and then it was solved! I think this error is caused by closing the window in the wrong way. Please check if there is any exception on the terminal right after closing the window.
I also had the same problem. Just changed it to 1 and it was perfectly working. I guess it's related to the number of camera devices you have used.
For example, I guess I have Iruin external camera as my first option which I didn't connect this time.
Here is the error and corrected code.
global /tmp/pip-req-build-f51eratu/opencv/modules/videoio/src/cap_v4l.cpp (890) open VIDEOIO(V4L2:/dev/video0): can't open camera by index
Code to change:
vid = cv2.VideoCapture(1)
The OP appears to be operating on a Raspberry PI. Raspberry is moving to a new system to manage cameras, so when the user upgrades the OS via sudo apt-get upgrade the camera system gets the new library and the legacy camera system is disabled. To enable the legacy camera system again, try
sudo raspi-config
Then select
3 Interface Options Configure connections to peripherals
then select
I1 Legacy Camera Enable/disable legacy camera support
and follow the directions to enable and then reboot.
Of course, this patch will only work for so long, as the legacy system has been deprecated.
I've also had this problem on Ubuntu
I've solved this by these comands
sudo adduser username video
sudo usermod -a -G video username
username - it is the name of your device
than write
id -a
and copy index from ()
for me it is 1000
so than just write:
camera = cv2.VideoCapture(1000)
Tried every anwser but only changing camera id from -1 to 1 and then back to 0 worked.
For Linux, make sure OpenCV is built using the WITH_V4L (with video for linux).
I have do everytime after restart or unplug usb camera and replug
chmod 777 /dev/video0
Don't know if this is still an issue.
In my case, I was getting the same error until I unplugged and plugged the usb camera. Even if I reboot, the error happened.
It's similar to someone said: my camera was already been captured.
The problem is that it was not used by my script, so it was hard to identify.
A few days before the issue, I installed the motion library, but just to test something and I didn't use it anymore. The motion starts at boot, so the camera was being captured by the service. That's why only the unplug-plug worked.
I uninstalled the library, and the error was gone.
video = cv2.VideoCapture(0,cv2.CAP_DSHOW)
This worked for me.
This issue is due to the interruption. Try to end the execution with the key 'q' for example, don't close the window suddenly.
I solved the same issue by opening terminal again and execute the same script again.
I'm trying to run the example from here
import cv2
def viewImage(image):
cv2.namedWindow('Display', cv2.WINDOW_NORMAL)
cv2.imshow('Display', image)
print('test')
cv2.waitKey(0)
cv2.destroyAllWindows()
def grayscale_17_levels (image):
high = 255
while(1):
low = high - 15
col_to_be_changed_low = np.array([low])
col_to_be_changed_high = np.array([high])
curr_mask = cv2.inRange(gray, col_to_be_changed_low,col_to_be_changed_high)
gray[curr_mask > 0] = (high)
high -= 15
if(low == 0 ):
break
image = cv2.imread('ombre_circle.png')
viewImage(image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
grayscale_17_levels(gray)
viewImage(gray)
Whenever I run the code I get the error:
Kernel Restarting
The kernel for main.ipynb appears to have died. It will restart automatically.
I when I comment out these lines:
#cv2.namedWindow('Display', cv2.WINDOW_NORMAL)
#cv2.imshow('Display', image)
the core runs and prints out 'test' and I don't get an error.
I'm using:
Ubuntu-server 18.04
Jupyter lab 1.1.3
opencv-python 4.1.1.26
I run this on a server not on my local environment
I found a workaround for this issue by displaying it with Matplotlib:
def viewImage(image):
plt.subplot(122)
plt.title("RGB")
plt.imshow(image)
plt.show()
image = cv2.imread('img/ombre_circle.png')
viewImage(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
grayscale_17_levels(gray)
viewImage3(cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB))
However this doesn't solve the issue and takes extra transformations/code so I would like to find a solution to display with opencv.
X11 forwarding is enabled.
I tried opening an SSH connection with the -Y and -C flag (via this question) but this doesn't fix it.
Any ideas what could be the issue?
IPython Github Issue
What I understand from the discussion is that it's a C-level linking or runtime error from the openCV code being run.
I faced the same problem, got solved by using matplotlib SO jupyternb crash
image=cv2.imread("the file")
cv2.imshow("test file", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
I encountered similar issue when I'm loading large tiff files. Same code works for small tiff files. You can look at this post to compress your image then display.
cv2.imshow() would cause Jupyter sessions
to crash: this post of the issue.
As a substitution, please consider using
from google.colab.patches import cv2_imshow on Google Colab.
I'm writing a program in python using OpenCV which detects the edges (Canny Edge Detector) from the footage my webcam records. I'm also using two track-bars in order to control the threshold values (in order for to understand how these values change the output of this edge detector).
The code I wrote is the following:
import cv2
import numpy as np
def nothing(x):
pass
img = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('cannyEdge')
cv2.createTrackbar("minVal", "cannyEdge", 0,100, nothing)
cv2.createTrackbar("maxVal", "cannyEdge", 100,200,nothing)
cap = cv2.VideoCapture(0)
while(True):
minVal = cv2.getTrackbarPos("minVal", "cannyEdge")
maxVal = cv2.getTrackbarPos("maxVal", "cannyEdge")
#capture frame by frame
ret, frame = cap.read()
cv2.imshow('frame', frame)
edge = cv2.Canny(frame,minVal,maxVal)
#display the resulting frame
cv2.imshow('frame', edge)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#When everything is done, release the capture
cap.release
cv2.destroyAllWindows()
This program is for educational purposes only as I'm currently learning to use OpenCV.
Every time I run the program above the code seems to be working just fine but I get the following Error:
GLib-GObject-CRITICAL **: g_object_unref: assertion 'G_IS_OBJECT (object)' failed
I've searched for the reason this error occurs but I haven't found anything helpful. My instinct tells me that my implementation for the trackbars is wrong and thus it's causing this error.
The tutorials I used are the following:
OpenCV tutorials - Canny Edge Detector
OpenCV tutorials - Trackbars
Does anybody know why this error occurs? Any help will be appreciated!
I am running Ubuntu 14.04, OpenCV 3.2.0 and Python 2.7.6
Try making the track bars and displaying the image in the same window and see if the error persists. I bet it shouldn't. Change: cv2.imshow('cannyEdge', edge)
Have you created another window named "frame"? If not, it looks like you should change 'frame' to 'cannyEdge':
cv2.imshow('cannyEdge', frame)
For my image processing algorithm I'm using python / OpenCV. The output of my algorithm shall be updated im the same window over and over again.
However sometimes the window freezes and doesn't update at all, but the algorithm is still running and updated the picture a multiple times in the meantime. The window turns dark gray on this Ubuntu machine.
Here is an excerpt of the involved code:
for i in range(0,1000):
img = loadNextImg()
procImg = processImg(img)
cv2.imshow("The result", procImg)
cv2.waitKey(1)
N.B.: processImg() takes about 1-2 s for its procedures. The line cv2.imshow(procImg) creates the window in first instance (i.e. there is no preceding invocation)
My suggestion is to use Matplotlib pyplot for displaying the image. I do it the following way.
import matplotlib.pyplot as plt
# load image using cv2....and do processing.
plt.imshow(cv2.cvtColor(image, cv2.BGR2RGB))
# as opencv loads in BGR format by default, we want to show it in RGB.
plt.show()
I know it does not solve the problem of cv2.imshow, but it solves our problem.
Increasing the wait time solves this issue. However in my opinion this is unnecessary time spent on sleeping (20 ms / frame), even though it's not much.
Changing
cv2.waitKey(1)
to
cv2.waitKey(20)
prevents the window from freezing in my case. The duration of this required waiting time may vary on different machines.
Just add cv2.destroyAllWindows() just after cv2.waitKey()
I have the very same issue and I noticed that the fps the window is updated is getting slower and slower until it freezes completely.
Increasing the waitKey(x) to something higher just extends the duration where the images are updated but when the time that cv2.imshow() needs to calculate exceeds the time from wait(Key) it just stops updating.
(Skip this complainment:)
I think the cv2.imshow() with waitKey() combination is a complete design error, why isn't imshow() just blocking until the UI is updated? That would make life so much easier without having to call waitKey() everytime...
P.S.: There is a possibility to start an own thread for opencv windows inside opencv:
import cv2
img = cv2.imread("image.jpg")
cv2.startWindowThread()
cv2.namedWindow("preview")
cv2.imshow("preview", img)
source: cv2.imshow command doesn't work properly in opencv-python
Well this doesn't work for me because I always get this errors when I run it:
(python3:1177): GLib-GObject-CRITICAL **: g_object_unref: assertion 'G_IS_OBJECT (object)' failed
Attempt to unlock mutex that was not locked
Aborted
Maybe you could try it and report if it is working for you?
Edit:
Okay I solved the problem for me by creating a separate script imshow.py:
import cv2
import os.path
while True:
if os.path.exists("image.pgm"):
image = cv2.imread("image.pgm")
if not image is None and len(image) > 0:
cv2.imshow("Frame", image)
cv2.waitKey(20)
And I am writing the image out in my other program with: cv2.imwrite("image.pgm", image)
And I am calling the script like this:
import subprocess
subprocess.Popen(["python3", "imshow.py"])
Although this is creating some dirty reads sometimes it is sufficient enough for me, a better solution would be to use pipes or queues between the two processes.
So what I think is going on here is that the window,(an element of the highGUI) which is still active after the first call to imshow, is waiting for some sort of response from your waitKey function, but is becoming inactive since the program is stuck calculating in either the processImg of loadNextImg functions. If you don't care about a slight waste of efficiency (i.e. you're not running on an embedded system where every operation counts), you should just destroy the window after waitKey, and recreate before imshow. Since the window no longer exists during the time you are processing and loading images, the highGUI wont get stuck waiting for a call from waitKey, and it won't become unresponsive.
If your window is going grey then it might be take more processing power. So try to resize image into smaller size image and execute. Sometimes times it freezes while running in ipython notebooks due to pressing any key while performing operation. I had personally executed your problem but I didn't get grey screen while doing it. I did executing directly using terminal. Code and steps are shown below.
import argparse
import cv2
import numpy as np
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())
# load the image, grab its dimensions, and show it
image = cv2.imread(args["image"])
(h, w) = image.shape[:2]
cv2.imshow("Original", image)
cv2.waitKey(0)
for i in range(0,1000):
image = cv2.imread(args["image"])
cv2.imshow("The result",image);
cv2.waitKey(0)
Run it in terminal:
source activate env_name
python Filename.py --image Imagename.png
This will get to your result in one window only(updating each time) without freezing and if you want seperate image in every new window then add .format(i) as given below. But Remember to run in terminal only not in jupyter notebooks.
You can check using terminal commands in this video link
https://www.youtube.com/watch?v=8O-FW4Wm10s
for i in range(0,1000):
image = cv2.imread(args["image"])
cv2.imshow("The result{}".format(i),image);
cv2.waitKey(0)
This may help to get you 1000 images separately.
try:
import cv2
except:
print("You need to install Opencv \n Run this command \n pip install python-opencv")
exit()
print('Press q to quit frame')
def viewer(name,frame):
while True:
cv2.imshow(name,frame)
if cv2.waitKey(10) & 0xff ==ord('q'):
break
return
cv2.destroyWindow(name)
Save this program and from now onwards, import this and use the function viewer to display any frame/image and your display windows will not hang or crash.
Add the following two lines of code after cv2.imshow() function,
cv2.waitKey()
cv2.destroyAllWindows()
You can use while loop to take burst images without freezing. Here is an example for taking 10 images. You can also try to increase waitkey number and sleep time in while loop. This work for me.
key = cv2.waitKey(1)
webcam = cv2.VideoCapture(0)
sleep(1)
while True:
try:
check, frame = webcam.read()
cv2.imshow("Capturing", frame)
key = cv2.waitKey(1)
img_counter = 0
if key & 0xFF == ord('s'): #press s to take images
while img_counter < 10:
check, frame = webcam.read()
cv2.imshow("Capturing", frame)
key = cv2.waitKey(1)
path = 'F:/Projects/' #folder path to save burst images
img_name = "burst_{}.png".format(img_counter)
cv2.imwrite(os.path.join(path, img_name), img=frame)
print("Processing image...")
img_ = cv2.imread(img_name, cv2.IMREAD_ANYCOLOR) #save as RGB color format
print("{} written!".format(img_name))
img_counter += 1
sleep(0.2)
webcam.release()
cv2.destroyAllWindows()
break
elif key == ord('q'): #press q to quit without taking images
webcam.release()
cv2.destroyAllWindows()
break
except(KeyboardInterrupt):
print("Turning off camera.")
webcam.release()
print("Camera off.")
print("Program ended.")
cv2.destroyAllWindows()
break
This is an old thread but in case someone else encounters it, normally the issue happen when you update opencv/opencv-contrib versions with pip and still some of their dependencies are unmet (for example you might have numpy already installed so it wont reinstall it and this causes it to crash in the back).
Simply do
pip install opencv-python opencv-contrib-python --no-cache --force-reinstall
Version 4.5.2.52 is working fine on ubuntu 20.04 and 18.04 with python > 3.8
My program generates a series of windows using the following code:
def display(img, name, fun):
global clicked
cv.NamedWindow(name, 1)
cv.ShowImage(name, img)
cv.SetMouseCallback(name, fun, img)
while cv.WaitKey(33) == -1:
if clicked == 1:
clicked = 0
cv.ShowImage(name, img)
cv.DestroyWindow(name)
I press "q" within the gui window to close it. However, the code continues to the next call of the display function and displays a second gui window while not closing the first. I'm using a Mac with OpenCV 2.1, running the program in Terminal. How can I close the gui windows? Thanks.
You need to run cv.startWindowThread() after opening the window.
I had the same issue and now this works for me.
Hope this helps for future readers. And there is also a cv2 binding (I advise to use that instead of cv).
This code works for me:
import cv2 as cv
import time
WINDOW_NAME = "win"
image = cv.imread("ela.jpg", cv.CV_LOAD_IMAGE_COLOR)
cv.namedWindow(WINDOW_NAME, cv.CV_WINDOW_AUTOSIZE)
initialtime = time.time()
cv.startWindowThread()
while (time.time() - initialtime < 5):
print "in first while"
cv.imshow(WINDOW_NAME, image)
cv.waitKey(1000)
cv.waitKey(1)
cv.destroyAllWindows()
cv.waitKey(1)
initialtime = time.time()
while (time.time() - initialtime < 6):
print "in second while"
The same issue happens with the C++ version, on Linux:
Trying to close OpenCV window has no effect
There are a few peculiarities with the GUI in OpenCV. The destroyImage call fails to close a window (atleast under Linux, where the default backend was Gtk+ until 2.1.0) unless waitKey was called to pump the events. Adding a waitKey(1) call right after destroyWindow may work.
Even so, closing is not guaranteed; the the waitKey function is only intercepted if a window has focus, and so if the window didn't have focus at the time you invoked destroyWindow, chances are it'll stay visible till the next destroyWindow call.
I'm assuming this is a behaviour that stems from Gtk+; the function didn't give me any trouble when I used it under Windows.
Sayem2603
I tried your solution and it worked for me - thanks! I did some trial and error and discovered that looping 4 times did the trick for me... or posting the same code 4 times just the same..
Further, I drilled down to:
cv2.destroyAllWindows()
cv2.waitKey(1)
cv2.waitKey(1)
cv2.waitKey(1)
cv2.waitKey(1)
or simply calling DestroyAllWindows and then looping the waitKey() code 4 times:
cv2.destroyAllWindows()
for i in range (1,5):
cv2.waitKey(1)
Worked as well. I am not savvy enough to know why this works exactly, though I assume it has something to do with the interruption and delay created by looping that code(?)
Matthäus Brandl said, above, that the third waitKey() worked for him, so perhaps it is slightly different on each system? (I am running Linux Mint with 3.16.1 kernel and python 2.7)
The delay, alone, doesn't explain it, as simply increasing the delay time on the waitKey() does not do the trick. (Also looped print("Hello") 1000 times instead of using wiatKey() just to see if the delay that created helped any - it did not.) Must have something more to do with how waitKey() interacts with window events.
OpenCV Docs say: "This function is the only method in HighGUI that can fetch and handle events, so it needs to be called periodically for normal event processing unless HighGUI is used within an environment that takes care of event processing."
Perhaps it creates an interrupt of sorts in the GUI display that allows the destroyAllWindows() action to process?
J
Here is what worked for me:
cv2.namedWindow("image")
cv2.imshow('image', img)
cv2.waitKey(0) # close window when a key press is detected
cv2.destroyWindow('image')
cv2.waitKey(1)
This solution works for me (under Ubuntu 12.04 with python open in the shell):
Re-invoke cv.ShowImage after the window is 'destroyed'.
If you are using Spyder ( Anaconda Package ) there is the problem.
None of the solutions worked for me.
I discovered that the problem wasn't the functions, but a problem on Spyder really. Try to use a texteditor plus running on terminal and you be fine using simply:
WINDOW_NAME = "win"
image = cv.imread("foto.jpg", 0)
cv.namedWindow(WINDOW_NAME, cv.CV_WINDOW_AUTOSIZE)
cv.startWindowThread()
cv.imshow(WINDOW_NAME, image)
cv.waitKey()
cv.destroyAllWindows()
I solved the problem by calling cv2.waitKey(1) in a for loop, I don't know why it worked but gets my job done, so I didn't bother myself further.
for i in range(1,10):
cv2.destroyAllWindows()
cv2.waitkey(1)
you are welcome to explain.
It seems that none of the above solutions 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()
Fiddling around with this issue in the python console I observed the following behavior:
issuing a cv2.imshow after cv2.destroyWindow sometimes closes the window. Albeit the old window pops up again with the next highgui call, e.g., cv2.namedWindow
the third call of cv2.waitKey after cv2.destroyWindow closed the window every time I tried. Additionally the closed window remained closed, even when using cv2.namedWindow afterwards
Hope this helps somebody.
(I used Ubuntu 12.10 with python 2.7.3 but OpenCV 2.4.2 from the 13.04 repos)
After searching aroung for some time, none of the solutions provided worked for me so since there's a bug in this function and I did not have time to fix it, I did not have to use the cv2 window to show the frames. Once a few frames have been saved, you can open the file in a different viewer, like VLC or MoviePlayer ( for linux ).
Here's how i did mine.
import cv2
threadDie = True # change this to false elsewhere to stop getting the video
def getVideo(Message):
print Message
print "Opening url"
video = cv2.VideoCapture("rtsp://username:passwordp#IpAddress:554/axis-media/media.amp")
print "Opened url"
fourcc = cv2.cv.CV_FOURCC('X','V','I','D')
fps = 25.0 # or 30.0 for a better quality stream
writer = cv2.VideoWriter('out.avi', fourcc,fps, (640,480),1)
i = 0
print "Reading frames "
while threadDie:
ret, img = video.read()
print "frame number: ",i
i=i+1
writer.write(img)
del(video)
print "Finished capturing video"
Then open the file with a different viewer, prabably in a nother function, like if you like vlc, you can start it and pass the saved file as a parameter. On the terminal, i would do this
vlc out.avi #out.avi is my video file being saved by the function above.
This worked for me on arch linux.
I had the same issue. The problem is that while(cap.isOpened()): loop does not finish so that I added below structure. When video has no frame in the following part, it returns ret values as False. Normally, I put destroyAllWindows command out of loop but I moved it into the loop. It works in my code properly.
while(cap.isOpened()):
ret, frame = cap.read()
if ret == False:
cap.release()
cv2.waitKey(1)
cv2.destroyAllWindows()
cv2.waitKey(1)
This worked for me in spyder :
import cv2 as cv
cv.namedWindow("image")
img = cv.imread("image_name.jpg")
cv.imshow("image",img)
cv.waitKey(5000) # 5 sec delay before image window closes
cv.destroyWindow("image")
Remember use only cv.waitKey(positive Integer) for this to work
cv2.imshow("the image I want to show ",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1) # to close the window.
The above code worked well for me.
I'm using Mac and python 3.7 .
Close the terminal, later close the window, it worked for me in Visual Studio Code in Windows; I made a task to compile and run the executable in the terminal, the program used my webcam to capture video and display it in a QT window, when I clicked the close button it didn't close, it reopened itself again and continued with the program until I closed the terminal and later could close the program window without it reopening again.