Algorithm RGB -> HSV
0 <= R, G, B <= 1
0 <= H <= 360
0 <= S, V <= 1
max = MAX( R, G, B )
min = MIN( R, G, B )
1) max = min
h = 0
2) max = R
h = (60 * (G - B) / (max - min) + 360 ) mod 360
3) max = G
h = 60 * (B - R) / (max - min) + 120
4) max = B
h = 60 * (R - G) / (max - min) + 240
1) max = 0
S = 0
2) otherwise
S = (max - min) / max = 1 - (min / max)
V = max
Algorithm HSV -> RGB
0 <= R, G, B <= 1
0 <= H < 360
0 <= S, V <= 1
Hi = INT(H /60.0) mod 6
F = H / 60.0 - INT(H /60.0)
P = V * (1 - S)
Q = V * (1 - F * S)
T = V * (1 - (1 - F) * S)
1) Hi = 0
R = V
G = T
B = P
2) Hi = 1
R = Q
G = V
B = P
3) Hi = 2
R = P
G = V
B = T
4) Hi = 3
R = P
B = Q
G = V
5) Hi = 4
R = T
G = P
B = V
6) Hi = 5
R = V
G = P
B = Q
// r, g, b are [0, 1]
// h is [0, 360)
// s is [0, 1]
// v is [0, 1]
#define RGB2HSV( r, g, b, h, s, v ) /
I_MACRO_BEGIN /
if ( (r) == (g) && (g) == (b) ) /
{ /
(h) = 0; /
(s) = 0; /
(v) = (g); /
} /
else /
{ /
float _max; /
float _min; /
if ( (r) > (g) ) /
{ /
_min = (g) > (b) ? (b) : (g); /
if ( (r) > (b) ) /* r is max */ /
{ /
_max = (r); /
(h) = ((int) (60.0 * ((g) - (b)) / ((r) - _min) + 0.5) + 360) % 360; /
} /
else /* b is max */ /
{ /
_max = (b); /
(h) = (int) (60.0 * ((r) - (g)) / ((b) - _min) + 0.5) + 240; /
} /
} /
else /* (r) <= (g) */ /
{ /
_min = (r) > (b) ? (b) : (r); /
if ( (g) > (b) ) /* g is max */ /
{ /
_max = (g); /
(h) = (int) (60.0 * ((b) - (r)) / ((g) - _min) + 0.5) + 120; /
} /
else /* b is max */ /
{ /
_max = (b); /
(h) = (int) (60.0 * ((r) - (g)) / ((b) - _min) + 0.5) + 240; /
} /
} /
(v) = _max; /
if ( _max == 0 ) /
{ /
(s) = 0; /
} /
else /
{ /
(s) = (float) (_max - _min) / (float) _max; /
} /
} /
I_MACRO_END
// h is [0, 360)
// s is [0, 1]
// v is [0, 1]
// r, g, b are [0, 255]
#define HSV2RGB( h, s, v, r, g, b ) /
I_MACRO_BEGIN /
int _hi; /
float _f; /
float _p; /
float _q; /
float _t; /
assert( (h) < 360 ); /
_hi = ((int) (h) / 60) % 6; /
_f = (float) (h) / 60.0 - (int) ((int) (h) / 60); /
_p = (v) * (1.0 - (s)); /
_q = (v) * (1.0 - _f * (s)); /
_t = (v) * (1.0 - (1.0 - _f) * (s)); /
switch ( _hi ) /
{ /
case 0: /
(r) = (v); /
(g) = (_t); /
(b) = (_p); /
break; /
case 1: /
(r) = (_q); /
(g) = (v); /
(b) = (_p); /
break; /
case 2: /
(r) = (_p); /
(g) = (v); /
(b) = (_t); /
break; /
case 3: /
(r) = (_p); /
(g) = (_q); /
(b) = (v); /
break; /
case 4: /
(r) = (_t); /
(g) = (_p); /
(b) = (v); /
break; /
case 5: /
(r) = (v); /
(g) = (_p); /
(b) = (_q); /
break; /
} /
I_MACRO_END