我们正式的来看一下这些代码原理的实现,这么多循迹的运用就是没有人写,真鸡儿过分。
闲话不多说,先放个转换色彩空间的代码来看看:
# Python3 program change RGB Color
# Model to HSV Color Model
def rgb_to_hsv(r, g, b):
# R, G, B values are divided by 255
# to change the range from 0..255 to 0..1:
r, g, b = r / 255.0, g / 255.0, b / 255.0
# h, s, v = hue, saturation, value
cmax = max(r, g, b) # maximum of r, g, b
cmin = min(r, g, b) # minimum of r, g, b
diff = cmax-cmin # diff of cmax and cmin.
# if cmax and cmax are equal then h = 0
if cmax == cmin:
h = 0
# if cmax equal r then compute h
elif cmax == r:
h = (60 * ((g - b) / diff) + 360) % 360
# if cmax equal g then compute h
elif cmax == g:
h = (60 * ((b - r) / diff) + 120) % 360
# if cmax equal b then compute h
elif cmax == b:
h = (60 * ((r - g) / diff) + 240) % 360
# if cmax equal zero
if cmax == 0:
s = 0
else:
s = (diff / cmax) * 100
# compute v
v = cmax * 100
return h, s, v
print(rgb_to_hsv(0, 51, 238))
作用是RGB空间转到HSV的空间
一开始的计算过程很简单
#R、G、B值除以255
#更改范围从0.255到0.1。有点像归一化的意思,当然也可以写一下关于归一化的通式是什么样子的:
n-min
-----
max-min
中间的横杠是除号,假装是除号。。。
转换公式
也可以看这个,都是一样的
r, g, b = r / 255.0, g / 255.0, b / 255.0
cmax = max(r, g, b) # maximum of r, g, b
cmin = min(r, g, b) # minimum of r, g, b
diff = cmax-cmin # diff of cmax and cmin.
if cmax == cmin:
h = 0
elif cmax == r:
h = (60 * ((g - b) / diff) + 360) % 360
elif cmax == g:
h = (60 * ((b - r) / diff) + 120) % 360
elif cmax == b:
h = (60 * ((r - g) / diff) + 240) % 360
if cmax == 0:
s = 0
else:
s = (diff / cmax) * 100
v = cmax * 100
具体的转换公式就是这样
https://ww2.mathworks.cn/help/matlab/ref/rgb2hsv.html
对于一个理科狗来说,MATLAB嘤嘤嘤
HSV = rgb2hsv(RGB)
hsvmap = rgb2hsv(rgbmap)
这个是语法
具体用法是:
示
将 RGB 图像的红色、绿色和蓝色值转换为 HSV 图像的色调、饱和度和明度 (HSV) 值。
启动!
>> rgb = prism(6)
rgb =
1.0000 0 0
1.0000 0.5000 0
1.0000 1.0000 0
0 1.0000 0
0 0 1.0000
0.6667 0 1.0000
>> hsv = rgb2hsv(rgb)
hsv =
0 1.0000 1.0000
0.0833 1.0000 1.0000
0.1667 1.0000 1.0000
0.3333 1.0000 1.0000
0.6667 1.0000 1.0000
0.7778 1.0000 1.0000
先直接转换一下看看结果
再转回去也得说一下,不想敲代码的可以,可以在MATLAB里面输入以下的一串东西:
openExample('graphics/Hsv2RgbColormapExample')
hsv = [.6 1 1; .6 .7 1; .6 .5 1; .6 .3 1; .6 0 1];
rgb = hsv2rgb(hsv);
surf(peaks);
colormap(rgb);
colorbar
C:\Users\CY-306\Documents\MATLAB\Examples\graphics
这些例子可以在计算机的这个位置找到