New Tutorials:   TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs
See the Tutorial List

Working with Images in Matplotlib

In this tutorial, we will cover how to work with images in the Matplotlib library.

In Matploltlib library, The image module is used for adding images in plots and figures.

  • Only PNG images are supported by matplotlib.

  • There are two useful and important methods of the image module imread(it is used to read images) and imshow (it is used to display the image).

Now we will cover some examples showing how you can work with images:

Example 1:

In the code snippet, we will read the image using imread() and then display the image using imshow():

import matplotlib.pyplot as plt 
import matplotlib.image as img 

testImage = img.imread('C:\\Users\\StudyTonight\\Desktop\\logoo.png') 

plt.imshow(testImage) 

Following will be the output:

add image as background to matplotlib plot

Example 2:

In the code example given below, we read the image using imread() and then represent it in the form of an array:

import matplotlib.pyplot as plt 
import matplotlib.image as img 

testImage = img.imread('C:\\Users\\StudyTonight\\Desktop\\logoo.png') 

print(testImage) 


[[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
...
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
...
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
...
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

...

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
...
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
...
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
...
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]]

Example 3:

In the example given below, we will modify all the parameters of the image:

import matplotlib.pyplot as plt 
import matplotlib.image as img 

testImage = img.imread('C:\\Users\\StudyTonight\\Desktop\\logoo.png') 

print(testImage.shape) 

modifiedImage = testImage[50:200, 100:200, 1] 

plt.imshow(modifiedImage) 

In the above code, the height of the image is 150 pixels (that is displayed from the 50th pixel), width is 100 pixels (that is displayed from the 100th pixel) and the mode value is 1.

Following is the output of the above code:

adding image in matplotlib plot

Conclusion:

With this we come to an end for our Matplotlib tutorial. We will keep on adding more tutorial pages and guides to this tutorial along with some applications for Matplotlib plots and figures.