Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert all colors other than a particular color in a bitmap to white

I am using tess-two library and I wish to convert all the colors other than black in my image to white (Black will be text). Thus making it easier for the tess-two to read the text. I have tried various methods but they are taking too much time as they convert pixel by pixel. Is there a way to achieve this using canvas or anything that give results faster.

UPDATE

Another problem that came up with this algorithm is that printer doesn't print with the same BLACK and White as in android. So the algorithm converts the whole picture to white.

Pixel by pixel method that I am currently using.

 binarizedImage = convertToMutable(cropped);// the bitmap is made mutable
 int width = binarizedImage.getWidth();
 int height = binarizedImage.getHeight();
 int[] pixels = new int[width * height];
 binarizedImage.getPixels(pixels, 0, width, 0, 0, width, height);

 for(int i=0;i<binarizedImage.getWidth();i++) {
     for(int c=0;c<binarizedImage.getHeight();c++) {
         int pixel = binarizedImage.getPixel(i, c);
         if(!(pixel == Color.BLACK  || pixel == Color.WHITE))
         {
              int index = c * width + i;
             pixels[index] = Color.WHITE;
             binarizedImage.setPixels(pixels, 0, width, 0, 0, width, height);
          }
     }
 }
like image 831
Rishabh Lashkari Avatar asked Apr 07 '16 11:04

Rishabh Lashkari


People also ask

How many colors can you mask in a bitmap?

You can mask as many as 10 colors in a bitmap.


1 Answers

Per, Rishabh's comment. Use a color matrix. Since black is black and is RGB(0,0,0,255), it's immune to multiplications. So if you multiply everything by 255 in all channels everything will exceed the limit and get crimped to white, except for black which will stay black.

       ColorMatrix bc = new ColorMatrix(new float[] {
                255, 255, 255, 0, 0,
                255, 255, 255, 0, 0,
                255, 255, 255, 0, 0,
                0, 0, 0, 1, 0,
        });
        ColorMatrixColorFilter filter = new ColorMatrixColorFilter(bc);
        paint.setColorFilter(filter);

You can use that paint to paint that bitmap in only-black-stays-black colormatrix filter glory.

Note: This is a quick and awesome trick, but, it will ONLY work for black. While it's perfect for your use and will turn that lengthy op into something that is instant, it does not actually conform to the title question of "a particular color" my algorithm works in any color you want, so long as it is black.

like image 183
Tatarize Avatar answered Oct 06 '22 11:10

Tatarize