Thanks to theidioms.com

Learn Matplotlib for Data Science (Course III)

Learn Matplotlib for Data Science (Course III)

Working with images in Matplotlib

Matplotlib provides an easy interface to work with images. In this chapter, we will get familiar with reading, plotting and manipulating images in matplotlib.

How to read images in Matplotlib?

To work with images we first need to import the image data into Numpy arrays using the imread() function of Matplotlib Image (imported below as mpimg).

# Libraries/Modules import conventions
import matplotlib.image as mpimg

# Read a network/local image and store as numpy array
img = mpimg.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/Flag_of_Nepal.svg/135px-Flag_of_Nepal.svg.png')

# Printing the image type
print(type(img))
Output: <class 'numpy.ndarray'>

How to plot images in Matplotlib?

Images can be plotted in Matplotlib with the help of the imshow() function of Matplotlib pyplot as shown in the following example:

# Libraries/Modules import conventions
import matplotlib.image as mpimg

# Read a network/local image and store as numpy array
img = mpimg.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/Flag_of_Nepal.svg/135px-Flag_of_Nepal.svg.png')

# Show the image stored in the numpy array
imgplot = plt.imshow(img)
Images in matplotlib

Since the image is basically stored as pixel values in a NumPy array, we can change the values of the pixels to manipulate the image. The following example changes the color of the image:

# Libraries/Modules import conventions
import matplotlib.image as mpimg

# Read a network/local image and store as numpy array
img = mpimg.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/Flag_of_Nepal.svg/135px-Flag_of_Nepal.svg.png')

# Apply pseudocolor schemes to image plots 
manipulated_img = img[:, :, 0] # array slicing operation

# Show the image stored in the manipulated numpy array
imgplot = plt.imshow(manipulated_img)
Plotting images with matplotlib

Now we know how to read, display and manipulate an image in Matplotlib. For more details on working with images, this Matplotlib guide can be useful.

Also, congratulations on completing this course on Matplotlib!

Leave your thought here

Your email address will not be published. Required fields are marked *

Close Bitnami banner
Bitnami