OpenCV
Color Conversion
Convert between BGR, RGB, HSV, and grayscale.
By EZ4Code Team
colorhsvgray
Code
import cv2
img = cv2.imread("input.jpg")
# BGR <-> RGB (for matplotlib)
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# BGR -> grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# BGR -> HSV (good for color segmentation)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Threshold a color range in HSV
lower = (35, 50, 50)
upper = (85, 255, 255)
mask = cv2.inRange(hsv, lower, upper)
green_only = cv2.bitwise_and(img, img, mask=mask)
# Lab for perceptual comparisons
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
cv2.imwrite("mask.jpg", mask)Explanation
OpenCV loads images in BGR order, so cvtColor with COLOR_BGR2RGB is needed before passing to libraries like matplotlib. HSV separates hue from intensity, making color-range masks robust to lighting changes. inRange produces a binary mask that bitwise_and uses to isolate a color.
More OpenCV Snippets
Read and Write Images
Load, display, and save images in various formats.
Resize and Crop
Resize with interpolation and crop regions of interest.
Blur and Filter
Smooth and sharpen images with kernels.
Edge Detection
Detect edges with Canny, Sobel, and Laplacian.
Contours
Find, draw, and measure contours.
Face Detection
Detect faces with a Haar cascade classifier.