We display images to see what the computer is working on. It helps us check if the image is loaded or processed correctly.
Displaying images (cv2.imshow, matplotlib) in 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.
import cv2 image = cv2.imread('cat.jpg') cv2.imshow('Cat', image) cv2.waitKey(0) cv2.destroyAllWindows()
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()
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.
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()
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.
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.