本文介绍了使用TYPE_USHORT_GRAY在Java中读取黑白图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有以下代码来读取Java中的黑白图片.

I have the following code to read a black-white picture in 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到25​​5之间的数字.但我会看到'-1'和另一个大整数.有人可以强调我的错误吗?

As you can see I have set the type of BufferedImage into TYPE_USHORT_GRAY and I expect that I see the numbers between 0 and 255 in the two D array mattrix. but I will see '-1' and another large integer. Can anyone highlight my mistake please?

推荐答案

正如注释和答案中已经提到的,错误在于使用了 getRGB()方法,该方法将像素值转换为打包的 int 格式(默认为sRGB颜色空间)( TYPE_INT_ARGB ).在这种格式下, -1 与´0xffffffff`相同,表示纯白色.

As already mentioned in comments and answers, the mistake is using the getRGB() method which converts your pixel values to packed int format in default sRGB color space (TYPE_INT_ARGB). In this format, -1 is the same as ´0xffffffff`, which means pure white.

要直接访问未签名的 short 像素数据,请尝试:

To access your unsigned short pixel data directly, try:

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提供的第二个链接可能仍然是一个好主意,以实现正确的颜色到灰色的转换.;-)

PS: It's probably still a good idea to look at the second link provided by @blackSmith, for proper color to gray conversion. ;-)

这篇关于使用TYPE_USHORT_GRAY在Java中读取黑白图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 15:23