Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one display an image using cv2 in Python

I've been working with code to display frames from a movie. The bare bones of the code is as follows:

import cv2
import matplotlib.pyplot as plt

# Read single frame avi
cap = cv2.VideoCapture('singleFrame.avi')
rval, frame = cap.read()

# Attempt to display using cv2 (doesn't work)
cv2.namedWindow("Input")
cv2.imshow("Input", frame)

#Display image using matplotlib (Works)
b,g,r = cv2.split(frame)
frame_rgb = cv2.merge((r,g,b))
plt.imshow(frame_rgb)
plt.title('Matplotlib') #Give this plot a title, 
                        #so I know it's from matplotlib and not cv2
plt.show()

Because I can display the image using matplotlib, I know that I'm successfully reading it in.

I don't understand why my creation of a window and attempt to show an image using cv2 doesn't work. No cv2 window ever appears. Oddly though, if I create a second cv2 window, the 'input' window appears, but it is only a blank/white window.

What am I missing here?

like image 573
user1245262 Avatar asked Jan 23 '16 17:01

user1245262


People also ask

How do I display an image in cv2 Python?

To read and display image using OpenCV Python, you could use cv2. imread() for reading image to a variable and cv2. imshow() to display the image in a separate window.

How do you display an image in Python?

Python – Display Image using PIL To show or display an image in Python Pillow, you can use show() method on an image object. The show() method writes the image to a temporary file and then triggers the default program to display that image.


3 Answers

As far as I can see, you are doing it almost good. There is one thing missing:

cv2.imshow('image',img)
cv2.waitKey(0)

So probably your window appears but is closed very very fast.

like image 74
phev8 Avatar answered Oct 19 '22 18:10

phev8


you can follow following code

import cv2
# read image 
image = cv2.imread('path to your image')
# show the image, provide window name first
cv2.imshow('image window', image)
# add wait key. window waits until user presses a key
cv2.waitKey(0)
# and finally destroy/close all open windows
cv2.destroyAllWindows()

I think your job is done then

like image 29
amruta patil Avatar answered Oct 19 '22 18:10

amruta patil


Since OpenCV reads images with BGR format, you'd convert it to RGB format before pass the image to pyplot

import cv2
import matplotlib.pyplot as plt

image = cv2.imread('YOUR_FILEPATH')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)
plt.show()
like image 9
sungjun park Avatar answered Oct 19 '22 17:10

sungjun park