彩色图像基础
颜色特性:亮度、色调、饱和度
-
(1)亮度:即强度,如灰度值
-
(2)色调:混合光波中的主导光波属性,即被观察者感知的主导色。如描述一个物体为红色,就是这个物体的色调为红色。
-
(3)饱和度:指相对的纯度,或与一种色调混合的白光量。比如深红色(红色+白色)和淡紫色(紫色+白色)是不饱和的,白色越多,越不饱和。
色度:色调+饱和度,颜色可以由亮度+色度来表征
彩色图像模型
常见的彩色图像模型有:
-
(1)RGB(红、绿、蓝):一般用于彩色显示器和彩色摄像机;
-
(2)CMY(青、深红、黄)和CMYK(青、深红、黄、黑):一般用于彩色打印;
-
(3)HSI(色调、饱和度、亮度):描述和解释颜色;
RGB和HSI之间的相互转换
从RGB到HSI
H色调分量的计算:
S饱和度分量计算:
I 亮度分量计算:
备注:上面的转换公式假设图像的RGB值归一化到[0, 1]区间,得到的HSI结果值也在区间[0, 1]。
python">def RGB2HSI(img1):img1 = img1.astype('float32')b, g, r = img1[:, :, 0]/255.0, img1[:, :, 1]/255.0, img1[:, :, 2]/255.0I = (r+g+b)/3.0tem = np.where(b >= g, g, b)minValue = np.where(tem >= r, r, tem)S = 1 - (3 / (r + g + b)) * minValuenum1 = 2*r - g - bnum2 = 2*np.sqrt(((r - g) ** 2) + (r-b)*(g-b))deg = np.arccos(num1/num2)H = np.where(g >= b, deg, 2*np.pi - deg)resImg = np.zeros((img1.shape[0], img1.shape[1],img1.shape[2]), dtype=np.float)resImg[:, :, 0], resImg[:, :, 1], resImg[:, :, 2] = H*255, S*255, I*255resImg = resImg.astype('uint8')return resImg
从HSI到RGB(值区间与(1)相同[0, 1])
前提:在将HSI转换为RGB时,需要先通过H色调值进行判断,然后使用不同的公式:
-
即将H值乘360°,将值从[0, 1]转换到[0, 360],然后进行分类:
-
RG扇区(H在[0, 120]):
B蓝色分量计算:
R红色分量计算:
G绿分量计算:
GB扇区(H在[120, 240]):
首先将H减去120:
然后转换到RGB:
BR扇区(H在[240, 360]):
首先将H减去240:
然后计算RGB值:
python">def HSI2RGB(img):H1, S1, I1 = img[:,:,0]/255.0, img[:,:,1]/255.0, img[:,:,2]/255.0B = np.zeros((H1.shape[0], H1.shape[1]), dtype='float32')G = np.zeros((S1.shape[0], S1.shape[1]), dtype='float32')R = np.zeros((I1.shape[0], I1.shape[1]), dtype='float32')H = np.zeros((H1.shape[0], H1.shape[1]), dtype='float32')for i in range(H1.shape[0]):for j in range(H1.shape[1]):H = H1[i][j]S = S1[i][j]I = I1[i][j] if (H >=0) & (H < (np.pi * (2/3))):B[i][j] = I*(1-S)R[i][j] = I * (1 + ((S*np.cos(H))/np.cos(np.pi * (1/3) - H)))G[i][j] = 3*I - (B[i][j]+R[i][j])elif (H >= (np.pi * (2/3))) & (H < np.pi * (4/3)):R[i][j] = I*(1-S)G[i][j] = I * (1 + ((S*np.cos(H - np.pi * (2/3)))/np.cos(np.pi * (1/2) - H)))B[i][j] = 3*I - (G[i][j]+R[i][j])elif (H >= (np.pi * (2/3))) & (H < (np.pi * 2)):G[i][j] = I*(1-S)B[i][j] = I * (1 + ((S*np.cos(H - np.pi * (4/3)))/np.cos(np.pi * (10/9) - H)))R[i][j] = 3*I - (G[i][j]+B[i][j])img = cv2.merge((B*255, G*255, R*255))img = img.astype('uint8')return img