java - Java:如何获取图像的 RGB 值?
问题描述
我知道那里有很多类似的问题,但似乎没有一个能解决我的问题。我想读取图像的像素值并将它们存储在双精度数组中。由于图像只有灰度,我将 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();
灰度像素的所有颜色通道都具有相同的值。你不需要在那里做任何算术运算。
查看您的其余代码,我没有看到任何错误。问题很可能是您那里的黑色不是黑色。黑色是 RGB 的(0, 0, 0)
。
将你的结果乘以 255 得到大约 15。所以颜色是 RGB,(15, 15, 15)
其中#0F0F0F
. 这很黑,但不要把它误认为是真正的黑色#000000
。
推荐阅读
- python - Groupby 占总数的百分比
- android - 如何从Android中的json数组中读取第二个数组
- outlook - Outlook 模块扩展 - 维护上下文
- python - 如何在 Pandas 中为未命名对象设置过滤器/标准
- c++ - 从函数指针 C++ 向函数发送参数
- android - Android 开发者控制台 - 卸载应用
- sql-server - 无法为 Snowflake 创建链接服务器
- postgresql - Mybatis Generator Postgres 返回 created id 支持
- xml - 更新子节点及其属性信息 - Powershell
- javascript - 在检查 javascript 数组中的重复值并忽略其中一些重复值时,我的代码出现问题