我有以下代码来读取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()
方法,该方法将像素值转换为默认 sRGB 颜色空间中的打包 int
格式(TYPE_INT_ARGB
)。在此格式中,-1
与“0xffffffff”相同,表示纯白色。
要直接访问未签名的短
像素数据,请尝试:
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 提供的第二个链接可能仍然是一个好主意,以实现正确的颜色到灰色的转换。 ;-)
关于java - 使用 TYPE_USHORT_GRAY 在java中读取黑白图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26093390/