色彩追踪简介:在RGB图像中,我们感兴趣的部分往往具有趋于一致的颜色,我们想得到感兴趣部分时,可以考虑先找到特定颜色的区域。比如说有一张风景照,我们对蓝天白云(其它部分不是蓝色)感兴趣,我们考虑使用色彩追踪算法追踪图像中的蓝色和白色,得到原图的蓝色和白色区域。
关于色彩追踪算法的详细说明请查看以下链接
色彩追踪讲解
色彩追踪算法产生的掩膜中白色部分含一些黑色小点,使用掩膜直接作用于图像的话,效果不理想(如 图1)。学习图像处理的过程中,我们知道,使用图像形态学处理之闭运算(先膨胀,后腐蚀)能够有效地消除掩膜中这些小黑点,我们做此运算。
关于图像形态学处理的详细说明请查看以下链接
膨胀和腐蚀算法讲解
图像开闭运算讲解
图像形态学处理 opencv实现
图1:
实验:使用色彩追踪算法生成掩膜 + 图像形态学处理闭运算去噪 = 提取到的蓝色天空
实验原图:
实验结果:
实验源码 python
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))] = 1
return mask
# masking
def masking(img, mask):
out = img.copy()
# mask [h, w] -> [h, w, channel]
mask = np.tile(mask, [3, 1, 1]).transpose([1, 2, 0])
out *= mask
return out
# Erosion
def Erode(img, Erode_time=1):
H, W = img.shape
out = img.copy()
# kernel
MF = np.array(((0, 1, 0),
(1, 0, 1),
(0, 1, 0)), dtype=np.int)
# each erode
for i in range(Erode_time):
tmp = np.pad(out, (1, 1), 'edge')
# erode
for y in range(1, H+1):
for x in range(1, W+1):
if np.sum(MF * tmp[y - 1 : y + 2 , x - 1 : x + 2]) < 1 * 4:
out[y-1 , x-1] = 0
return out
# Dilation
def Dilate(img, Dil_time=1):
H, W = img.shape
# kernel
MF = np.array(((0, 1, 0),
(1, 0, 1),
(0, 1, 0)), dtype=np.int)
# each dilate time
out = img.copy()
for i in range(Dil_time):
tmp = np.pad(out, (1, 1), 'edge')
for y in range(1, H+1):
for x in range(1, W+1):
if np.sum(MF * tmp[y - 1 : y + 2, x - 1 : x + 2]) >= 1:
out[y-1 , x-1] = 1
return out
# Opening morphology
def Morphology_Opening(img, time=1):
out = Erode(img, Erode_time=time)
out = Dilate(out, Dil_time=time)
return out
# Closing morphology
def Morphology_Closing(img, time=1):
out = Dilate(img, Dil_time=time)
out = Erode(out, Erode_time=time)
return out
# Read image
img = cv2.imread("../lantian.jpg").astype(np.float32)
# RGB > HSV
hsv = BGR2HSV(img)
# color tracking
mask = get_mask(hsv)
# closing
mask = Morphology_Closing(mask, time=2)
# opening
mask = Morphology_Opening(mask, time=0)
# masking
out = masking(img, mask)
out = out.astype(np.uint8)
# Save result
cv2.imwrite("out.jpg", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()