#include <iostream.h>
#include <math.h>
typedef unsigned char uchar;
#define eps 1e-12
struct HSV
{
double H;
double S;
double V;
};
struct RGB
{
uchar R;
uchar G;
uchar B;
};
uchar Max2(uchar &x, uchar &y)
{
return x > y ? x : y;
}
uchar Max3(uchar &a, uchar &b, uchar &c)
{
uchar tmp = Max2(a, b);
return Max2(tmp, c);
}
uchar Min2(uchar &x, uchar &y)
{
return x < y ? x : y;
}
uchar Min3(uchar &a, uchar &b, uchar &c)
{
uchar tmp = Min2(a, b);
return Min2(tmp, c);
}
HSV RGB2HSV(RGB &rgb)
{
uchar max = Max3(rgb.R, rgb.G, rgb.B);
uchar min = Min3(rgb.R, rgb.G, rgb.B);
HSV hsv;
if (max == min)
{
hsv.H = 0;
hsv.S = 0;
hsv.V = max;
return hsv;
}
if (rgb.R == max)
{
hsv.H = (double)(rgb.G - rgb.B) / (max - min);
}
else if (rgb.G == max)
{
hsv.H = 2.0 + (double)(rgb.B - rgb.R) / (max - min);
}
else
{
hsv.H = 4.0 + (double)(rgb.R - rgb.G) / (max - min);
}
hsv.H *= 60;
if (hsv.H < 0)
{
hsv.H += 360;
}
hsv.V = max;
hsv.S = double(max - min) / max;
return hsv;
}
RGB HSV2RGB(HSV &hsv)
{
RGB rgb;
if (fabs(hsv.S) < eps)
{
rgb.R = rgb.G = rgb.B = (uchar)hsv.V;
}
else
{
hsv.H /= 60;
int i = int(hsv.H);
double f = hsv.H - i;
double a = double(hsv.V * (1 - hsv.S));
double b = double(hsv.V * (1 - hsv.S * f));
double c = double(hsv.V * (1 - hsv.S * (1 - f)));
switch (i)
{
case 0:
rgb.R = (uchar)ceil(hsv.V);
rgb.G = (uchar)ceil(c);
rgb.B = (uchar)ceil(a);
break;
case 1:
rgb.R = (uchar)ceil(b);
rgb.G = (uchar)ceil(hsv.V);
rgb.B = (uchar)ceil(a);
break;
case 2:
rgb.R = (uchar)ceil(a);
rgb.G = (uchar)ceil(hsv.V);
rgb.B = (uchar)ceil(c);
break;;
case 3:
rgb.R = (uchar)ceil(a);
rgb.G = (uchar)ceil(b);
rgb.B = (uchar)ceil(hsv.V);
break;
case 4:
rgb.R = (uchar)ceil(c);
rgb.G = (uchar)ceil(a);
rgb.B = (uchar)ceil(hsv.V);
break;
case 5:
rgb.R = (uchar)ceil(hsv.V);
rgb.G = (uchar)ceil(a);
rgb.B = (uchar)ceil(b);
break;
default:
rgb.R = rgb.G = rgb.B = 0;
}
}
return rgb;
}
int main()
{
RGB rgb = {100, 90, 125};
HSV hsv = RGB2HSV(rgb);
RGB ret = HSV2RGB(hsv);
cout<<(int)ret.R<<endl;
cout<<(int)ret.G<<endl;
cout<<(int)ret.B<<endl;
return 0;
}
(orphan006) |