织梦CMS - 轻松建站从此开始!

罗索

rgb hsv 互换

落鹤生 发布于 2012-03-01 15:27 点击:次 
RGB与HSV之间互相转换的实现代码。
TAG:

#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)
本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201203/15775.html]
本文出处:百度博客 作者:orphan006
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容