Frank Lioty's picture

Desature a texture

Hi guy,
I have a .png with transparency that I need to desaturate. I read perhaps I need to take the average R,G and B value of the bitmap then use:

G*.59
R*.3
B*.11

but I can't make it work. This is my code:

private void Average_Color(Bitmap bitmap, ref double r, ref double g, ref double b) {
  Color c = new Color();
  int pixel_number = 0;
  r = 0;
  g = 0;
  b = 0;
 
  for (int i = 0; i < bitmap.Width; i++) {
    for (int j = 0; j < bitmap.Height; j++) {
      c = bitmap.GetPixel(i, j);
        r += c.R;
        g += c.G;
        b += c.B;
        pixel_number++;
    }
  }
  r /= pixel_number;
  g /= pixel_number;
  b /= pixel_number;
}

Then, first to paint my texture, I set the Color in this way:

Average(bitmap, ref r, ref g, ref b);
GL.Color3(r * 0.59 / 255, g * 0.3 /255, b * 0.11 / 255);
//here I draw my texture

I don't know why but it doesn't work (wrong color). I guess it's something wrong in Average_Color or maybe I don't have to use GL.Color3?

Inline Images

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
mOfl's picture

What exactly do you need the GL.Color3 for? I don't understand what you are trying to achieve. If you want to desaturate your texture, you have to desaturate each pixel of the texture data, not just subtract a single color or value from the whole texture. There are many ways to do rgb to grayscale, but the common way is to avarage r, g and b channel, so what you'd do would be first calculate the average value at each pixel ((r + g + b) / 3.0) and then interpolate between your current color and the grayscale color with the weight you want.

A more intuitive way would be to just convert the color space of the texture from rgb to hsv, do the saturation magic you want to do, and then convert it back to rgb and update the texture data.

Frank Lioty's picture

Thanks, done with the average value. Really cool :)