天天看点

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语言实现的,各位可以直接拿去用。

继续阅读