简体   繁体   English

将灰度位图转换为二维数组

[英]grayscale bitmap into 2d array

Hi everyone i have problems in converting GrayScale bmp images into integer 2D-array (with values 0-255) in Java. 大家好,我在用Java将GrayScale bmp图像转换成整数2D数组(值0-255)时遇到问题。

I have a pmb image that could be seen as an integer(0-255) 2D-array and i want to see that 2D-array in a Java data structure 我有一个pmb图片,可以将其视为整数(0-255)2D数组,我想在Java数据结构中看到该2D数组

i tried this way: 我这样尝试过:

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

Then with my BufferedImage i create int[][] this way: 然后用我的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);
    }
}

But now all the 2D-array is full of number like "-9211021" or similar. 但是现在所有2D阵列都充满了“ -9211021”或类似数字。

i think that the problem is in getRGB(j,k) but i don't know if it's possible to solve it. 我认为问题出在getRGB(j,k)中,但我不知道是否有可能解决它。

edit: 编辑:

i know RGB is not grayscale, so how can i get the grayscale value of a single pixel from a grayscale BufferedImage? 我知道RGB不是灰度,因此如何从灰度BufferedImage获取单个像素的灰度值?

In a grayscale image, BufferedImage.getPixel(x,y) wont give values within the [0-255] range. 在灰度图像中, BufferedImage.getPixel(x,y)不会提供[0-255]范围内的值。 Instead, it returns the corresponding value of a gray level(intensity) in the RGB colorspace. 相反,它在RGB颜色空间中返回相应的灰度(强度)值。 That's why you are getting values like "-9211021" . 这就是为什么您得到像“ -9211021”这样的值的原因。

The following snippet should solve your problem : 以下代码段可以解决您的问题:

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

where image is the created BufferedImage. image是创建的BufferedImage。 The 0 in the getSample indicates that we are accessing the first byte/band(setting it to a greater value will throw a ArrayOutOfBoundException in grayscale images). getSample中的0表示我们正在访问第一个字节/带(将其设置为更大的值将在灰度图像中引发ArrayOutOfBoundException )。

You can use Catalano Framework. 您可以使用Catalano Framework。 Contains several filters for image processing. 包含几个用于图像处理的过滤器。

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

Detail: That's it faster than using WritableRaster. 详细信息:这比使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM