Display an image with Python

2019-01-23 11:29发布

问题:

I tried to use IPython.display with the following code:

from IPython.display import display, Image
display(Image(filename='MyImage.png'))

I also tried to use matplotlib with the following code:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
plt.imshow(mpimg.imread('MyImage.png'))

In both cases, nothing is displayed, not even an error message.

回答1:

If you are using matplotlib and want to show the image in your interactive notebook, try the following:

%pylab inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('your_image.png')
imgplot = plt.imshow(img)
plt.show()


回答2:

If you use matplotlib, you need to show the image using plt.show() unless you are not in interactive mode. E.g.:

plt.figure()
plt.imshow(sample_image) 
plt.show()  # display it


回答3:

In a much simpler way you can do the same using

import Image

image = Image.open('image.jpg')
image.show()


回答4:

Using opencv-python is faster for more operation on image:

import cv2
import matplotlib.pyplot as plt

im = cv2.imread('image.jpg')
im_resized = cv2.resize(im, (224, 224), interpolation=cv2.INTER_LINEAR)

plt.imshow(cv2.cvtColor(im_resized, cv2.COLOR_BGR2RGB))
plt.show()


回答5:

It's simple Use following pseudo code

from pylab import imread,subplot,imshow,show

import matplotlib.pyplot as plt

image = imread('...')  // choose image location

plt.imshow(image)

plt.show() // this will show you the image on console.



回答6:

This worked for me, Inspired by @the_unknown_spirit

from PIL import Image
image = Image.open('test.png')
image.show()