How to convert pixels to gray scale?

霸气de小男生 提交于 2019-12-04 04:24:39

For each pixel, the value for the red, green and blue channels should be their averages. Like this:

int red = pixel.R;
int green = pixel.G;
int blue = pixel.B;

pixel.R = pixel.G = pixel.B = (red + green + blue) / 3;

Since in your case the pixel colors seem to be stored in an array rather than in properties, your code could end up looking like:

int red = pixel[0];
int green = pixel[1];
int blue = pixel[2];

pixel[0] = pixel[1] = pixel[2] = (red + green + blue) / 3;

The general idea is that when you have a gray scale image, each pixel's color measures only the intensity of light at that point - and the way we perceive that is the average of the intensity for each color channel.

user2468700

The following code loads an image and cycle through its pixels, changing the saturation to zero and keeping the same hue and brightness values.

PImage img;

void setup () {
    colorMode(HSB, 100);
    img = loadImage ("img.png");
    size(img.width,img.height);
    color sat = color (0,0,0);

    img.loadPixels();

    for (int i = 0; i < width * height; i++) {
        img.pixels[i]=color (hue(img.pixels[i]), sat, brightness(img.pixels[i]));
    }

    img.updatePixels();
    image(img,0,0);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!