LAST UPDATED: NOVEMBER 11, 2020
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.
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:
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:
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.