我有下面的代码来读取java中的黑白图片。
imageg = ImageIO.read(new File(path));
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_USHORT_GRAY);
Graphics g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
int w = img.getWidth();
int h = img.getHeight();
int[][] array = new int[w][h];
for (int j = 0; j < w; j++) {
for (int k = 0; k < h; k++) {
array[j][k] = img.getRGB(j, k);
System.out.print(array[j][k]);
}
}
正如您所看到的,我已将 BufferedImage 的类型设置为 TYPE_USHORT_GRAY,并且我希望在两个 D 数组矩阵中看到 0 到 255 之间的数字。但我会看到“-1”和另一个大整数。谁能强调我的错误吗?
正如评论和答案中已经提到的,错误是使用getRGB()
将像素值转换为打包的方法int
默认 sRGB 色彩空间中的格式(TYPE_INT_ARGB
)。在这种格式中,-1
与“0xffffffff”相同,表示纯白色。
访问您的未签名short
直接像素数据,尝试:
int w = img.getWidth();
int h = img.getHeight();
DataBufferUShort buffer = (DataBufferUShort) img.getRaster().getDataBuffer(); // Safe cast as img is of type TYPE_USHORT_GRAY
// Conveniently, the buffer already contains the data array
short[] arrayUShort = buffer.getData();
// Access it like:
int grayPixel = arrayUShort[x + y * w] & 0xffff;
// ...or alternatively, if you like to re-arrange the data to a 2-dimensional array:
int[][] array = new int[w][h];
// Note: I switched the loop order to access pixels in more natural order
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
array[x][y] = buffer.getElem(x + y * w);
System.out.print(array[x][y]);
}
}
// Access it like:
grayPixel = array[x][y];
PS:查看@blackSmith 提供的第二个链接可能仍然是一个好主意,以实现正确的颜色到灰色的转换。 ;-)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)