Can anyone explain why this code works as it does? (Desaturating colours)

edited June 2014 in Questions about Code

Hello i've been working on a project where i need to push a button and an image turns black/white (grey)

I found this code:

    for (int x=0; x<width; x++)
    {
      for (int y=0; y<height; y++)
      {
    color c = get(x,y);
     float red = red(c);
     float green = green(c);
     float blue = blue(c);
     int grey = (int)(red+green+blue)/3;
     color Color =color(grey,grey,grey);
     set(x,y,Color);
      }
}

It works great and the image turns grey, i just have no idea why? :S

Could anyone explain line from line why?

Thanks

Tagged:

Answers

  • edited June 2014 Answer ✓

    In RGB, shades of grey happens when R, G, B have the same value.
    That is, no channel is stronger than the others!

    background(100, 100, 100); same as background(100);.

    Actually, line #10 could be replaced by:
    color c = color(grey);

    http://processing.org/reference/color_.html
    http://processing.org/reference/color_datatype.html

  • Answer ✓

    There are three color channels: red, green, and blue. As @GoToLoop mentioned, when these have the same value then that represents some shade of grey (or white / black).

    The three floats in the code get the values of each color channel and the shade of grey is calculated by averaging the three color values. The averaging is done by summing the color channel values and then dividing by three (because there are three color channels).

  • Thanks guys :) Helped a lot.

Sign In or Register to comment.