python–RGB转HSV

python–RGB转HSV

RGB:颜色空间相对简单,也*为普遍,就分为三个颜色通道,分别为红色,绿色,蓝色这三种基本色调的值,然后将这三个颜色融合在一起,也就成为一种颜色。

HSV:是个六棱锥模型,这个模型中颜色的参数分别是:色调(H),饱和度(S),明度(V)。

为什么使用HSV去判断色差:

用RGB比较颜色之间的相似度时,往往一个通道的一点改变,会导致*后融合在一起的颜色发生巨大变化,而如果三个通道的同时改变,却只会使*后的明暗发生变化,色调并不会产生巨大变化。
RGB TO HSV
def rgb2hsv(r, g, b):
r, g, b = r/255.0, g/255.0, b/255.0
mx = max(r, g, b)
mn = min(r, g, b)
df = mx-mn
if mx == mn:
h = 0
elif mx == r:
h = (60 * ((g-b)/df) + 360) % 360
elif mx == g:
h = (60 * ((b-r)/df) + 120) % 360
elif mx == b:
h = (60 * ((r-g)/df) + 240) % 360
if mx == 0:
s = 0
else:
s = df/mx
v = mx
return h, s, v

计算HSV的距离

def HSVDistance(hsv_1,hsv_2):
H_1,S_1,V_1 = hsv_1
H_2,S_2,V_2 = hsv_2
R=100
angle=30
h = R * math.cos(angle / 180 * math.pi)
r = R * math.sin(angle / 180 * math.pi)
x1 = r * V_1 * S_1 * math.cos(H_1 / 180 * math.pi);
y1 = r * V_1 * S_1 * math.sin(H_1 / 180 * math.pi);
z1 = h * (1 – V_1);
x2 = r * V_2 * S_2 * math.cos(H_2 / 180 * math.pi);
y2 = r * V_2 * S_2 * math.sin(H_2 / 180 * math.pi);
z2 = h * (1 – V_2);
dx = x1 – x2;
dy = y1 – y2;
dz = z1 – z2;
return math.sqrt(dx * dx + dy * dy + dz * dz)

HSV To RGB

def hsv2rgb(h, s, v):
h = float(h)
s = float(s)
v = float(v)
h60 = h / 60.0
h60f = math.floor(h60)
hi = int(h60f) % 6
f = h60 – h60f
p = v * (1 – s)
q = v * (1 – f * s)
t = v * (1 – (1 – f) * s)
r, g, b = 0, 0, 0
if hi == 0: r, g, b = v, t, p
elif hi == 1: r, g, b = q, v, p
elif hi == 2: r, g, b = p, v, t
elif hi == 3: r, g, b = p, q, v
elif hi == 4: r, g, b = t, p, v
elif hi == 5: r, g, b = v, p, q
r, g, b = int(r * 255), int(g * 255), int(b * 255)
return r, g, b