2014-09-29 227 views
1

我有以下代碼來讀取java中的黑白圖片。在Java中使用TYPE_USHORT_GRAY讀取黑色/白色圖像

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,我希望我看到的0到255之間的數字在兩d陣列mattrix。但我會看到'-1'和另一個大整數。任何人都可以突出我的錯誤嗎?

+0

這是由於'getRGB'方法。如果你對二進制(純B/W)圖像感興趣,請看http://stackoverflow.com/questions/5925426/java-how-would-i-load-a-black-and-white-image-into-二進制 – blackSmith 2014-09-29 06:23:20

+0

如果你的目的是讀爲GrayScale,你需要一個轉換公式。 http://stackoverflow.com/questions/687261/converting-rgb-to-grayscale-intensity – blackSmith 2014-09-29 06:29:59

回答

0

正如意見和答案已經提到,錯誤使用getRGB()方法,轉換你的像素值,在默認的sRGB色彩空間(TYPE_INT_ARGB)包裝int格式。在這種格式下,-1與「0xffffffff」相同,這意味着純白色。

要直接訪問你的簽名short像素數據,嘗試:

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提供的第二個鏈接,進行適當的顏色以灰色轉換。 ;-)

0

A BufferedImageTYPE_USHORT_GRAYTYPE_USHORT_GRAY如其名稱所述使用16位存儲像素(short的大小是16位)。範圍0..255只有8位,所以顏色可能會大大超過255
而且BufferedImage.getRGB()不返回這些16象素的數據位而是從引用其javadoc

返回整數像素在默認RGB顏色模型(TYPE_INT_ARGB)和默認的sRGB顏色空間。

getRGB()將始終返回RGB格式的像素,而不管BufferedImage的類型如何。

+0

Icza,也感謝您對TYPE_SHORT_GRAY的解釋。我認爲它是8位。 – Mohammadreza 2014-10-05 01:05:57