Understanding Color Space Conversions in OpenCV: Grayscale, BGR, and HSV with Python Example
This article explains the three commonly used color spaces in computer vision—grayscale, BGR, and HSV—detailing their characteristics and typical applications, and provides a Python OpenCV code example that converts an image to grayscale and displays both the original and processed images.
OpenCV provides hundreds of methods for converting between different color spaces. Currently, three color spaces are commonly used in computer vision: grayscale, BGR, and HSV (Hue, Saturation, Value).
1) Grayscale color space converts color information into gray levels; it is especially effective for intermediate processing such as face recognition.
2) BGR (blue‑green‑red) color space represents each pixel with a three‑element array corresponding to blue, green, and red channels. Web developers may be more familiar with the similar RGB space, which differs only in channel order.
3) HSV separates color into hue (H), saturation (S), and value (V), where value indicates brightness or darkness.
Example: Convert an image to grayscale
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/7/17 下午9:53
# @Author : huaan
import cv2 as cv
img = cv.imread('zwj.jpg')
cv.imshow("BRG_img", img)
# cv2读取图片的通道是RGB(蓝绿红)
# PIL读取图片的通道是RGB
gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow("gray_img", gray_img)
# 保存图片
cv.imwrite("gray_lena.jpg", gray_img)
cv.waitKey(0)
cv.destroyAllWindows()Follow the public account, let's grow together.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.