2011-12-05 97 views
24

嗨,大家好,我需要你們的幫助,我試圖用紅,綠,藍的平均值將彩色圖像轉換成灰度。但它出來有錯誤,Android:將彩色圖像轉換爲灰度

這裏是我的代碼

imgWidth = myBitmap.getWidth(); 
imgHeight = myBitmap.getHeight(); 

for(int i =0;i<imgWidth;i++) { 
    for(int j=0;j<imgHeight;j++) { 
    int s = myBitmap.getPixel(i, j)/3; 
    myBitmap.setPixel(i, j, s); 
    } 
} 

ImageView img = (ImageView)findViewById(R.id.image1); 
img.setImageBitmap(myBitmap); 

但是當我在模擬器上運行我的應用程序,它是強制關閉。任何想法?

我已經解決了我的問題,使用下面的代碼:

for(int x = 0; x < width; ++x) { 
      for(int y = 0; y < height; ++y) { 
       // get one pixel color 
       pixel = src.getPixel(x, y); 
       // retrieve color of all channels 
       A = Color.alpha(pixel); 
       R = Color.red(pixel); 
       G = Color.green(pixel); 
       B = Color.blue(pixel); 
       // take conversion up to one single value 
       R = G = B = (int)(0.299 * R + 0.587 * G + 0.114 * B); 
       // set new pixel color to output bitmap 
       bmOut.setPixel(x, y, Color.argb(A, R, G, B)); 
      } 
     } 
+1

什麼是錯誤發佈錯誤日誌。 – user370305

+0

你是否在日誌中得到任何確切的錯誤?如stackoverflow? – doNotCheckMyBlog

回答

29

嘗試解決from this previous answer by leparlon

public Bitmap toGrayscale(Bitmap bmpOriginal) 
    {   
     int width, height; 
     height = bmpOriginal.getHeight(); 
     width = bmpOriginal.getWidth();  

     Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); 
     Canvas c = new Canvas(bmpGrayscale); 
     Paint paint = new Paint(); 
     ColorMatrix cm = new ColorMatrix(); 
     cm.setSaturation(0); 
     ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); 
     paint.setColorFilter(f); 
     c.drawBitmap(bmpOriginal, 0, 0, paint); 
     return bmpGrayscale; 
    } 
+1

我怎樣才能讓照片變亮?圖像現在是灰色的,但由於原始圖像中的顏色,圖像也很暗。 – Andrew

+0

所以在轉換成黑白圖像後,圖像尺寸會減小嗎? (size in kb) –

+0

Lalit能告訴我如何從灰度圖像中提取字符? –

11

拉利特具有最實際的答案。 但是,你想要得到的灰色是平均的紅色,綠色和藍色,並應設置你的矩陣,像這樣:

float oneThird = 1/3f; 
    float[] mat = new float[]{ 
      oneThird, oneThird, oneThird, 0, 0, 
      oneThird, oneThird, oneThird, 0, 0, 
      oneThird, oneThird, oneThird, 0, 0, 
      0, 0, 0, 1, 0,}; 
    ColorMatrixColorFilter filter = new ColorMatrixColorFilter(mat); 
    paint.setColorFilter(filter); 
    c.drawBitmap(original, 0, 0, paint); 

最後,正如我所面對的圖像轉換爲問題灰度前 - 視覺上最令人愉悅的結果在所有情況下由未取平均值,而是通過給予取決於其percieved亮度每個顏色不同的權重來實現,我傾向於使用這些值:

float[] mat = new float[]{ 
      0.3f, 0.59f, 0.11f, 0, 0, 
      0.3f, 0.59f, 0.11f, 0, 0, 
      0.3f, 0.59f, 0.11f, 0, 0, 
      0, 0, 0, 1, 0,}; 
+0

@ user1324936謹慎闡述? – Jave

65

你可以這樣做太:

ColorMatrix matrix = new ColorMatrix(); 
    matrix.setSaturation(0); 

    ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix); 
    imageview.setColorFilter(filter); 
+0

是否有可能使其只有全黑(0xff000000)和全白(0xffffffff)? –

+0

@androiddeveloper你可以用ImageView的內置setColorFilter(color,mode)方法或普通的PorterDuffColorFilter來實現。 http://developer.android.com/reference/android/graphics/PorterDuffColorFilter.html – Pkmmte

+0

@Pkmmte什麼是常規PorterDuffColorFilter? –