0
0
Computer Visionml~20 mins

Color spaces (RGB, BGR, grayscale, HSV) in Computer Vision - ML Experiment: Train & Evaluate

Choose your learning style9 modes available
Experiment - Color spaces (RGB, BGR, grayscale, HSV)
Problem:You have an image loaded in BGR format using OpenCV. You want to convert it to RGB, grayscale, and HSV color spaces to prepare it for different computer vision tasks.
Current Metrics:Currently, the image is only in BGR format, which causes incorrect color display when shown with libraries expecting RGB. No color space conversions are applied.
Issue:The image colors appear wrong when displayed, and grayscale or HSV representations are not available for further processing.
Your Task
Convert the input BGR image to RGB, grayscale, and HSV color spaces correctly and display all versions side by side.
Use OpenCV functions for color space conversion.
Do not change the original image data.
Display images using matplotlib which expects RGB format.
Hint 1
Hint 2
Hint 3
Solution
Computer Vision
import cv2
import matplotlib.pyplot as plt

# Load image in BGR format
image_bgr = cv2.imread('sample.jpg')

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

# Convert BGR to Grayscale
image_gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)

# Convert BGR to HSV
image_hsv = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2HSV)

# Display all images side by side
fig, axs = plt.subplots(1, 4, figsize=(16, 5))

axs[0].imshow(image_rgb)  # Show original image in RGB for correct colors
axs[0].set_title('RGB (Original)')
axs[0].axis('off')

axs[1].imshow(image_rgb)  # Correct color display
axs[1].set_title('RGB')
axs[1].axis('off')

axs[2].imshow(image_gray, cmap='gray')  # Grayscale image
axs[2].set_title('Grayscale')
axs[2].axis('off')

axs[3].imshow(image_hsv)  # HSV shown as RGB will look strange
axs[3].set_title('HSV (shown as RGB)')
axs[3].axis('off')

plt.tight_layout()
plt.show()
Added conversion from BGR to RGB for correct color display in matplotlib.
Added conversion from BGR to grayscale for single channel image processing.
Added conversion from BGR to HSV for color-based segmentation tasks.
Displayed all images side by side for easy comparison.
Fixed display of original image to use RGB instead of BGR for correct colors.
Results Interpretation

Before: Image displayed in BGR format looks incorrect in matplotlib because it expects RGB.

After: RGB image shows correct colors, grayscale image shows intensity, HSV image shows color components differently.

Understanding and correctly converting color spaces is essential in computer vision to ensure images are processed and displayed as intended.
Bonus Experiment
Try converting the image from RGB to LAB color space and display it alongside the others.
💡 Hint
Use cv2.cvtColor() with cv2.COLOR_RGB2LAB and remember to convert BGR to RGB first.