2016-05-12 78 views
0

我最近開始使用java中的圖像。 我想實現一個基於顏色的基本運動跟蹤系統(我知道這不會很有效,但它只是用於測試)。瀏覽圖片的每個像素

現在我想用Java處理圖像。 我想刪除RGB圖像中的所有顏色,而不是一個顏色或一系列顏色。

現在我還沒有找到一個好的解決方案。我希望它儘可能保持簡單,並儘量不要使用除標準Java之外的任何其他庫。

+0

到目前爲止發現了什麼? –

回答

1

隨着BufferedImage(java中的標準圖像類),你有兩個「好」的解決方案來訪問像素。

1 - 使用柵格更容易,因爲它自動處理編碼,但速度較慢。

WritableRaster wr = image.getRaster() ; 
for (int y=0, nb=0 ; y < image.getHeight() ; y++) 
    for (int x=0 ; x < image.getWidth() ; x++, nb++) 
     { 
     int r = wr.getSample(x, y, 0) ; // You just give the channel number, no need to handle the encoding. 
     int g = wr.getSample(x, y, 1) ; 
     int b = wr.getSample(x, y, 2) ; 
     } 

2 - 使用DataBuffer,最快,因爲直接訪問像素,但你必須處理編碼。

switch (image.getType()) 
    { 
    case BufferedImage.TYPE_3BYTE_BGR : // Classical color images encoding. 
     byte[] bb = ((DataBufferByte)image.getRaster().getDataBuffer()).getData() ; 
     for (int y=0, pos=0 ; y < image.getHeight() ; y++) 
      for (int x=0 ; x < image.getWidth() ; x++, pos+=3) 
       { 
       int b = bb[pos] & 0xFF ; 
       int g = bb[pos+1] & 0xFF ; 
       int r = bb[pos+2] & 0xFF ; 
       } 
     break ; 
    } 

getRGB()很簡單,但比光柵慢很多,所以只是禁止它。