简体   繁体   中英

Java: How to get RGB-values of an image?

I know there are quite a few similar questions out there, but none of them seemed to solve my problem. I want to read the pixel values of an image and store them in a double array. Since the images are only grayscale, I converted the RGB-values to an grayscale value. I also changed the range of values from 0-255 to 0-1 .

That's my code:

public static double[] getValues(String path) {
    BufferedImage image;
    try {
        image = ImageIO.read(new File(path));

        int width = image.getWidth();
        int height = image.getHeight();

        double[] values = new double[width * height];

        int index = 0;
        for(int x = 0; x < width; x++) {
            for(int y = 0; y < height; y++) {
                Color color = new Color(image.getRGB(y, x));
                int gray = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
                values[index++] = gray / 255d;
            }
        }

        return values;
    } catch (IOException e) {
        e.printStackTrace();
    } 

    return null;
}

However, when I use this to convert a black image to double values I expect only 0.0 as values in the array. But what I get looks somewhat like the following: [0.058823529411764705, 0.058823529411764705, 0.058823529411764705, ...]

Can you tell me what I'm doing wrong? Thank you.

Change this line ...

int gray = (color.getRed() + color.getGreen() + color.getBlue()) / 3;

... to ...

int gray = color.getRed();

A grayscaled pixel has all it's color channels having the same value. You don't need to do any arithmetic operations there.


Looking at the rest of your code, I don't see any mistake. The problem is most likely that the black color you have there is not black. Black is RGB of (0, 0, 0) .


Multiplying your result by 255 gives me around 15. So the color is RGB of (15, 15, 15) which is #0F0F0F . This is pretty dark but don't mistake it with true black that is #000000 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM