We know that matplotlib is awesome python library for generating graphs and figures. But what if we wanted to display a simple RGB image? Can we do that with matplotlib?
In this post I 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.
Displaying Image with Matplotlib
An RGB image, sometimes referred to as a truecolor image, is stored as an \( m \times n \times 3 \) data array that defines red, green, and blue color components for each individual pixel. The color of each pixel is determined by the combination of the red, green, and blue intensities stored in each color plane at the pixel’s location. Graphics file formats store RGB images as 24-bit images, where the red, green, and blue components are 8 bits each. Lets read an image with OpenCV and display with matplotlib. Original image is
# import the required library import numpy as np import matplotlib.pyplot as plt import cv2 # Read the color image img = cv2.imread('image/mandrill.png') # Display the color image with matplotlib plt.imshow(img) plt.axis('off') plt.show()
Running above script we can see that the colors of our image are not correct:
Why the results aren’t as expected?
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!
So how to fix this problem?
There’s an easy fix though. All we need to do is convert the image from BGR to RGB:
# import the required library import numpy as np import matplotlib.pyplot as plt import cv2 # Read the color image img = cv2.imread('image/mandrill.png') # Convert the BGR image to RGB image temp = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.imshow(temp) # Display the color image with matplotlib plt.imshow(temp) plt.axis('off') plt.show()
The result of above code is
Result of our script shows that the colors of our image are now correct.
In this post I showed you how to display matplotlib RGB images.
- We made use of matplotlib and pyplot to load and display our images.
- To remove the axes of the figure, make a call to plt.axis("off").
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!View Jupyter Notebook
This article is contributed by Ram Kripal. If you like eLgo Academy and would like to contribute, you can mail your article to firstname.lastname@example.org. See your article appearing on the eLgo Academy page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.