OpenCV and Python – Using matplotlib as an Image Viewer

OpenCV & Python - the matplotlib library header

If you are using OpenCV in a Python environment, you will find that the matplotlib library is the perfect tool for viewing the images produced during the Image Analysis task. In fact, this library is very flexible and allows you to make customizations and display modes that OpenCV’s internal tools do not have. We will see with a couple of examples how to view images both individually and in groups using plots and subplots.

[wpda_org_chart tree_id=38 theme_id=50]

The disadvantages of using cv2.imshow()

OpenCV is a library that was developed to work with the C++ language. So its internal visualization systems in this area are highly appreciated and useful. However, if you are working with Python, using such tools, such as cv2.imshow() , for viewing images with OpenCV has some disadvantages to consider:

  • Specific development environment: cv2.imshow() is most commonly used in script-based development environments, such as when developing and testing Python code from the command line. It’s not as convenient when working in more interactive environments like Jupyter Notebooks, where Matplotlib might offer more flexibility.
  • Limited interaction: cv2.imshow() provides basic user interaction, such as the ability to resize the image, but does not offer the same level of control and flexibility that Matplotlib offers.
  • Problems with some development environments: In some development environments, such as some IDEs, cv2.imshow() may lead to display or interaction problems, especially in Windows-based operating systems.
  • OpenCV event loop dependency: cv2.imshow() often requires the use of cv2.waitKey() to handle keyboard events. This can make event management more complex and could lead to problems in some situations.

To mitigate these disadvantages

Use Matplotlib to view OpenCV images

Matplotlib is a visualization library in Python that allows you to create graphs, charts, and in our case, visualize images. While matplotlib is not the only way to display images with OpenCV, it is now almost common practice. This is mainly due to its flexibility and ease of use in the context of Python. So OpenCV also has its own display methods, such as cv2.imshow(), using Matplotlib offers many advantages, including:

  • Python Integration: Matplotlib is a Python library, which makes it easy to integrate with Python code you may already have.
  • Flexibility: Matplotlib offers detailed control over image display. You can customize the look of your view, add labels, titles, legends and more.
  • Interactivity: Matplotlib allows for greater interactivity in visualization. For example, you can easily zoom, move and save the view in various formats.
  • Support for Jupyter Notebooks: If you’re working in an environment like Jupyter Notebooks, Matplotlib is especially convenient, as it can display images directly inside the notebook.

However, if you prefer to use OpenCV’s visualization methods, you can certainly do so, especially if you are working in a context where detailed visualization is not a priority and you prefer a lighter and faster solution. The choice between Matplotlib and OpenCV often depends on your specific needs and personal preferences

View an OpenCV image with matplotlib

We show here a very simple example in Python, which allows us to show the minimal pattern of commands to use to display an image generated as a value returned by one of the many functions of the OpenCV library. This example can serve as a guide to OpenCV and Matplotlib for viewing an image.

Remember that you will need to install the necessary libraries if you don’t already have them installed. You can do this with the following command:

pip install opencv-python matplotlib

Let’s take the following image as an example:

leaf-identification

Right-click on it and download it to your computer, simply saving it as leaf.jpg.

import cv2
from matplotlib import pyplot as plt

# Load an image with OpenCV
image_path = "leaf.jpg"
image = cv2.imread(image_path)

# OpenCV reads the image in BGR format, but Matplotlib displays images in RGB format,
# so we need to convert the format before displaying it
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# View image with Matplotlib
plt.imshow(image_rgb)
plt.title('Image shown by Matplotlib')
plt.axis('off')  # Nasconde gli assi x e y
plt.show()

Running the code you will get the following view:

OpenCV & Python - image with matplotlib

As we can see we have a perfect reproduction of the original image, with a title placed above it. This is a basic example, but there are many things you can do with OpenCV and Matplotlib to analyze and visualize images. For example, you can combine multiple images, draw shapes or regions of interest on the image, apply filters, and more.

View multiple images at once with matplotlib

One of the most used aspects with Matplotlib is the ability to view multiple images simultaneously within a single view. You can do this using Matplotlib subplots, which allow you to organize multiple images in a grid or custom layout. Let’s add a second image:

Torino

Download it as done with the previous image, saving it with the name torino.jpg. You can also use another image of your choice.

Once the second image has also been downloaded, we reformulate the previous code to be able to view both images through the subplots.

import cv2
from matplotlib import pyplot as plt

# Load images with OpenCV
image1 = cv2.imread("leaf.jpg")
image2 = cv2.imread("torino.jpg")

# Convert images from BGR to RGB
image1_rgb = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)
image2_rgb = cv2.cvtColor(image2, cv2.COLOR_BGR2RGB)

# Create a two-subplot visualization
plt.subplot(1, 2, 1)  # 1 riga, 2 colonne, primo subplot
plt.imshow(image1_rgb)
plt.title('Image 1')
plt.axis('off')

plt.subplot(1, 2, 2)  # 1 row, 2 columns, second subplot
plt.imshow(image2_rgb)
plt.title('Image 2')
plt.axis('off')

# Show view
plt.show()

In this example, plt.subplot(1, 2, 1) defines the first subplot in the grid with a single row and two columns, while plt.subplot(1, 2, 2) defines the second subplot. In fact, running the code gives the following result.

OpenCV & Python - images with matplotlib

You can customize the number of rows and columns based on the number of images you want to display at once.

Conclusion

You can extend this idea to create more complex layouts with multiple rows and columns. Matplotlib provides many options for customizing subplots and their locations, offering great flexibility in creating multiple visualizations.

This is just a starting point, and you can delve further into the functionality of both libraries to tailor them to your specific needs.

Leave a Reply