图像色彩追踪
色彩追踪指的是找出RGB图像中特定颜色在原图中所在的位置
思考:由于在RGB色彩空间中颜色有256³种,色彩追踪是比较困难的。所以我们考虑先将图像转换到HSV色彩空间中。
HSV变换,是将RGB变换到H(Hue:色相)、S(Saturation:饱和度)、V(Value:明度)的方法
关于HSV色彩空间的一些说明:
- 饱和度越小,图像越白,饱和度越大,颜色越浓烈,0<=S<=1;
- 明度数值越高图像越接近于白色,越低越接近于黑色,0<=V<=1;
- 色相:将颜色用0到360度表示,具体色相与数值对应关系可参考下图:
实验:追踪图像中的蓝色部分:
思考:为了追踪蓝色,可以将RGB图像转换为HSV图像后,提取色相在180°到240°之间的图像,将其值置为255(白色)。
import cv2
import numpy as np
import matplotlib.pyplot as plt
# BGR -> HSV
def BGR2HSV(_img):
img = _img.copy() / 255.
hsv = np.zeros_like(img, dtype=np.float32)
# get max and min
max_v = np.max(img, axis=2).copy()
min_v = np.min(img, axis=2).copy()
min_arg = np.argmin(img, axis=2)
# H
hsv[..., 0][np.where(max_v == min_v)]= 0
## if min == B
ind = np.where(min_arg == 0)
hsv[..., 0][ind] = 60 * (img[..., 1][ind] - img[..., 2][ind]) / (max_v[ind] - min_v[ind]) + 60
## if min == R
ind = np.where(min_arg == 2)
hsv[..., 0][ind] = 60 * (img[..., 0][ind] - img[..., 1][ind]) / (max_v[ind] - min_v[ind]) + 180
## if min == G
ind = np.where(min_arg == 1)
hsv[..., 0][ind] = 60 * (img[..., 2][ind] - img[..., 0][ind]) / (max_v[ind] - min_v[ind]) + 300
# S
hsv[..., 1] = max_v.copy() - min_v.copy()
# V
hsv[..., 2] = max_v.copy()
return hsv
# make mask
def get_mask(hsv):
mask = np.zeros_like(hsv[..., 0])
#mask[np.where((hsv > 180) & (hsv[0] < 260))] = 255
mask[np.logical_and((hsv[..., 0] > 180), (hsv[..., 0] < 260))] = 255
return mask
# Read image
img = cv2.imread("../lantian.jpg").astype(np.float32)
# RGB > HSV
hsv = BGR2HSV(img)
# color tracking
mask = get_mask(hsv)
out = mask.astype(np.uint8)
# Save result
cv2.imwrite("out.png", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
实验结果: