首页 > 解决方案 > Java:如何获取图像的 RGB 值?

问题描述

我知道那里有很多类似的问题,但似乎没有一个能解决我的问题。我想读取图像的像素值并将它们存储在双精度数组中。由于图像只有灰度,我将 RGB 值转换为灰度值。我还将值的范围从 更改0-2550-1

那是我的代码:

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;
}

但是,当我使用它来将黑色图像转换为双精度值时,我只希望0.0作为数组中的值。但我得到的看起来有点像以下: [0.058823529411764705, 0.058823529411764705, 0.058823529411764705, ...]

你能告诉我我做错了什么吗?谢谢你。

标签: javaimagecolorsrgbgrayscale

解决方案


改变这一行...

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

... 到 ...

int gray = color.getRed();

灰度像素的所有颜色通道都具有相同的值。你不需要在那里做任何算术运算。


查看您的其余代码,我没有看到任何错误。问题很可能是您那里的黑色不是黑色。黑色是 RGB 的(0, 0, 0)


将你的结果乘以 255 得到大约 15。所以颜色是 RGB,(15, 15, 15)其中#0F0F0F. 这很黑,但不要把它误认为是真正的黑色#000000


推荐阅读