Related
I check other question on google or stackoverflow, they are talking about run cv2.imshow in script, but my code run in jupyter notebook.
Here is my configuration:
ubuntu 16.4x64
python 3.5
opencv 3.1.0
I start a jupyter notebook: here is the code I put it notebook:
%pylab notebook
import cv2
cvim2disp = cv2.imread('data/home.jpg')
cv2.imshow('HelloWorld', cvim2disp)
cv2.waitKey() #image will not show until this is called
cv2.destroyWindow('HelloWorld') #make sure window closes cleanly
When I execute these code. image will show in a pop up window, but I can not close this window by clicking the x on the top right corner, and a moment later, system will prompt me that the window is not responding, it will give me 2 choices: "wait" , "fore quit". if I hit wait, then It will show the same prompt later, If I hit 'fore quit', then the jupyter notebook kernel die and I have to start over.
I google around, many solution suggest that I should add this code
cv2.startWindowThread()
before imshow, but situation get worse, the kernel hang forever!.
anybody have some idea what's going on.
Here is the pic of my error:
%matplotlib inline
#The line above is necesary to show Matplotlib's plots inside a Jupyter Notebook
import cv2
from matplotlib import pyplot as plt
#Import image
image = cv2.imread("input_path")
#Show the image with matplotlib
plt.imshow(image)
plt.show()
I was having a similar problem, and could not come to a good solution with cv2.imshow() in the Jupyter Notebook. I followed this stackoverflow answer, just using matplotlib to display the image.
import matplotlib.pyplot as plt
# load image using cv2....and do processing.
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
# as opencv loads in BGR format by default, we want to show it in RGB.
plt.show()
The API documentation for cv2.waitKey() notes the following:
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.
So perhaps calling the function in an endless loop would make the window responsive? I haven't tested this, but maybe you would like to try the following:
import cv2
cvim2disp = cv2.imread('data/home.jpg')
cv2.imshow('img', cvim2disp)
while(True):
k = cv2.waitKey(33)
if k == -1: # if no key was pressed, -1 is returned
continue
else:
break
cv2.destroyWindow('img')
This will help you understand what is happening:
import cv2
cvim2disp = cv2.imread('data/home.jpg')
cv2.imshow('HelloWorld', cvim2disp)
cv2.waitKey(0)
cv2.destroyWindow('HelloWorld')
waitKey(0) method is waiting for an input infinitely. When you see a frame of the corresponding image, do not try to close the image using close in top right corner.
Instead press some key. waitkey method will take that as an input and it will return back a value. Further you can also check which key was pressed to close the frame.
Additionally waitKey(33) will keep the frame active for 33 ms and then close it automatically.
destroyWindow() will destroy the current frame if there.
destroyAllWindows() will destroy all the frames currently present.
This will solve.
if your facing problem in google collab ,you can use this patch
from google.colab.patches import cv2_imshow
cv2_imshow(img)
%matplotlib inline
from matplotlib import pyplot as plt
img = cv2.imread(valid_img_paths[1])
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
The following code works fine in Jupyter to show one image
%matplotlib inline
import cv2
from matplotlib import pyplot as plt
cap = cv2.VideoCapture(videoFName)
ret, image = cap.read()
image=cv2.resize(image,None,fx=0.25,fy=0.25,interpolation=cv2.INTER_AREA)
plt.imshow(image)
plt.show()
If you want to show the video instead of an image in a separate window, use the following code:
import cv2
cap = cv2.VideoCapture(videoFName)
while cap.isOpened():
ret, image = cap.read()
image=cv2.resize(image,None,fx=0.25,fy=0.25,interpolation=cv2.INTER_AREA)
cv2.imshow('image',image)
k = cv2.waitKey(30) & 0xff # press ESC to exit
if k == 27 or cv2.getWindowProperty('image', 0)<0:
break
cv2.destroyAllWindows()
cap.release()
Make sure the window name match, otherwise it will not work. In this case I use 'image' as window name.
The new window that opens up from Jupyter uses the same kernel as notebook. Just add this below to the code and it would work fine.
cv2.waitKey(0)
cv2.destroyAllWindows()
image = cv2.imread(file_path)
while True:
# Press 'q' for exit
exit_key = ord('q')
if cv2.waitKey(exit_key) & 255 == exit_key:
cv2.destroyAllWindows()
break
cv2.imshow('Image_title', image)
I have just developed a library that is exactly similar to cv2.imshow and it can be used in both Jupyter and colab. It can update the window. Therefore you can easily see the video inside it. It uses HTML canvas and is browser friendly :)
Installation:
pip install opencv_jupyter_ui
Usage:
This is the replacement of cv2.imshow for Jupiter. you need only to replace cv2.imshow with jcv2.imshow. It will work in Jupiter.
First:
please import the library
import opencv_jupyter_ui as jcv2
Then:
change cv2.imshow ->jcv2.imshow
More details exist on the Github Repository. Binder Demo gif
It also supports jcv2.waitKey(100) and jcv2.destroyAllWindows(). In case of the absence of Jupyter, it fallbacks to original cv2 functionality.
In order to change the default keys you can use jcv2.setKeys(['a','b','esc']). Please follow the document for more information
I am not sure if you can open a window from Jupyter Notebook.
cv2.imshow expects a waitKey which doesn't work in Jupyter.
Here is what I have done (using OpenCV 3.3):
from IPython.display import display, HTML
import cv2
import base64
def imshow(name, imageArray):
_, png = cv2.imencode('.png', imageArray)
encoded = base64.b64encode(png)
return HTML(data='''<img alt="{0}" src="data:image/png;base64, {1}"/>'''.format(name, encoded.decode('ascii')))
img = cv2.imread('./media/baboon.jpg',cv2.IMREAD_COLOR)
imshow('baboon', img)
If you don't need to use cv2, just:
from IPython.display import Image
Image('./media/baboon.jpg')
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
I'm trying to show images with cv2 library in my Jupiter Notebook with cv2.imshow(img) and it shows as expected, but I can not use or don't know how to use cv2.waitKey(0), hence the cell will not stop executing.
cv2.waitKey(0) works in script, but not in Notebook.
Here's a snippet:
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
How do I stop executing cell without restarting the whole kernel?
So, thanks to #Micka, here's the solution:
You must write cv2.startWindowThread() first, explained here.
I found the answer from primoz very useful. Here is a code for a function that reads an image from specified path, draws the image, waits for any input to close a window and returns the image object.
import cv2
def cv2_imshow(path, title):
"""
function:
- reads image from `path`,
- shows image in a separate window,
- waits for any key to close the window.
return: image object
"""
img = cv2.imread(path)
cv2.startWindowThread()
cv2.imshow(title, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
return img
Call the function with image path and title:
img_raw = cv2_imshow(path = r'img\example\test.png', title = "raw image")
I have just developed a library to facilitate the opencv functionality in Jupyter.
I used buttons in jupyter for simulating waitKey
It shows the image in the jupyer.
Document
Installation
pip install opencv_jupyter_ui
Usage
You need to only change cv2 to jcv2.
import opencv_jupyter_ui as jcv2
...
jcv2.imshow(img,title)
if jcv2.waitKey(1000)==ord('q'):
break
jcv2.destroyAllWindows()
I'm using opencv 2.4.2, python 2.7
The following simple code created a window of the correct name, but its content is just blank and doesn't show the image:
import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('ImageWindow',img)
does anyone knows about this issue?
imshow() only works with waitKey():
import cv2
img = cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('ImageWindow', img)
cv2.waitKey()
(The whole message-loop necessary for updating the window is hidden in there.)
I found the answer that worked for me here:
http://txt.arboreus.com/2012/07/11/highgui-opencv-window-from-ipython.html
If you run an interactive ipython session, and want to use highgui
windows, do cv2.startWindowThread() first.
In detail: HighGUI is a simplified interface to display images and
video from OpenCV code. It should be as easy as:
import cv2
img = cv2.imread("image.jpg")
cv2.startWindowThread()
cv2.namedWindow("preview")
cv2.imshow("preview", img)
You must use cv2.waitKey(0) after cv2.imshow("window",img). Only then will it work.
import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0)
If you are running inside a Python console, do this:
img = cv2.imread("yourimage.jpg")
cv2.imshow("img", img); cv2.waitKey(0); cv2.destroyAllWindows()
Then if you press Enter on the image, it will successfully close the image and you can proceed running other commands.
add cv2.waitKey(0) in the end.
I faced the same issue. I tried to read an image from IDLE and tried to display it using cv2.imshow(), but the display window freezes and shows pythonw.exe is not responding when trying to close the window.
The post below gives a possible explanation for why this is happening
pythonw.exe is not responding
"Basically, don't do this from IDLE. Write a script and run it from the shell or the script directly if in windows, by naming it with a .pyw extension and double clicking it. There is apparently a conflict between IDLE's own event loop and the ones from GUI toolkits."
When I used imshow() in a script and execute it rather than running it directly over IDLE, it worked.
Method 1:
The following code worked for me.
Just adding the destroyAllWindows() didn't close the window. Adding another cv2.waitKey(1) at the end did the job.
im = cv2.imread("./input.jpg")
cv2.imshow("image", im)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
credit : https://stackoverflow.com/a/50091712/8109630
Note for beginners:
This will open the image in a separate window, instead of displaying inline on the notebook. That is why we have to use the destroyAllWindows() to close it later.
So if you don't see a separate window pop up, check if it is behind your current window.
After you view the image press a key to close the popped up window.
Method 2:
If you want to display on the Jupyter notebook.
from matplotlib import pyplot as plt
import cv2
im = cv2.imread("./input.jpg")
color = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
plt.imshow(color)
plt.title('Image')
plt.show()
This is how I solved it:
import cv2
from matplotlib import pyplot
img = cv2.imread('path')
pyplot.imshow(img)
pyplot.show()
For me waitKey() with number greater than 0 worked
cv2.waitKey(1)
You've got all the necessary pieces somewhere in this thread:
if cv2.waitKey(): cv2.destroyAllWindows()
works fine for me in IDLE.
If you have not made this working, you better put
import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0)
into one file and run it.
Doesn't need any additional methods after waitKey(0) (reply for above code)
import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('ImageWindow',img)
cv2.waitKey(0)
Window appears -> Click on the Window & Click on Enter. Window will close.
For 64-bit systems to prevent errors, use this end cv2.waitKey(1) add 0xFF.
example:
import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0) & 0xFF
cv2.destroyAllwindows()
You can also use the following command for more control by stopping the program by pressing the Q button.
import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
if cv2.waitKey(0) & 0xFF == ord('Q'):
break
cv2.destroyAllwindows()
I also had a -215 error. I thought imshow was the issue, but when I changed imread to read in a non-existent file I got no error there. So I put the image file in the working folder and added cv2.waitKey(0) and it worked.
this solved it for me, import pyautogui
If you choose to use "cv2.waitKey(0)", be sure that you have written "cv2.waitKey(0)" instead of "cv2.waitkey(0)", because that lowercase "k" might freeze your program too.
error: (-215) size.width>0 && size.height>0 in function imshow
This error is produced because the image is not found. So it's not an error of imshow function.
I had the same 215 error, which I was able to overcome by giving the full path to the image, as in, C:\Folder1\Folder2\filename.ext
import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0)
cv2.destroyAllwindows()
you can try this code :)
If you still want to have access to the console while looking at the pictures.
You can also pass a list of images which will be shown one after another.
from threading import Thread
from typing import Union
import numpy as np
import cv2
from time import sleep
def imshow_thread(
image: Union[list, np.ndarray],
window_name: str = "",
sleep_time: Union[float, int, None] = None,
quit_key: str = "q",
) -> None:
r"""
Usage:
import glob
import os
from z_imshow import add_imshow_thread_to_cv2 #if you saved this file as z_imshow.py
add_imshow_thread_to_cv2() #monkey patching
import cv2
image_background_folder=r'C:\yolovtest\backgroundimages'
pics=[cv2.imread(x) for x in glob.glob(f'{image_background_folder}{os.sep}*.png')]
cv2.imshow_thread( image=pics[0], window_name='screen1',sleep_time=None, quit_key='q') #single picture
cv2.imshow_thread( image=pics, window_name='screen1',sleep_time=.2, quit_key='e') #sequence of pics like a video clip
Parameters:
image: Union[list, np.ndarray]
You can pass a list of images or a single image
window_name: str
Window title
(default = "")
sleep_time: Union[float, int, None] = None
Useful if you have an image sequence.
If you pass None, you will have to press the quit_key to continue
(default = None)
quit_key: str = "q"
key to close the window
Returns:
None
"""
t = Thread(target=_cv_imshow, args=(image, window_name, sleep_time, quit_key))
t.start()
def _cv_imshow(
cvimages: Union[list, np.ndarray],
title: str = "",
sleep_time: Union[float, int, None] = None,
quit_key: str = "q",
) -> None:
if not isinstance(cvimages, list):
cvimages = [cvimages]
if sleep_time is not None:
for cvimage in cvimages:
cv2.imshow(title, cvimage)
if cv2.waitKey(1) & 0xFF == ord(quit_key):
break
sleep(sleep_time)
else:
for cvimage in cvimages:
cv2.imshow(title, cvimage)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
cv2.destroyAllWindows()
def add_imshow_thread_to_cv2():
cv2.imshow_thread = imshow_thread # cv2 monkey patching
# You can also use imshow_thread(window_name, image, sleep_time=None)
# if you dont like monkey patches
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.