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
Related
I am trying to find a way to show an image without the dependency of waitKey(). I want the image to be shown and continue on with next operations (like a plot using matplotlib). How can this be achieved?
If you're wanting to show the window and have the program continue execution without relying on cv2.waitKey(), then cv2.startWindowThread() is what you're looking for.
Example:
import cv2
img = cv2.imread("C:\\Test\\so1.png")
cv2.imshow("Test", img)
cv2.startWindowThread()
for x in range(0, 10000000):
print(x)
This will display the image and continue execution without using waitKey
I tried multiple methods, but what worked was using matplotlib
import matplotlib.pyplot as plt
#obtain I as a numpy array
plt.imshow(cv2.cvtColor(I, cv2.COLOR_BGR2RGB))
I am trying to run this program in jupyter notebook, but it's not running at all. It's just showing the asterisk beside the program. Can anyone tell me why is that happening? I have also tried other programs of OpenCV as well, but the result was the same. None of them are running.
import cv2
import numpy as np
image = cv2.imread('images/input.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow('Original image',image)
cv2.imshow('Gray image', gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
Try this following code, opencv imshow cause issues with notebook.
from matplotlib import pyplot as plt
import cv2
image = cv2.imread('images/input.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
plt.imshow(gray)
plt.title('Gray image')
plt.show()
I am trying to make a simple program to detect a circle in an image. I've written this code, and the result can be seen in the attached picture. Could someone please tell me what am I doing wrong?
import time
import cv2
import imutils
import numpy as np
img=cv2.imread('circle.jpg')
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
binary=cv2.threshold(gray,150,255,cv2.THRESH_BINARY)[1]
cv2.imshow('binary',binary)
circles=cv2.HoughCircles(binary,cv2.HOUGH_GRADIENT,1,50,50,30,5,100)
if circles is not None:
circles=np.round(circles[0,:]).astype("int")
for i in circles:
cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),4)
cv2.circle(img,(i[0],i[1]),2,(0,0,255),3)
else:
print"no circle"
cv2.imshow('circle',img)
k=cv2.waitKey(0)
if k==27:
cv2.destroyAllWindows()
Image
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 am doing some image editing with the PIL libary. The point is, that I don't want to save the image each time on my HDD to view it in Explorer. Is there a small module that simply enables me to set up a window and display the image?
From near the beginning of the PIL Tutorial:
Once you have an instance of the Image class, you can use the methods
defined by this class to process and manipulate the image. For
example, let's display the image we just loaded:
>>> im.show()
Update:
Nowadays the Image.show() method is formally documented in the Pillow fork of PIL along with an explanation of how it's implemented on different OSs.
I tested this and it works fine for me:
from PIL import Image
im = Image.open('image.jpg')
im.show()
You can use pyplot to show images:
from PIL import Image
import matplotlib.pyplot as plt
im = Image.open('image.jpg')
plt.imshow(im)
plt.show() # image will not be displayed without this
If you find that PIL has problems on some platforms, using a native image viewer may help.
img.save("tmp.png") #Save the image to a PNG file called tmp.png.
For MacOS:
import os
os.system("open tmp.png") #Will open in Preview.
For most GNU/Linux systems with X.Org and a desktop environment:
import os
os.system("xdg-open tmp.png")
For Windows:
import os
os.system("powershell -c tmp.png")
Maybe you can use matplotlib for this, you can also plot normal images with it. If you call show() the image pops up in a window. Take a look at this:
http://matplotlib.org/users/image_tutorial.html
You can display an image in your own window using Tkinter, w/o depending on image viewers installed in your system:
import Tkinter as tk
from PIL import Image, ImageTk # Place this at the end (to avoid any conflicts/errors)
window = tk.Tk()
#window.geometry("500x500") # (optional)
imagefile = {path_to_your_image_file}
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()
For Python 3, replace import Tkinter as tk with import tkinter as tk.
Yes, PIL.Image.Image.show() easy and convenient.
But if you want to put the image together, and do some comparing, then I will suggest you use the matplotlib. Below is an example,
import PIL
import PIL.IcoImagePlugin
import PIL.Image
import matplotlib.pyplot as plt
with PIL.Image.open("favicon.ico") as pil_img:
pil_img: PIL.IcoImagePlugin.IcoImageFile # You can omit. It helps IDE know what the object is, and then it will hint at the method very correctly.
out_img = pil_img.resize((48, 48), PIL.Image.ANTIALIAS)
plt.figure(figsize=(2, 1)) # 2 row and 1 column.
plt.subplots_adjust(hspace=1) # or you can try: plt.tight_layout()
plt.rc(('xtick', 'ytick'), color=(1, 1, 1, 0)) # set xtick, ytick to transparent
plt.subplot(2, 1, 1), plt.imshow(pil_img)
plt.subplot(2, 1, 2), plt.imshow(out_img)
plt.show()
This is what worked for me:
roses = list(data_dir.glob('roses/*'))
abc = PIL.Image.open(str(roses[0]))
PIL.Image._show(abc)