一、简介
RGB 是我们接触最多的颜色空间,分别为红色(R),绿色(G)和蓝色(B)。HSV 是用色调H,饱和度S,明亮度V来描述颜色的变化,H取值范围为0°~360°,从红色开始按逆时针方向计算,红色为0°,绿色为120°,蓝色为240°。饱和度S越高,颜色则深而艳。光谱色的白光成分为0,饱和度达到最高。通常取值范围为0%~100%,值越大,颜色越饱和。H表示颜色明亮的程度,对于光源色,明度值与发光体的光亮度有关;对于物体色,此值和物体的透射比或反射比有关。通常取值范围为0%(黑)到100%(白)。
二、从RGB转换到HSV
转换代码如下:
-
float retmax(
float a,
float b,
float c)//求最大值
-
{
-
float
max =
0;
-
max = a;
-
if(
max
-
max = b;
-
if(
max
-
max = c;
-
return
max;
-
}
-
float retmin(
float a,
float b,
float c)//求最小值
-
{
-
float
min =
0;
-
min = a;
-
if(
min>b)
-
min = b;
-
if(
min>c)
-
min = c;
-
return
min;
-
}
-
//R,G,B参数传入范围(
0~
100)
-
//转换结果h(
0~
360),s(
0~
100),v(
0~
100)
-
void rgb_to_hsv(
float *h,
float *s,
float *v,
float R,
float G,
float B)
-
{
-
float
max =
0,
min =
0;
-
R = R/
100;
-
G = G/
100;
-
B = B/
100;
-
-
max = retmax(R,G,B);
-
min = retmin(R,G,B);
-
*v =
max;
-
if(
max ==
0)
-
*s =
0;
-
else
-
*s =
1 - (
min/
max);
-
-
if(
max ==
min)
-
*h =
0;
-
else
if(
max == R && G>=B)
-
*h =
60*((G-B)/(
max-
min));
-
else
if(
max == R && G
-
*h =
60*((G-B)/(
max-
min)) +
360;
-
else
if(
max == G)
-
*h =
60*((B-R)/(
max-
min)) +
120;
-
else
if(
max == B)
-
*h =
60*((R-G)/(
max-
min)) +
240;
-
-
*v = *v *
100;
-
*s = *s *
100;
-
}
三、从HSV转换到RGB
1、转换公式如下:
2、转换代码如下:
-
//参数入参范围h(0~360),s(0~100),v(0~100),这里要注意,要把s,v缩放到0~1之间
-
//转换结果R(0~100),G(0~100),B(0~100),如需转换到0~255,只需把后面的乘100改成乘255
-
void
hsv_to_rgb
(int h,int s,int v,float *R,float *G,float *B)
-
{
-
float
C
=
0,X =
0,Y =
0,Z =
0;
-
int i=
0;
-
float H=(
float)(h);
-
float S=(
float)(s)/
100.0;
-
float V=(
float)(v)/
100.0;
-
if(S ==
0)
-
*R = *G = *B = V;
-
else
-
{
-
H = H/
60;
-
i = (
int)H;
-
C = H - i;
-
-
X = V * (
1 - S);
-
Y = V * (
1 - S*C);
-
Z = V * (
1 - S*(
1-C));
-
switch(i){
-
case
0 : *R = V; *G = Z; *B = X;
break;
-
case
1 : *R = Y; *G = V; *B = X;
break;
-
case
2 : *R = X; *G = V; *B = Z;
break;
-
case
3 : *R = X; *G = Y; *B = V;
break;
-
case
4 : *R = Z; *G = X; *B = V;
break;
-
case
5 : *R = V; *G = X; *B = Y;
break;
-
}
-
}
-
*R = *R *
100;
-
*G = *G *
100;
-
*B = *B *
100;
-
}