In this Matplotlib tutorial, we will explore how to use the imread() function from the PyPlot module. The purpose of this function is fairly simple. It takes a filepath as a parameter, and loads the image data into our Matplotlib application.
The syntax is as follows:
matplotlib.pyplot.imread(filename, format=None)
The first parameter is compulsory, and must be either a filename (if image is in the same directory) or it must be a complete path to the image.
The second parameter is optional. It takes as parameter an image format, such as “png” or “jpg”. This is not really needed though as this function can automatically detect the format of the image.
Reading an Image
In the below example we have created a image object, called img, which has the image data for the “contourplot.png” image.
import matplotlib.pyplot as plt
img = plt.imread("contourplot.png")
And that’s it. We now have our image object loaded into our matplotlib application.
Image Data
The image object contains some useful information about the Image we just loaded, so let’s take a look by printing out the dimensions of the image data (stored in an array)
print(img.shape)
(480, 640, 4)
The first two parameters represent the height and width respectively. If this was a gray-scale image, there would be only be two parameters. But this is an RGBA image, so we have 3 parameters.
For RGB images, the third parameter has the value “3”, because there are three channels, Red, Green and Blue. RGBA images have an extra alpha (transparency) channel so they have 4 channels in total.
PNG images include an alpha channel, hence our image has 4 channels. Other image types like JPG’s do not have an alpha channel.
For more tutorials on Matplotlib, follow the link to our main page for matplotlib, and all it’s related information.
This marks the end of the Matplotlib imread() with PyPlot Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.