Android: Convert a color image to grayscale

Hi guys, I need your help, I'm trying to convert a color image to shades of gray using the average of red, green, blue. But he comes out with errors

Here is my code

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

But when I run my application on the emulator, it forcibly closes. Any idea?

I solved my problem using the following code:

 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)); } } 
+28
android grayscale
Dec 05 2018-11-12T00:
source share
3 answers

You can do it too:

  ColorMatrix matrix = new ColorMatrix(); matrix.setSaturation(0); imageview.setColorFilter(new ColorMatrixColorFilter(matrix)); 
+75
Dec 29 '12 at 17:55
source share

Try the solution from leparlon's previous answer :

 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; } 
+31
Dec 05 2018-11-12T00:
source share

Lalit has the most practical answer. However, you wanted the resulting gray to be the average value of red, green, and blue and should have set up your matrix like this:

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

And finally, when I encountered the problem of converting an image to shades of gray earlier - the most visually pleasing result in all cases is achieved not by averaging, but by providing each color with a different weight depending on its perceptual brightness, I tend to use these values:

  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,}; 
+13
Dec 05 2018-11-11T00:
source share



All Articles