Tags

, , , , ,

This little snippet comes from one of the lecture sources given in Stanford’s CS106A (GrayImage.java)


private int computeLuminosity(int r, int g, int b) {
	return GMath.round((0.299 * r) + (0.587 * g) + (0.114 * b));
}


Example usage:


//loop here to get one pixel at a time from an image, in this example, image is a 2D array of pixels.
for (int i = 0; i < height; i++) {
  for (int j = 0; j < width; j++) {
    pixel = image[i][j];
    // pixel.r,pixel.g,pixel.b are the red, green, blue values of a pixel (most likely pixel would normally be a 24bit integer, and this here would not make sense... but meh, this is an example.)
    int luminosity = computeLuminosity(pixel.r, pixel.g, pixel.b);
    grayPixel = makeRGBPixel(luminosity,luminosity,luminosity); // use luminosity as R,G and B value.
    //replace pixel with grayPixel in-place, or into a new image you create..whatever
  }
}

The code sample is in Java, but it can be adapted to any language very easily.

Advertisements