提示:内容整理自:https://github.com/gzr2017/ImageProcessing100Wen
CV小白从0开始学数字图像处理
使用 HSV 表示色彩图像的色调反转
HSV 即使用**色调(Hue)、饱和度(Saturation)、明度(Value)**来表示色彩的一种方式。
色调:将颜色使用0到360度表示,就是平常所说的颜色名称,如红色、蓝色。色相与数值按下表对应:
红 | 黄 | 绿 | 青色 | 蓝色 | 品红 | 红 |
---|---|---|---|---|---|---|
0 | 60 | 120 | 180 | 240 | 300 | 360 |
饱和度:是指色彩的纯度,饱和度越低则颜色越黯淡( 0<= S < 1);
明度:即颜色的明暗程度。数值越高越接近白色,数值越低越接近黑色 ( 0 <= V < 1);
代码如下:
CV2计算机视觉库
import cv2
import numpy as np
img = cv2.imread("imori.jpg").astype(np.float32) / 255.
out = np.zeros_like(img)
max_v = np.max(img, axis=2).copy()
min_v = np.min(img, axis=2).copy()
min_arg = np.argmin(img, axis=2)
H = np.zeros_like(max_v)
H[np.where(max_v == min_v)] = 0
## if min == B
ind = np.where(min_arg == 0)
H[ind] = 60 * (img[..., 1][ind] - img[..., 2][ind]) / (max_v[ind] - min_v[ind]) + 60
## if min == R
ind = np.where(min_arg == 2)
H[ind] = 60 * (img[..., 0][ind] - img[..., 1][ind]) / (max_v[ind] - min_v[ind]) + 180
## if min == G
ind = np.where(min_arg == 1)
H[ind] = 60 * (img[..., 2][ind] - img[..., 0][ind]) / (max_v[ind] - min_v[ind]) + 300
V = max_v.copy()
S = max_v.copy() - min_v.copy()
# Transpose Hue
H = (H + 180) % 360
C = S
H_ = H / 60
X = C * (1 - np.abs( H_ % 2 - 1))
Z = np.zeros_like(H)
vals = [[Z,X,C], [Z,C,X], [X,C,Z], [C,X,Z], [C,Z,X], [X,Z,C]]
for i in range(6):
ind = np.where((i <= H_) & (H_ < (i+1)))
out[..., 0][ind] = (V-C)[ind] + vals[i][0][ind]
out[..., 1][ind] = (V-C)[ind] + vals[i][1][ind]
out[..., 2][ind] = (V-C)[ind] + vals[i][2][ind]
out[np.where(max_v == min_v)] = 0
out = (out * 255).astype(np.uint8)
cv2.imwrite("out.jpg", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()