Main Menu

Menu

Wednesday 10 August 2011

RGB to HSV method in C#

because i saw many confusing methods, I combined some of them
so i post this one that works very nice:

public static Hsv RGB_to_HSV(Rgb rgb)
       {
           int rgb_max = (int)Math.Max(rgb.Red, Math.Max(rgb.Green, rgb.Blue));
           int rgb_min = (int)Math.Min(rgb.Red, Math.Min(rgb.Green, rgb.Blue));
           Hsv hsv = new Hsv();
           hsv.Value = rgb_max;
           if (hsv.Value == 0)
           {
               hsv.Hue = hsv.Satuation = 0;
               return hsv;
           }
           hsv.Satuation = 255 * (rgb_max - rgb_min) / hsv.Value;
           if (hsv.Satuation == 0)
           {
               hsv.Hue = 0;
               return hsv;
           }
           /* Compute hue */
           if (rgb_max == rgb.Red)
           {
               hsv.Hue = 0 + 43 * (rgb.Green - rgb.Blue) / (rgb_max - rgb_min);
           }
           else if (rgb_max == rgb.Green)
           {
               hsv.Hue = 85 + 43 * (rgb.Blue - rgb.Red) / (rgb_max - rgb_min);
           }
           else /* rgb_max == rgb.b */
           {
               hsv.Hue = 171 + 43 * (rgb.Red - rgb.Green) / (rgb_max - rgb_min);
           }
           return hsv;

       }

Cheers!

No comments:

Post a Comment