user2517280
user2517280

Reputation: 221

Adding colour to greyscale image

Im looking to add colour to a greyscale image; it doesnt have to be an accurate colour representation but adding a colour to a different shade of grey, this is just to identify different areas of interest within an image. E.g. areas of vegetation are likely to be of a similar shade of grey, by adding a colour to this range of values it should be clear which areas are vegetation, which are of water, etc.

I have the code for getting colours from an image and storing them as a colour object but this doesnt seem to give a way to modify the values. E.g. if the grey vale is less than 85, colour red, if between 86 and 170 colour green and between 171 and 255 colour blue. I have no idea how this will look but in theory the resulting image should allow a user to identify the different areas.

The current code I have for getting pixel value is below.

int total_pixels = (h * w);
Color[] colors = new Color[total_pixels];

for (int x = 0; x < w; x++)
{
  for (int y = 0; y < h; y++)
  {
    colors[i] = new Color(image.getRGB(x, y));
    i++;
  }
}
for (int i = 0; i < total_pixels; i++)
{
  Color c = colors[i];
  int r = c.getRed();
  int g = c.getGreen();
  int b = c.getBlue();
  System.out.println("Red " + r + " | Green " + g + " | Blue " + b);
}

I appreciate any help at all! Thanks a lot

Upvotes: 0

Views: 156

Answers (2)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79807

You are going to have to choose your own method of converting colours from the greyscale scheme to whatever colour you want.

In the example you've given, you could do something like this.

public Color newColorFor(int pixel) {
    Color c = colors[pixel];
    int r = c.getRed();  // Since this is grey, the G and B values should be the same
    if (r < 86) {
        return new Color(r * 3, 0, 0);  // return a red
    } else if (r < 172) {
        return new Color(0, (r - 86) * 3, 0); // return a green
    } else {
        return new Color(0, 0, (r - 172) * 3); // return a blue
    }
}

You may have to play around a bit to get the best algorithm. I suspect that the code above will actually make your image look quite dark and dingy. You'd be better off with lighter colours. For example, you might change every 0 in the code above to 255, which will give you shades of yellow, magenta and cyan. This is going to be a lot of trial and error.

Upvotes: 2

Akira
Akira

Reputation: 4071

I recommend you to take a look at Java2D. It has many classes that can make your life much easier. You may end up reinventing the wheel if you ignore it.

Here is a short showcase of what you can do:

    int width = 100;
    int height = 100;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    image.getRGB(x, y);
    Graphics2D g2d = (Graphics2D)image.getGraphics();
    g2d.setColor(Color.GREEN);
    g2d.fillRect(x, y, width, height);

Upvotes: 0

Related Questions