我知道那里有很多类似的问题,但是似乎没有一个问题可以解决我的问题。我想读取图像的像素值并将其存储在双精度数组中。由于图像只是灰度,因此我将RGB值转换为灰度值。我也将值的范围从0-255
更改为0-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, ...]
你能告诉我我在做什么错吗?谢谢。
尝试更改此行...
int gray = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
...到...
int gray = color.getRed();
灰度像素的所有颜色通道都具有相同的值。您不需要在那里进行任何算术运算。
看着其余的代码,我看不到任何错误。问题很可能是您所拥有的black颜色不是黑色。黑色是(0, 0, 0)
的RGB。
将结果乘以255,我得到大约15。因此,您所拥有的颜色可能是(15, 15, 15)
的RGB,即0F0F0F
。这已经很黑了,但请不要误认为是纯黑。