1

大家好,我在将灰度 bmp 图像转换为 Java 中的整数二维数组(值为 0-255)时遇到问题。

我有一个可以被视为整数(0-255)二维数组的 pmb 图像,我想在 Java 数据结构中查看该二维数组

我试过这样:

Image image = ImageIO.read(new File("my_img.bmp"));
BufferedImage img = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = img.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();

然后用我的 BufferedImage 我这样创建 int[][] :

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);
    }
}

但是现在所有的二维数组都充满了“-9211021”或类似的数字。

我认为问题出在 getRGB(j,k) 但我不知道是否有可能解决它。

编辑:

我知道 RGB 不是灰度的,那么如何从灰度 BufferedImage 中获取单个像素的灰度值?

4

2 回答 2

1

在灰度图像中,BufferedImage.getPixel(x,y)不会给出 [0-255] 范围内的值。相反,它返回 RGB 颜色空间中灰度级(强度)的相应值。这就是为什么你会得到像 "-9211021"这样的值。

以下代码段应该可以解决您的问题:

Raster raster = image.getData();
for (int j = 0; j < w; j++) {
    for (int k = 0; k < h; k++) {
        array[j][k] = raster.getSample(j, k, 0);
    }
}

其中image是创建的 BufferedImage。getSample中的 0表示我们正在访问第一个字节/波段(将其设置为更大的值将在灰度图像中 引发ArrayOutOfBoundException )。

于 2013-07-10T12:54:37.393 回答
0

You can use Catalano Framework. Contains several filters for image processing.

http://code.google.com/p/catalano-framework/

Detail: That's it faster than using WritableRaster.

FastBitmap fb = new FastBitmap(bufferedImage);

int[][] image = new int[fb.getHeight()][fb.getWidth];
fb.toArrayGray(image);

//Do manipulations with image
//...

//Place the image into fastBitmap
fb.arrayToImage(image);

//Retrieve in bufferedImage if you desire.
bufferedImage = fb.toBufferedImage();
于 2013-07-15T13:36:34.513 回答