OpenCV's waitKey() alternative in IPython Notebook - python

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

Related

Why cv2.namedWindow is not works?

I try start my code, but process finishes on step with method cv2.namedWindow (without
any errors).
Do you have any suggestions, why it could be so?
import cv2
image_cv2 = cv2.imread('/home/spartak/PycharmProjects/python_base/lesson_016/python_snippets/external_data/girl.jpg')
def viewImage(image, name_of_window):
print('step_1')
cv2.namedWindow(name_of_window, cv2.WINDOW_NORMAL)
print('step_2')
cv2.imshow(name_of_window, image)
print('step_3')
cv2.waitKey(0)
print('step_4')
cv2.destroyAllWindows()
cropped = image_cv2
viewImage(cropped, 'Cropped version')
P.S.:
Also I erased UBUNTU , and installed Fedora.
Instead Pycharm, check programm on VS code.
But nothing changes.
I changed location for picture (girl.jpg) to directory with python document.
But program stops on step1 and waiting something.
I find out the problem.
I started this code in virtual environment.
Apparently, in virtual environment on UBUNTU/FEDORA, opencv have restrictions.
The code completes all 4 steps for me
I think there is a problem with the image path which you took
The function cv2.namedWindow creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names If a window with the same name already exists, the function does nothing.
I do think the function
cv2.destroyAllWindows
This function is deallocating some needed gui elements, I would guess.
So calling this multiple times will produce some trouble.
import cv2
image_cv2 = cv2.imread('foo.jpg')
def viewImage(image, name_of_window):
print('step_1')
cv2.namedWindow(name_of_window)
print('step_2')
cv2.imshow(name_of_window, image)
print('step_3')
cv2.waitKey(0)
#print('step_4')
#cv2.destroyAllWindows()
cropped = image_cv2
viewImage(cropped, 'Cropped version')
#e.g. better usage at the end of the code or section
cv2.destroyAllWindows()

Jupyter kernel crashes when trying to display image with OpenCV

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.

opencv.imshow will cause jupyter notebook crash

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

Opencv imshow() freezes when updating

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

cv2.imshow command doesn't work properly in opencv-python

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

Categories

Resources