So we know that matplotlib is awesome for generating graphs and figures.
But what if we wanted to display a simple RGB image? Can we do that with matplotlib?
This blog post will show you how to display a Matplotlib RGB image in only a few lines of code…as well as clear up any caveats that you may run into when using OpenCV and matplotlib together.
Tutorial: How to Display a Matplotlib RGB Image
Alright, let’s not waste any time. Let’s jump into some code:
>>> import matplotlib.pyplot as plt >>> import matplotlib.image as mpimg >>> image = mpimg.imread("chelsea-the-cat.png") >>> plt.imshow(image) >>> plt.show()
The first thing we are going to do is import our
matplotlib package. Then we’re going to import the
image sub-package of
matplotlib, aliasing it as
mpimg for convenience. This sub-package handles matplotlib’s image manipulations.
A simple call to the
imread method loads our image as a multi-dimensional NumPy array (one for each Red, Green, and Blue component, respectively) and
imshow displays our image to our screen.
We can see our image below:
That’s a good start, but how about getting rid of the numbered axes?
plt.axis("off") plt.imshow(image) plt.show()
plt.axis("off") we can remove our numbered axes.
Executing our code we end up with:
Nothing to it! You can now see that the numbered axes are gone.
The OpenCV Caveat
But of course, we use OpenCV a lot on this blog.
So let’s load up an image using OpenCV and display it with matplotlib:
import cv2 image = cv2.imread("chelsea-the-cat.png") plt.axis("off") plt.imshow(image) plt.show()
Again, the code is simple.
But the results aren’t as expected:
Uh-oh. That’s not good.
The colors of our image are clearly wrong!
Why is this?
The answer lies as a caveat with OpenCV.
OpenCV represents RGB images as multi-dimensional NumPy arrays…but in reverse order!
This means that images are actually represented in BGR order rather than RGB!
There’s an easy fix though.
All we need to do is convert the image from BGR to RGB:
plt.axis("off") plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) plt.show()
Running our script we can see that the colors of our image are now correct:
As I said, there’s nothing to displaying matplotlib RGB images!
In this blog post I showed you how to display matplotlib RGB images.
We made use of
mpimg to load and display our images.
To remove the axes of the figure, make a call to
Just remember that if you are using OpenCV that your images are stored in BGR order rather than RGB!
As long as you remember that, you won’t have any issues!
Download the Source Code and FREE 17-page Resource Guide
Enter your email address below to get a .zip of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!