2011-11-13 233 views
1

我想將彩色圖像轉換爲灰度。首先我獲取彩色圖像的數據並更改此數據,但是當我想從此數據創建加利圖像時,我有這樣的錯誤。 。 enter image description here將彩色圖像轉換爲灰度

的getData()maethod:

public double[] getData(BufferedImage a){ 
     double[] data2=new double[h*w]; 
     int red=0,green=0,blue=0; 

     int counter=0; 
     for(int w1=0;w1<w;w1++){ 
      for(int h1=0;h1<h;h1++){ 
       int rgb=a.getRGB(w1,h1); 
       red=(rgb)>> 16; 
       green=(rgb)>>8; 
       blue=(rgb); 

       data2[counter]=(red+green+blue)/3; 
       counter++; 
      } 
     } 
    return data2; 
} 

創建圖像()方法:

void createImage(){ 
double[] data1=getData(colorImage); 

      BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY); 
       WritableRaster raster = image.getRaster(); 

     int counter = 0 ; 
     for(int i = 0; i<h; i++){ 
      for(int j = 0; j<w; j++){ 
        raster.setSample(i, j, 0, data1[counter]); 
      counter++; 
      } 
     } 
} 
+0

這不是問題,但getData中的計數器不會在任何地方遞增。 – Dimme

+0

double [] data2 = new double [h * w]; h和w從哪裏來? – Dimme

+0

w和h是加載的圖像的寬度和高度。 – Tofiq

回答

2

,因爲它看起來對我來說,i和j在setSample調用必須交換。 (或BufferedImage中的w和h)