Related
This python script with openCV works when you wait for a key press with cv2.waitKey(0), but it doesn't when I want to make a smooth animation with time.sleep(0.1) instead of cv2.waitKey(0). It then shows a cursor symbol that the system gets stuck. Why is this?
import cv2
import random
import numpy as np
originalImg = cv2.imread('assets/fluf.jpg', cv2.IMREAD_UNCHANGED)
img = np.copy(originalImg)
index = 0
while True:
index += 1
smallPartImg = originalImg[500:700,index:index+200]
img[0:200,0:200] = smallPartImg
cv2.imshow('image',img)
cv2.waitKey(0)
Just copying the comments into an Answer (thanks #Micka!) to complete this for anyone coming later
Use waitKey(1). OpenCV needs the waitKey command to perform the window rendering
The issue is that
waitKey(0) waits forever until a key is pressed. waitKey(1) waits 1 ms or until a key is pressed. Both perform the screen rendering of all previous imshow calls. time.sleep doesn't perform the opencv window rendering.
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')
I installed openCV and numpy libraries in python 2.7.
I've tested them using commands import cv2 and import numpy and it compiled.
But when I use the cv2.imshow('frame', ----) function it displays a window but not displaying the image. And it's showing " frame is Not Responding".
So, I tried with matplotlib functions for displaying image and it worked.
I inserted cv2.imshow function in the 2nd case and it worked.
Versions [Python-2.7.10, OpenCV-2.4.11]
Below is the code,
Case 1: Not Working,displaying window but not image (showing FRAME IS NOT RESPONDING)
import cv2
import numpy
img = cv2.imread('a.jpg')
cv2.imshow('FRAME',img)
Case 2: Working
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
img = mpimg.imread('a.jpg')
img2 = cv2.imread('b.jpg')
cv2.imshow('FRAME',img2)
plt.imshow(img)
plt.show()
imshow should be followed by waitKey function which displays the image for specified milliseconds. Otherwise, it won’t display the image. For example, waitKey(0) will display the window infinitely until any keypress (it is suitable for image display). waitKey(25) will display a frame for 25 ms, after which display will be automatically closed. (If you put it in a loop to read videos, it will display the video frame-by-frame). Here's a working example:
import cv2
img = cv2.imread('a.jpg')
cv2.imshow('FRAME', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Try using imread like this
img = cv2.imread('a.jpg',0)#grayscale
img = cv2.imread('a.jpg',1)#rgb
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