简体   繁体   中英

Convert color image to Black and White (not grayscale) depending on color conditions in java

I have an image(test.jpg) which contains alphabets in different 8 colours. These 8 colours are:

RGB

0 0 0

0 255 0

0 0 255

0 255 255

255 0 0

255 0 255

255 255 0

255 255 255

I want to color these alphabets with the above 8 colors to BLACK and rest everything to WHITE I tried doing these by some if statements on red green blue values of pixels but the output is not that good. Is there any good approach to perform such task. Test Image Output Image after if statement

for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
                Color c = new Color(bi.getRGB(j, i));
                      if((c.getRed()>200 && c.getBlue()<60 && c.getGreen()<60)||
                        (c.getRed()>200 && c.getBlue()<60 && c.getGreen()>200) ||
                        (c.getRed()>200 && c.getBlue()>200 && c.getGreen()<60) ||
                        (c.getRed()<60 && c.getBlue()>200 && c.getGreen()<60)||
                        (c.getRed()<60 && c.getBlue()<60 && c.getGreen()>200)||
                        (c.getRed()<60 && c.getBlue()>200 && c.getGreen()>200)|| 
                        (c.getRed()==255 && c.getBlue()==255 && c.getGreen()==255)||    
                        (c.getRed()==0 && c.getBlue()==0 && c.getGreen()==0))
                    imageOut.setRGB(j,i,black.getRGB());
                else
                    imageOut.setRGB(j, i, white.getRGB());
            }
        }

Test for the exact RGB values that you listed then the program will do what you specified. for example...

if((c.getRed()==255 && c.getBlue()==0 && c.getGreen()==0)||

I would change the if statement in the following way:

int red = c.getRed(), green = c.getGreen(), blue = c.getBlue();
if ((red   == 255 || red   == 0) &&
    (green == 255 || green == 0) &&
    (blue  == 255 || blue  == 0)) {
    imageOut.setRGB(j,i,black.getRGB());
} else {
    imageOut.setRGB(j, i, white.getRGB());
}

Apart from that you can afterwards iterate over all pixels once again and check that every black pixel has a lot of other black pixels around. That way you remove the little black sparkles in some places.

The completely black area on the right however will be very hard to remove

If you have the original you can do subtraction.

Otherwise you can't get a perfect result - if you are after that

since completely separated intervals cannot be guarranteed

You may have to go into segmentation but that wont give you perfect result either

See if storing in png helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM