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

但是当我在模拟器上运行我的应用程序时,它强制closures。 任何想法?

我已经解决了我的问题使用下面的代码:

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

Solutions Collecting From Web of "Android:将彩色图像转换为灰度"

你也可以这样做 :

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

试试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; } 

拉利特有最实际的答案。 然而 ,你想要得到的灰色是红色,绿色和蓝色的平均值,应该像这样设置你的matrix:

  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,};