03 彩色空间互转
3.2 学习目标
- 了解相关颜色空间的基础知识
- 理解彩色空间互转的理论
- 掌握OpenCV框架下颜色空间互转API的使用
3.4 算法理论介绍与资料推荐
3.4.1 RGB与灰度图互转
将R、G、B三个通道作为笛卡尔坐标系中的X、Y、Z轴,就得到了一种对于颜色的空间描述
对于彩色图转灰度图,有一个很著名的心理学公式:
Gray = R * 0.299 + G * 0.587 + B * 0.114
HSV模型
这个模型就是按色彩、深浅、明暗来描述的。
H是色彩;
S是深浅, S = 0时,只有灰度;
V是明暗,表示色彩的明亮程度,但与光强无直接联系。
应用:可以用于偏光矫正、去除阴影、图像分割等.
3.5 基于OpenCV的实现
- 工具:OpenCV
函数原型(python)
def cvtColor(src, code, dst=None, dstCn=None): # real signature unknown; restored from __doc__
"""
cvtColor(src, code[, dst[, dstCn]]) -> dst
. @brief Converts an image from one color space to another.
.
. The function converts an input image from one color space to another. In case of a transformation
. to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note
. that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the
. bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue
. component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and
. sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on.
.
. The conventional ranges for R, G, and B channel values are:
. - 0 to 255 for CV_8U images
. - 0 to 65535 for CV_16U images
. - 0 to 1 for CV_32F images
- src: 输入图像
- dst: 输出图像
- code: 颜色空间转换标识符
- OpenCV2的CV_前缀宏命名规范被OpenCV3中的COLOR_式的宏命名前缀取代
- 注意RGB色彩空间默认通道顺序为BGR
- 具体可以参考: enum cv::ColorConversionCode部分
- dstCn: 目标图像的通道数,该参数为0时,目标图像根据源图像的通道数和具体操作自动决定
Python代码
import cv2
import numpy as np
if __name__ == ‘__main__‘:
img = cv2.imread(‘./00_dog.jpg‘, cv2.IMREAD_UNCHANGED)
cv2.imshow("img", img)
print(‘RGB2GRAY‘)
cv2.imshow("RGB2GRAY", cv2.cvtColor(img, cv2.COLOR_RGB2GRAY))
print(‘RGB2HSV‘)
dst1 = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
cv2.imshow("RGB2HSV", dst1)
print(‘HSV2RGB‘)
dst2 = cv2.cvtColor(dst1, cv2.COLOR_HSV2RGB)
cv2.imshow("RGB2HSV", dst2)
cv2.waitKey(10000)
cv2.destroyAllWindows()