OpenCV Python – Using Matplotlib
OpenCV is powerful for image processing, but when it comes to visualization, Matplotlib is often used alongside it. Matplotlib helps you display images in notebooks, compare outputs, and visualize color channels in a more flexible way than OpenCV’s imshow().
In this tutorial, you will learn how to use Matplotlib with OpenCV Python for image display and visualization.
1. Why Use Matplotlib with OpenCV?
OpenCV uses its own window system (cv2.imshow()), which is not ideal for:
- Jupyter Notebooks
- Web-based environments
- Multiple image comparisons
- Custom plotting layouts
Matplotlib solves these problems by allowing:
- Inline image display
- Better visualization control
- Multiple plots in one figure
- Easy integration with data science tools
2. Install Matplotlib
If not installed, use pip:
pip install matplotlib
3. Import Libraries
import cv2
import matplotlib.pyplot as plt
4. Read and Display Image using Matplotlib
img = cv2.imread("image.jpg")
plt.imshow(img)
plt.show()
⚠️ Note: OpenCV reads images in BGR format, but Matplotlib uses RGB format.
5. Convert BGR to RGB (Important Step)
To display correct colors:
img = cv2.imread("image.jpg")
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
plt.title("Correct Color Image")
plt.show()
6. Display Grayscale Image
img = cv2.imread("image.jpg", cv2.IMREAD_GRAYSCALE)
plt.imshow(img, cmap='gray')
plt.title("Grayscale Image")
plt.show()
7. Display Multiple Images
img1 = cv2.imread("image1.jpg")
img2 = cv2.imread("image2.jpg")
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)
plt.subplot(1, 2, 1)
plt.imshow(img1)
plt.title("Image 1")
plt.subplot(1, 2, 2)
plt.imshow(img2)
plt.title("Image 2")
plt.show()
8. Hide Axes for Clean Output
plt.imshow(img_rgb)
plt.axis("off")
plt.show()
9. Plot Image with Title and Styling
plt.imshow(img_rgb)
plt.title("OpenCV + Matplotlib Image Display")
plt.axis("off")
plt.show()
10. Common Mistakes
❌ Wrong Colors in Output
✔ Solution:
cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
❌ Image Not Showing
✔ Solution:
-
Ensure
plt.show()is used - Check image path
11. Applications of Matplotlib with OpenCV
- Image comparison in AI models
- Data visualization in computer vision
- Medical image analysis
- Deep learning dataset inspection
- Debugging image processing pipelines
12. Conclusion
Using Matplotlib with OpenCV makes image visualization much easier and more powerful, especially for data analysis and AI development. It helps you clearly display images, compare results, and analyze processed outputs efficiently.
Mastering this combination is essential for any computer vision developer.


0 Comments