Tags

, , , , ,

Commonly we choose shade of gray based on Lightness, average or luminosity.

  • Lightness:   gray level =  ½ × (max(R,G,B) + min(R,G,B))
  • Luminosity: gray level = 0.21 × R + 0.72 × G + 0.07 × B
  • Average: gray level = (R + G + B) ÷ 3
package graying;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 *
 * @author nayef
 */
public class GrayScaling {

    final static int average = 1;
    final static int lightness = 2;
    final static int lumin = 3;

 public BufferedImage getGrayScaleFromColor(String imagePath, int grayingAlgo) throws IOException {

        File imageFile = new File(imagePath);
        BufferedImage image;
        try {
            image = ImageIO.read(imageFile);
        } catch (IOException ex) {
            throw new IOException("Couldnt load Image");
        }

        Color c;
        Color tempColor;
        int red;
        int green;
        int blue;

        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                c = new Color(image.getRGB(x, y));
                red = c.getRed();
                green = c.getGreen();
                blue = c.getBlue();
                int grayScaleVal = getGrayScalevalue(red, green, blue, grayingAlgo);
                tempColor = new Color(grayScaleVal, grayScaleVal, grayScaleVal);
                image.setRGB(x, y, tempColor.getRGB());
            }
        }

        return image;
    }

    private int getGrayScalevalue(int red, int green, int blue, int algo) {

        if (algo == average) {
            return (red + green + blue) / 3;
        } else if (algo == lumin) {
            return (int) (0.21 * red + 0.72 * green + 0.07 * blue);
        } else if (algo == lightness) {
            return (int) (.5 * (getMax(red, green, blue) + getMin(red, green, blue)));
        } else {
            return -1;
        }

    }

    private int getMax(int r, int g, int b) {
        int max = r;
        if (g > max) {
            max = g;
        }
        if (b > max) {
            max = b;
        }
        return max;
    }

    private int getMin(int r, int g, int b) {
        int min = r;
        if (g < min) {
            min = g;
        }
        if (b < min) {
            min = b;
        }
        return min;
    }
}
original color pic

original color pic

Average scaling result

Average scaling result

result of lightness scaling

result of lightness scaling

result of lumin

result of lumin


					
Advertisements