cap = cv2.VideoCapture(0)
and
img = cv2.imread(/users/..../jumpingjacks.jpeg, 1)
cv2.imshow('Jumping Jacks', img)
when my prog run these two codes, the webcam feed and image doesn't pop out, but instead, it shows as minimized version, which requires me to press the icon at the bottom of the screen to bring it forward. anyidea what caused this ?
Found the answer by trying out this code:
img = cv2.imread('/users/..../jumpingjacks.jpeg', 1)
cv2.imshow('Jumping Jacks', img)
cv2.setWindowProperty("Jumping Jacks", cv2.WND_PROP_TOPMOST, 1)
cv2.waitKey(5000)
cv2.destroyAllWindows()
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 am running Anaconda install of python35 with cv2 install from menpo.
I am having trouble with cv2.imshow() inconsistently placing the image window outside of the viewable screen when running code similar to the one below both as a standalone script and line by line in the console (cmd, spyder, ipython)...
import cv2
img = cv2.imread('Image71.jpg',0)
cv2.startWindowThread()
cv2.namedWindow('image')
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
I have also tried the above without cv2.starWindowThread() and cv2.namedWindow() with the same result. The window appears on my taskbar but is not in view, cv2.waitKey(0) responds to the keystroke, and I am not able to bring the window into view using any of the window arrangement shortcut keys for Windows 10 (e.g. alt+tab, Winkey + left, etc).
My OS is Win10 version 1709.
Any help is much appreciated, thx!
img = cv2.imread("test.png")
winname = "Test"
cv2.namedWindow(winname) # Create a named window
cv2.moveWindow(winname, 40,30) # Move it to (40,30)
cv2.imshow(winname, img)
cv2.waitKey()
cv2.destroyAllWindows()
wrapped answer by Kinght in a function for easy calling
def showInMovedWindow(winname, img, x, y):
cv2.namedWindow(winname) # Create a named window
cv2.moveWindow(winname, x, y) # Move it to (x,y)
cv2.imshow(winname,img)
img = cv2.imread('path.png')
showInMovedWindow('named_window',img, 0, 200)
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