Python-opencv 读取图片RGB/HSI通道值
基于py-opencv2的彩色图片RGB/HSI三通道值读取
·
1. RGB值
RGB即使用红色(R)、绿色(G)、蓝色(B)作为三元色,以三者不同比例的混合产生不同颜色。
dic = {0:'牡丹粉', 1:'苋菜红', 2:'鼠背灰', 3:'卵石紫', 4:'钢青', 5:'竹绿', 6:'油菜花黄'}
img_all = [[[0 for i in range(3)]for j in range(7)]for k in range(1)]
for i in range(1, 7):
path = str(i) + '.png'
img = cv2.imread(path)
b= img[0][0][0]
g= img[0][0][1]
r= img[0][0][2]
print(f'{dic[i-1]}:\t[r,g,b]:[{r},{g},{b}]')
结果:
牡丹粉: [r,g,b]:[164,27,41]
苋菜红: [r,g,b]:[113,85,90]
鼠背灰: [r,g,b]:[47,22,28]
卵石紫: [r,g,b]:[20,34,51]
钢青: [r,g,b]:[27,166,131]
竹绿: [r,g,b]:[247,215,64]
代码中之所以并非以RGB的顺序读取,是因为cv2的文档中指出虽然cv2读取的格式是“RGB”但是是以BGR的顺序读取
输出图像验证:
dic = {0:'牡丹粉', 1:'苋菜红', 2:'鼠背灰', 3:'卵石紫', 4:'钢青', 5:'竹绿', 6:'油菜花黄'}
img_all = [[[0 for i in range(3)]for j in range(7)]for k in range(1)]
for i in range(1, 7):
path = str(i) + '.png'
img = cv2.imread(path)
b= img[0][0][0]
g= img[0][0][1]
r= img[0][0][2]
img_all[0][i-1][0] = r
img_all[0][i-1][1] = g
img_all[0][i-1][2] = b
print(f'{dic[i-1]}:\t[r,g,b]:[{r},{g},{b}]')
plt.imshow(img_all)
原始图像:
输出图像:
2. RGB --> HSI
用色调(H)、色饱和度(S)、亮度描述色彩(I)。HSI色彩空间可以用一个圆锥空间模型来描述。通常把色调和饱和度通称为色度,用来表示颜色的类别与深浅程度。
转换公式:
转换代码:
def Rgb2Hsi(r, g, b):
r /= 255
g /= 255
b /= 255
eps = 1e-8
h, s, i = 0, 0, 0
sum_rgb = r + g + b
min_rgb = min(r, g, b)
s = 1 - 3 * min_rgb / (sum_rgb + eps)
h = np.arccos((0.5 * (r + r - g - b)) / (((r - g) ** 2 + (r - b) * (g - b) + eps)) ** 0.5)
if b > g:
h = 2 * np.pi - h
h = h / (2 * np.pi)
if s == 0:
h = 0
i = sum_rgb / 3
return round(h, 2), round(s, 2), round(i, 2)
dic = {0:'牡丹粉', 1:'苋菜红', 2:'鼠背灰', 3:'卵石紫', 4:'钢青', 5:'竹绿', 6:'油菜花黄'}
for i in range(7):
path = str(i) + '.png'
img = cv2.imread(path)
b= img[0][0][0]
g= img[0][0][1]
r= img[0][0][2]
H, S, I = Rgb2Hsi(r, g, b)
print(f'{dic[i]}:\t[r,g,b]:[{r},{g},{b}]\t[h,s,i]:[{H},{S},{I}]')
结果:
牡丹粉: [r,g,b]:[234,159,161] [h,s,i]:[1.0,0.14,0.72]
苋菜红: [r,g,b]:[164,27,41] [h,s,i]:[0.99,0.65,0.3]
鼠背灰: [r,g,b]:[113,85,90] [h,s,i]:[0.97,0.11,0.38]
卵石紫: [r,g,b]:[47,22,28] [h,s,i]:[0.96,0.32,0.13]
钢青: [r,g,b]:[20,34,51] [h,s,i]:[0.59,0.43,0.14]
竹绿: [r,g,b]:[27,166,131] [h,s,i]:[0.46,0.75,0.42]
油菜花黄:[r,g,b]:[247,215,64] [h,s,i]:[0.14,0.63,0.69]
更多推荐
已为社区贡献3条内容
所有评论(0)