RGB和HSV的相互转换的代码

首先是结构体的定义,RGB和HSV。

typedef struct{
 unsigned char R;
 unsigned char G;
 unsigned char B;
}COLOR_RGB;

 

typedef struct{
 float H;
 float S;
 float V;
}COLOR_HSV;

 

RGB空间颜色向HSV空间颜色转变

void RGB_TO_HSV(const COLOR_RGB* input,COLOR_HSV* output)
 {
 float r,g,b,minRGB,maxRGB,deltaRGB;

 r = input->R/255.0f;
 g = input->G/255.0f;
 b = input->B/255.0f;
    minRGB = MIN(r,MIN(g,b));
    maxRGB = MAX(r,MAX(g,b));
 deltaRGB = maxRGB - minRGB;

 output->V = maxRGB;
 if(maxRGB != 0.0)
  output->S = deltaRGB / maxRGB;
 else
  output->S = 0.0;
 if (output->S <= 0.0)
 {
  output->H = -1.0f;
 }
 else
 {
  if (r == maxRGB)
  {
   output->H = (g-b)/deltaRGB;
  }
  else
  {
   if (g == maxRGB)
   {
    output->H = 2.0 + (b-r)/deltaRGB;
   }
   else
   {
    if (b == maxRGB)
    {
     output->H = 4.0 + (r-g)/deltaRGB;
    }
   }
  }
  output->H = output->H * 60.0;
  if (output->H < 0.0)
  {
   output->H += 360;
  }
  output->H /= 360;
 }

 }


HSV空间颜色向RGB空间颜色转变
void HSV_TO_RGB(COLOR_HSV* input,COLOR_RGB* output)
 {
 float R,G,B;
 int k;
 float aa,bb,cc,f;
 if (input->S <= 0.0)
  R = G = B = input->V;
 else
 {
  if (input->H == 1.0)
   input->H = 0.0;
  input->H *= 6.0;
  k = floor(input->H);
  f = input->H - k;
  aa = input->V * (1.0 - input->S);
  bb = input->V * (1.0 - input->S * f);
  cc = input->V * (1.0 -(input->S * (1.0 - f)));
  switch(k)
  {
  case 0:
   R = input->V;
   G = cc;
   B =aa;
   break;
  case 1:
   R = bb;
   G = input->V;
   B = aa;
   break;
  case 2:
   R =aa;
   G = input->V;
   B = cc;
   break;
  case 3:
   R = aa;
   G = bb;
   B = input->V;
   break;
  case 4:
   R = cc;
   G = aa;
   B = input->V;
   break;
  case 5:
   R = input->V;
   G = aa;
   B = bb;
   break;
  }
 }
 output->R = R * 255;
 output->G = G * 255;
 output->B = B * 255;
 }

以上的两个方法都是c语言实现的,各位可以直接拿去用。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值