0
0
Computer Visionml~5 mins

Displaying images (cv2.imshow, matplotlib) in Computer Vision

Choose your learning style9 modes available
Introduction

We display images to see what the computer is working on. It helps us check if the image is loaded or processed correctly.

You want to quickly see an image loaded from a file.
You want to show results of image processing steps.
You want to compare multiple images side by side.
You want to display images in a notebook or script.
You want to debug or explain what your program sees.
Syntax
Computer Vision
import cv2
cv2.imshow(window_name, image)
cv2.waitKey(delay)
cv2.destroyAllWindows()

# or using matplotlib
import matplotlib.pyplot as plt
plt.imshow(image)
plt.title('Title')
plt.axis('off')
plt.show()

cv2.imshow opens a new window to show the image. You must call cv2.waitKey() to display it properly.

matplotlib shows images inside notebooks or scripts and works well with color images if converted properly.

Examples
This shows the image in a window until you press a key.
Computer Vision
import cv2
image = cv2.imread('cat.jpg')
cv2.imshow('Cat', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
This shows the image inside the notebook or script with correct colors.
Computer Vision
import matplotlib.pyplot as plt
import cv2
image = cv2.imread('cat.jpg')
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image_rgb)
plt.title('Cat Image')
plt.axis('off')
plt.show()
Sample Model

This program loads a sample image, shows it in a window for 1 second using OpenCV, then shows it again inside the script using matplotlib with correct colors.

Computer Vision
import cv2
import matplotlib.pyplot as plt

# Load image
image = cv2.imread(cv2.samples.findFile('lena.jpg'))

# Show with cv2.imshow
cv2.imshow('Lena - OpenCV', image)
cv2.waitKey(1000)  # Show for 1 second
cv2.destroyAllWindows()

# Convert BGR to RGB for matplotlib
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Show with matplotlib
plt.imshow(image_rgb)
plt.title('Lena - Matplotlib')
plt.axis('off')
plt.show()
OutputSuccess
Important Notes

OpenCV uses BGR color order, but matplotlib uses RGB. Convert colors to see correct colors in matplotlib.

cv2.imshow windows need cv2.waitKey() to display and respond to keyboard events.

matplotlib is better for showing images inside notebooks or scripts, while cv2.imshow is good for quick pop-up windows.

Summary

Use cv2.imshow to open a window showing the image; remember to call cv2.waitKey() and cv2.destroyAllWindows().

Use matplotlib.pyplot.imshow to display images inside notebooks or scripts, converting colors from BGR to RGB first.

Displaying images helps you check and understand your computer vision work visually.