RGB 2 HSI && HSI 2 RGB

本文介绍了一种从RGB颜色空间转换到HSI颜色空间的方法,并提供了逆转换的算法实现。通过数学公式和代码详细解释了如何进行颜色空间的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**************************************************************************
* Func: rgb2hsi *
* *
* Desc: converts a value from RGB to HSI color space *
* *
* Params: r - normalized red value *
* g - normalized green value *
* b - normalized blue value *
* h - hue in degrees *
* s - normalized saturation *
* i - normalized intensity *
**************************************************************************/

// http://wangzaiqiqi.taobao.com


void rgb2hsi(float r,float g,float b,float *h,float *s,float *i)
{
float min, max; /* minimum and maximum RGB values */
float angle; /* temp variable used to compute Hue */

if((r<=g) && (r<=b))
min = r;
else if((g<=r) && (g<=b))
min = g;
else
min =b;

/* compute intensity */
*i=(r + g + b) / 3.0;

/* compute hue and saturation */
if((r==g) && (g==b)) /* gray-scale */
{
*s = 0.0;
*h = 0.0;
return;
}
else
{
*s= 1.0 - (3.0 / (r + g + b)) * min;
angle = (r - 0.5 * g - 0.5 * b) /
sqrt((r - g) * (r - g)+(r - b) * (g - b));
*h = acos(angle);
*h *= 57.29577951; /* convert to degrees */
}
if(b>g)
*h = 360.0 - *h;
}


/***************************************************************************
* Func: hsi2rgb *
* *
* Desc: converts a value from HSI to RGB color space *
* *
* Params: r - normalized red *
* g - normalized green *
* b - normalized blue *
* h - hue in degrees *
* s - normalized saturation *
* i - normalized intensity *
***************************************************************************/
// http://wangzaiqiqi.taobao.com


void hsi2rgb(float *r,float *g,float *b,float h,float s,float i)
{
float angle1, angle2, scale, temp, denom; /* temp variables */

if(i==0.0) /* BLACK */
{
*r = 0.0;
*g = 0.0;
*b = 0.0;
return;
}
if(s==0.0) /* gray-scale H is undefined*/
{
*r = i;
*g = i;
*b = i;
return;
}
if(h<0.0)
h+=360.0;
scale = 3.0 * i;
if(h<=120.0)
{
angle1=h*0.017453293; /* convert to radians - mul by pi/180 */
angle2=(60.0-h)*0.017453293;

*b = (1.0-s)/3.0;
*r = (1.0 + (s*cos(angle1)/cos(angle2)))/3.0;
*g = 1.0-*r-*b;
*b *= scale;
*r *= scale;
*g *= scale;
}
else if((h>120.0) && (h<=240.0))
{
h -= 120.0;
angle1=h*0.017453293; /* convert to radians - mul by pi/180 */
angle2=(60.0-h)*0.017453293;

*r = (1.0-s)/3.0;
*g = (1.0 + (s*cos(angle1)/cos(angle2)))/3.0;
*b = 1.0 - *r - *g;
*r *= scale;
*g *= scale;
*b *= scale;
}
else
{
h -= 240.0;
angle1=h*0.017453293; /* convert to radians - mul by pi/180 */
angle2=(60.0-h)*0.017453293;

*g = (1.0-s)/3.0;
*b = (1.0 + (s*cos(angle1)/cos(angle2)))/3.0;
*r = 1.0 - *g - *b;
*r *= scale;
*g *= scale;
*b *= scale;
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值