簡體   English   中英

在Java中區分16位和8位grascale圖像

[英]Telling apart 16 and 8 bit grascale Images in java

我正在嘗試讀取.png grayscaleimages並將grayvalues轉換為double[][]數組。 我需要將它們映射到0到1之間的值。

我正在使用BufferedImage,並且嘗試使用img.getColorModel().getColorSpace().getType()找出顏色深度,但返回的TYPE_5CLR或TYPE_6CLR通用組件顏色空間無濟於事。

目前,我正在讀取這樣的值:

BufferedImage img = null;
        try {
            img = ImageIO.read(new File(path));
        } catch (IOException e) {
            return null;
        }

        double[][] heightmap= new double[img.getWidth()][img.getHeight()];
        WritableRaster raster = img.getRaster();
        for(int i=0;i<heightmap.length;i++)
        {
            for(int j=0;j<heightmap[0].length;j++)
            {
                heightmap[i][j]=((double) raster.getSample(i,j,0))/65535.0;
            }
        }

65535如果是8位,則為256,但我不知道何時。

我在評論中寫道,您可以使用ColorModel.getNormalizedComponents(...) ,但是由於它使用float值並且不必要地復雜,因此實現這樣的轉換可能會更容易:

BufferedImage img;
try {
    img = ImageIO.read(new File(path));
} catch (IOException e) {
    return null;
}

double[][] heightmap = new double[img.getWidth()][img.getHeight()];

WritableRaster raster = img.getRaster();

// Component size should be 8 or 16, yielding maxValue 255 or 65535 respectively
double maxValue = (1 << img.getColorModel().getComponentSize(0)) - 1;

for(int x = 0; x < heightmap.length; x++) {
    for(int y = 0; y < heightmap[0].length; y++) {
        heightmap[x][y] = raster.getSample(x, y, 0) / maxValue;
    }
}

return heightmap;

請注意,上面的代碼僅對灰度圖像有效,但這似乎是您的輸入。 所有顏色分量的分量大小可能都相同( getComponentSize(0) ),但是R,G和B(如果有alpha分量,則可能有A)是單獨的樣本,並且代碼只會得到第一個樣本( getSample(x, y, 0) )。

PS:為清楚起見,我將變量xy重命名。 如果交換高度圖中的尺寸,並在內部循環中通過x而不是y循環,則很有可能會獲得更好的性能,這是因為數據位置更好。

如果假設圖像是灰度的,則調用getRGB並划分其成分之一可能會更容易:

heightmap[i][j] = (img.getRGB(j, i) & 0xff) / 255.0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM