How to import (load) an image in python ?

Active May 04, 2021    /    Viewed 6080    /    Comments 0    /    Edit


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 ?

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


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount