Display an image with Python

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.


Solution 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()

Solution 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

Solution 3:

In a much simpler way, you can do the same using

from PIL import Image

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

Solution 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()

Solution 5:

Your first suggestion works for me

from IPython.display import display, Image
display(Image(filename='path/to/image.jpg'))