How to convert pixels to gray scale?
Solution 1
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.
Solution 2
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);
}
Related videos on Youtube
An SO User
Updated on October 06, 2022Comments
-
An SO User over 1 year
Ok, I am using
Processing
which allows me to access pixels of any image asint[]
. What I now want to do is to convert the image to gray-scale. Each pixel has a structure as shown below:...........PIXEL............ [red | green | blue | alpha] <-8--><--8---><--8--><--8-->
Now, what transformations do I need to apply to individual RGB values to make the image gray-scale ??
What I mean is, how much do I add / subtract to make the image gray-scale ?Update
I found a few methods here: http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/
-
An SO User almost 11 yearsI also found a few more methods: johndcook.com/blog/2009/08/24/…
-
Geeky Guy almost 11 yearsone up to your comment because of the luminosity method described there. I never thought about weighting the values like that.
-
An SO User almost 11 yearsI want to get more into image processing.. Where do I begin ??
-
Geeky Guy almost 11 years@LittleChild I think Programmers is a good place to ask that. As for me, I learned a little on college, but never went into much depth on it. Now I wanna make videogames and I want to get more into it as well.
-
An SO User almost 11 yearsNo, He is using
Processing
which is a dialect of Java