I would like to know how to isolate a certain color in an image and set the rest to gray using java.
So far I managed to do so, but in a hardcode way by looping through all the pixels of the image and then checking the RGB values. I am using BufferedImage to load the image and the Color class to deal with RGB values.
The isColorRed checks if the color is red or not.
private static boolean isColorRed(Color color) {
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
return ((red >= 70 && red <= 255) && (green >= 0 && green <= 80) && (blue >= 0 && blue <= 80));
}
The isolateColor method is responsible to set all pixels to grey except for the red ones.
private static void isolateColor(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
Color c = new Color(image.getRGB(x, y));
if (!isColorRed(c)) {
int red = (int) (c.getRed() * 0.3);
int green = (int) (c.getGreen() * 0.587);
int blue = (int) (c.getBlue() * 0.114);
int gray = red + green + blue;
Color newColor = new Color(gray, gray, gray);
image.setRGB(x, y, newColor.getRGB());
} else {
Color newColor = new Color(c.getRed(), c.getGreen(), c.getBlue());
image.setRGB(x, y, newColor.getRGB());
}
}
}
File file;
try {
file = new File("src/grey.png");
ImageIO.write(image, "png", file);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
The original image :
After the treatment :
Is there any API built-in or external that can isolate one color or more in a single image

