39

赤、緑、青の平均を使用してカラー画像をグレースケールに変換しようとしています。しかし、それはエラーで出てきます。

これが私のコードです

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));
            }
        }
4

3 に答える 3

94

あなたもこれを行うことができます:

    ColorMatrix matrix = new ColorMatrix();
    matrix.setSaturation(0); 
    imageview.setColorFilter(new ColorMatrixColorFilter(matrix));
于 2012-12-29T17:55:05.010 に答える
32

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;
    }
于 2011-12-05T06:09:23.900 に答える
15

Lalit は最も実用的な答えを持っています。ただし、結果のグレーを赤、緑、青の平均にしたかったので、マトリックスを次のように設定する必要があります。

    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);

そして最後に、以前に画像をグレースケールに変換するという問題に直面したことがあります-すべての場合で最も視覚的に満足のいく結果は、平均を取るのではなく、知覚された明るさに応じて各色に異なる重みを与えることによって達成されます。これらの値:

    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,};
于 2011-12-05T09:19:52.600 に答える