0
0
Computer Visionml~15 mins

Displaying images (cv2.imshow, matplotlib) in Computer Vision - ML Experiment: Train & Evaluate

Choose your learning style9 modes available
Experiment - Displaying images (cv2.imshow, matplotlib)
Problem:You want to display images correctly using two popular Python libraries: OpenCV (cv2.imshow) and Matplotlib (plt.imshow). Currently, your images either do not show up or appear with wrong colors.
Current Metrics:Images either do not display or show incorrect colors (e.g., blue and red channels swapped).
Issue:OpenCV uses BGR color format while Matplotlib uses RGB. Also, cv2.imshow requires a waitKey and destroyAllWindows call to display images properly.
Your Task
Display the same image correctly using both cv2.imshow and matplotlib.pyplot.imshow, ensuring colors appear natural and images show up without errors.
You must use the same image file for both display methods.
Do not change the image content, only adjust display code.
Use only OpenCV and Matplotlib libraries.
Hint 1
Hint 2
Hint 3
Solution
Computer Vision
import cv2
import matplotlib.pyplot as plt

# Load image using OpenCV
image_bgr = cv2.imread('sample.jpg')

# Display using OpenCV (BGR format)
cv2.imshow('OpenCV Image', image_bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Convert BGR to RGB for Matplotlib
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)

# Display using Matplotlib
plt.imshow(image_rgb)
plt.axis('off')
plt.title('Matplotlib Image')
plt.show()
Added cv2.waitKey(0) and cv2.destroyAllWindows() after cv2.imshow to properly display the window.
Converted image from BGR to RGB before displaying with matplotlib to fix color issues.
Used plt.axis('off') to hide axes for cleaner image display in matplotlib.
Results Interpretation

Before: Images either did not appear or showed wrong colors (blue and red swapped).

After: OpenCV window shows the image correctly in BGR format. Matplotlib shows the same image with correct colors after converting to RGB.

Different libraries use different color formats and display methods. Understanding these differences and using proper conversions and display functions ensures images show correctly.
Bonus Experiment
Try displaying a grayscale image using both cv2.imshow and matplotlib.pyplot.imshow. Ensure the image appears in grayscale without color distortions.
💡 Hint
Use cv2.imread with flag cv2.IMREAD_GRAYSCALE. For matplotlib, use cmap='gray' in plt.imshow.