1.实现RGB到HSV的转换函数,函数声明:HSV RGB2HSV(COLORREF c)
函数功能:把COLORREF类对象c的颜色信息转换成一个HSV类对象返回。
代码:
#include
#include
#include
#include
using namespace std;
//RGB->HSV
class HSV //HSV类
{
public:
double H, S, V;
HSV() {}
HSV(double h, double s, double v) :H(h), S(s), V(v) {}
};
HSV RGB2HSV(COLORREF c)//RGB至HSV转换函数
{
//从COLORREF类对象c中获取颜色RGB值
BYTE R = GetRValue(c);
BYTE G = GetGValue(c);
BYTE B = GetBValue(c);
double H, S, V;
//转换公式
R = R / 255, G = G / 255, B = B / 255;
V = max(R, G, B);
if (V != 0)
{
S = (V - min(R, G, B)) / V;
if (V = R)
{
H = (60 * (G - B)) / V - min(R, G, B);
if (H < 0)
{
H = H + 360;
return HSV(H, S, V);
}
return HSV(H, S, V);
}
if (V = G)
{
H = 120 + ((60 * (B - R)) / (V - min(R, G, B)));
if (H < 0)
{
H = H + 360;
return HSV(H, S, V);
}
return HSV(H, S, V);
}
if (V = B)
{
H = 240 + ((60 * (R - G)) / (V - min(R, G, B)));
if (H < 0)
{
H = H + 360;
return HSV(H, S, V);
}
return HSV(H, S, V);
}
}
else
{
S = 0;
H = 0;
return HSV(H, S, V);
}
}
2、实现HSV到RGB的转换函数,函数声明:COLORREF HSV2RGB(HSV hsv)
函数功能:把HSV类对象hsv的颜色信息转换成一个COLORREF类对象返回。
代码:
#include
#include
#include
#include
using namespace std;
//HSV->RGB
COLORREF HSV2RGB(HSV hsv)
{
//定义变量
BYTE R, G, B;
double H, S, V;
H = hsv.H;
S = hsv.S;
V = hsv.V;
//转换公式
double C, X, m;
C = V * S;
X = C * (1 - (abs(((int)H / 60) % 2 - 1)));
m = V - C;
if (H >= 0 && H < 60)
{
R = C;
G = X;
B = 0;
R = (R + m) * 255;
G = (G + m) * 255;
B = (B + m) * 255;
//返回COLORREF类型的值
COLORREF c;
c = RGB(R, G, B);
return c;
}
if (H >= 60 && H < 120)
{
R = X;
G = C;
B = 0;
R = (R + m) * 255;
G = (G + m) * 255;
B = (B + m) * 255;
//返回COLORREF类型的值
COLORREF c;
c = RGB(R, G, B);
return c;
}
if (H >= 120 && H < 180)
{
R = 0;
G = C;
B = X;
R = (R + m) * 255;
G = (G + m) * 255;
B = (B + m) * 255;
//返回COLORREF类型的值
COLORREF c;
c = RGB(R, G, B);
return c;
}
if (H >= 180 && H < 240)
{
R = 0;
G = X;
B = C;
R = (R + m) * 255;
G = (G + m) * 255;
B = (B + m) * 255;
//返回COLORREF类型的值
COLORREF c;
c = RGB(R, G, B);
return c;
}
if (H >= 240 && H < 300)
{
R = X;
G = 0;
B = C;
R = (R + m) * 255;
G = (G + m) * 255;
B = (B + m) * 255;
//返回COLORREF类型的值
COLORREF c;
c = RGB(R, G, B);
return c;
}
if (H >= 300 && H < 360)
{
R = C;
G = 0;
B = X;
R = (R + m) * 255;
G = (G + m) * 255;
B = (B + m) * 255;
//返回COLORREF类型的值
COLORREF c;
c = RGB(R, G, B);
return c;
}
}