0

I don't can convert exactely my rgb image to an gray image..

My final image it's to dark, and affects my work.

I use this code:

public static BufferedImage rgb2gray(BufferedImage bi)//converter
{
    int heightLimit = bi.getHeight();
    int widthLimit = bi.getTileWidth();

    BufferedImage converted = new BufferedImage(widthLimit, heightLimit, BufferedImage.TYPE_BYTE_GRAY);

    for (int height = 0; height < heightLimit; height++) {
        for (int width = 0; width < widthLimit; width++) {
            Color c = new Color(bi.getRGB(width, height) & 0x00fffff);
            int newRed = (int) ((0.2989f * c.getRed()) * 1.45);//0.2989f
            int newGreen = (int) ((0.5870f * c.getGreen()) * 1.45);//0.5870f
            int newBlue = (int) ((0.1140f * c.getBlue()) * 1.45);
            int roOffset = newRed + newGreen + newBlue;
            converted.setRGB(width, height, roOffset);
        }
    }
    return converted;
}

What is wrong?

In matlab the result it's perfect, but with this code in java is poor.

FCoelho
  • 165
  • 1
  • 4
  • 11
  • Why have you multiplied each new value with 1.45? As far as I know the multiplier is just 0.2989, 0.587 and 0.1140 for r, g and b respectively – Dharini Chandrasekaran May 14 '13 at 00:04
  • This might help http://stackoverflow.com/questions/9460079/implementing-matlabs-rgb2gray-in-java – bilal.haider May 14 '13 at 00:07
  • @bilal.haider - it looks like the parentheses are in the right place in his code... so the answer you linked doesn't apply. But the additional *1.45 does seem out of place. Can't figure out why that wouldn't make the image "too bright" rather than "too dark", though. – Floris May 14 '13 at 00:14
  • But why result in Matlab it's different an result in java? – FCoelho May 14 '13 at 00:21

2 Answers2

0

I am not sure why this works in Matlab and not in java - except that perhaps color representation is not handled the same way in both platforms (but that's speculating). However, there is a very good way to do what you want to do - it doesn't answer your specific question ("what's wrong?"), but it should get you back to doing what you were hoping to do:

How do I desaturate a BufferedImage in Java?

Community
  • 1
  • 1
Floris
  • 45,857
  • 6
  • 70
  • 122
  • I think i have solved, i multiply by 1.35 instead of multiply by 1.45, and the result it's better. – FCoelho May 14 '13 at 00:14
0

Your mistake seems to be multiplying the new red, green and blue values with a mysterious 1.45.

Just remove that and make your code:

int newRed = (int) (0.2989f * c.getRed());
int newGreen = (int) (0.5870f * c.getGreen());
int newBlue = (int) (0.1140f * c.getBlue());

Matlab's documentation for it's rgb2gray function has these coefficients.