2 回答

TA貢獻1801條經驗 獲得超8個贊
我在評論中寫道,您可以使用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(以及 A,如果有 alpha 分量)可能有單獨的樣本,并且代碼將僅獲取第一個樣本 ( getSample(x, y, 0)) 。
xPS:為了清楚起見,我重命名了你的變量y。x如果交換高度圖中的尺寸并在內循環中循環,則很可能會獲得更好的性能,而不是y由于更好的數據局部性。

TA貢獻1797條經驗 獲得超6個贊
如果您假設圖像是灰度圖像,則調用getRGB并除以其分量之一可能會更容易:
heightmap[i][j]?=?(img.getRGB(j,?i)?&?0xff)?/?255.0;
添加回答
舉報