Load and show image using Matplotlib Python library
Matplotlib is a 2D plotting Python library that can produce figures, graphs, and charts. In this tutorial, I am going to show you how to show a simple RGB image using the Matplotlib Python library.
It is going to be so interesting to use Matplotlib to display an image. Using Matplotlib, with just a few lines of code we can easily display an image in Python.
Display image using Matplotlib in python
Now let’s jump into the code without wasting time anymore:
At the very beginning, first import our Matplotlib library and the Matplotlib image sub-package:
import matplotlib.pyplot as plt import matplotlib.image as mpllimg
The pyplot package of Matplotlib will plot our image figure and the image package will read the image and store it as the multidimensional NumPy array.
Now, let’s write the rest of our code:
img=mpllimg.imread('myimg.jpg') img_plot = plt.imshow(img) plt.show()
In our above code, the imread() method loads the image as the multi-dimensional NumPy array. All we have to do to get the NumPy array of our image is just to pass the image path to this method as an argument.
After that, we just pass the value to the imshow() method to plot the NumPy array with Matplotlib. In the end, we use show() method to show our image.
The image generated by Matplotlib will look like you can see below:
That’s it. We have completed our code to display image using the Matplotlib library in Python.
It was great. But how about, if we don’t want to show the number axes? Can we get rid of it?
yes, we can get rid of the axis number just by adding a single line of code just like you can see below:
plt.axis("off") img_plot = plt.imshow(img)
We have just called the axis method from the pyplot package and pass a string argument “off” inside it to stop showing those axis numbers:
Now if we run our code, we will just see our image without those axes. below is how it will then look:
I hope you have now understood how to load and show an image using Matplotlib Python library.