Posted on 2007-10-31 09:17
济公 阅读(5118)
评论(6) 编辑 收藏 引用 所属分类:
ImageProc
在开发有关bitmap方面的程序时,经常需要将位图的颜色在RGB和HSV色彩空间之间转换,该颜色转换由C++实现:
RGB颜色空间转换为HSV空间颜色值:
void Rgb2Hsv(float R, float G, float B, float& H, float& S, float&V)
{
// r,g,b values are from 0 to 1
// h = [0,360], s = [0,1], v = [0,1]
// if s == 0, then h = -1 (undefined)
float min, max, delta,tmp;
tmp = min(R, G);
min = min( tmp, B );
tmp = max( R, G);
max = max(tmp, B );
V = max; // v
delta = max - min;
if( max != 0 )
S = delta / max; // s
else
{
// r = g = b = 0 // s = 0, v is undefined
S = 0;
H = UNDEFINEDCOLOR;
return;
}
if( R == max )
H = ( G - B ) / delta; // between yellow & magenta
else if( G == max )
H = 2 + ( B - R ) / delta; // between cyan & yellow
else
H = 4 + ( R - G ) / delta; // between magenta & cyan
H *= 60; // degrees
if( H < 0 )
H += 360;
}
HSV颜色空间转换为RGB空间颜色值:
void Hsv2Rgb(float H, float S, float V, float &R, float &G, float &B)
{
int i;
float f, p, q, t;
if( S == 0 )
{
// achromatic (grey)
R = G = B = V;
return;
}
H /= 60; // sector 0 to 5
i = floor( H );
f = H - i; // factorial part of h
p = V * ( 1 - S );
q = V * ( 1 - S * f );
t = V * ( 1 - S * ( 1 - f ) );
switch( i )
{
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;
default: // case 5:
R = V;
G = p;
B = q;
break;
}
}