How to import (load) an image in python ?

Published: May 04, 2021

Tags: Python; Pillow; Matplotlib;

DMCA.com Protection Status

Examples of how to import (load) an image in python:

Import an image using matplotlib

To import an image in python, one solution is to use matplotlib:

from matplotlib import image

img = image.imread("eiffel-tower.jpeg")

Note:

print( type(img) )
print( img.shape )

returns:

<class 'numpy.ndarray'>

and

(1280, 850, 3)

3 corresponds to RGB.

It is then possible to plot the image using imshow from matplotlib

plt.imshow(img)

plt.show()

 Comment importer et tourner une image avec matplotlib  ?
Comment importer et tourner une image avec matplotlib ?

Import an image using Pillow

Another solution is to use Pillow

from PIL import Image

img= Image.open("eiffel-tower.jpeg")

Note that here

type(img)

is not a numpy array:

PIL.JpegImagePlugin.JpegImageFile

However it is always possible to plot the image using imshow

plt.imshow(img)

plt.show()

to convert img to a numpy array

import numpy as np

img = np.asarray(img)

References

Image

of