Android实时黑白阈值图像

前端之家收集整理的这篇文章主要介绍了Android实时黑白阈值图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个代码,使用以下代码将具有灰色的位图转换为黑色和白色的位图:
  1. // scan through all pixels
  2. for (int x = 0; x < width; ++x) {
  3. for (int y = 0; y < height; ++y) {
  4. // get pixel color
  5. pixel = bitmap.getPixel(x,y);
  6. A = Color.alpha(pixel);
  7. R = Color.red(pixel);
  8. G = Color.green(pixel);
  9. B = Color.blue(pixel);
  10. int gray = (int) (0.2989 * R + 0.5870 * G + 0.1140 * B);
  11.  
  12. // use 128 as threshold,above -> white,below -> black
  13. if (gray > 128)
  14. gray = 255;
  15. else
  16. gray = 0;
  17. // set new pixel color to output bitmap
  18. bmOut.setPixel(x,y,Color.argb(A,gray,gray));
  19. }
  20. }

正如你所看到的那样,我遍历了原始位图的所有像素点,然后我将颜色的分量与给定的阈值进行比较,在这种情况下为128,然后如果它在上面我说它是白色,否则它将是一个黑色像素.

我现在想做的是一个可以改变该阈值的Spinner,然后BW图像会有所不同.

要做到这一点,我需要再次绘制所有图像,这是非常cpu的成本时间,它需要时间再次传输所有像素.

有没有办法实时使用不同的BW阈值更改图像?

有人告诉我使用GIF,然后我会做的只是改变GIF的查找表值,有人在Android上有这方面的知识吗?

解决方法

自问这个问题以来已经过了一点时间,但我碰到了这个寻找其他东西并碰巧得到了解决方案.
您可以在没有OpenCV或任何其他第三方库的情况下实现此目的,仅使用自API级别1以来的 ColorMatrixColorFilter.

以下是您可以使用的矩阵:

  1. //matrix that changes picture into gray scale
  2. public static ColorMatrix createGreyMatrix() {
  3. ColorMatrix matrix = new ColorMatrix(new float[] {
  4. 0.2989f,0.5870f,0.1140f,0.2989f,1,0
  5. });
  6. return matrix;
  7. }
  8.  
  9. // matrix that changes gray scale picture into black and white at given threshold.
  10. // It works this way:
  11. // The matrix after multiplying returns negative values for colors darker than threshold
  12. // and values bigger than 255 for the ones higher.
  13. // Because the final result is always trimed to bounds (0..255) it will result in bitmap made of black and white pixels only
  14. public static ColorMatrix createThresholdMatrix(int threshold) {
  15. ColorMatrix matrix = new ColorMatrix(new float[] {
  16. 85.f,85.f,0.f,-255.f * threshold,0f,1f,0f
  17. });
  18. return matrix;
  19. }

以下是如何使用它们:

  1. BitmapFactory.Options options = new BitmapFactory.Options();
  2. options.inScaled = false;
  3.  
  4. //load source bitmap and prepare destination bitmap
  5. Bitmap pic = BitmapFactory.decodeResource(getResources(),R.drawable.thePicture,options);
  6. Bitmap result = Bitmap.createBitmap(pic.getWidth(),pic.getHeight(),Bitmap.Config.ARGB_8888);
  7. Canvas c = new Canvas(result);
  8.  
  9. //first convert bitmap to grey scale:
  10. bitmapPaint.setColorFilter(new ColorMatrixColorFilter(createGreyMatrix()));
  11. c.drawBitmap(pic,bitmapPaint);
  12.  
  13. //then convert the resulting bitmap to black and white using threshold matrix
  14. bitmapPaint.setColorFilter(new ColorMatrixColorFilter(createThresholdMatrix(128)));
  15. c.drawBitmap(result,bitmapPaint);
  16.  
  17. //voilà! You can now draw the result bitmap anywhere You want:
  18. bitmapPaint.setColorFilter(null);
  19. otherCanvas.drawBitmap(result,null,new Rect(x,x + size,y + size),bitmapPaint);

希望这会对某人有所帮助.

猜你在找的Android相关文章