views:

787

answers:

3

I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get the rgb value of each pixel in the BufferedImage and add the RGB value of the Color to it with some scaling factor.

+4  A: 

Let Y = 0.3*R + 0.59*G + 0.11*B for each pixel in the image, then set them to be

((R1+Y)/2,(G1+Y)/2,(B1+Y)/2)

if (R1,G1,B1) is what you are colorizing with.

Nick
+3  A: 

I have never used GIMP's colorize command. However, if your getting the RGB value of each pixel and adding RGB value to it you should really use a LookupOp. Here is some code that I wrote to apply a BufferedImageOp to a BufferedImage.

Using Nicks example from above heres how I would do it.

Let Y = 0.3*R + 0.59*G + 0.11*B for each pixel

(R1,G1,B1) is what you are colorizing with

protected LookupOp createColorizeOp(short R1, short G1, short B1) {
    short[] alpha = new short[256];
    short[] red = new short[256];
    short[] green = new short[256];
    short[] blue = new short[256];

    int Y = 0.3*R + 0.59*G + 0.11*B

    for (short i = 0; i < 256; i++) {
        alpha[i] = i;
        red[i] = (R1 + i*.3)/2;
        green[i] = (G1 + i*.59)/2;
        blue[i] = (B1 + i*.11)/2;
    }

    short[][] data = new short[][] {
            red, green, blue, alpha
    };

    LookupTable lookupTable = new ShortLookupTable(0, data);
    return new LookupOp(lookupTable, null);
}

It creates a BufferedImageOp that will mask out each color if the mask boolean is true.

Its simple to call too.

BufferedImageOp colorizeFilter = createColorizeOp(R1, G1, B1);
BufferedImage targetImage = colorizeFilter.filter(sourceImage, null);

If this is not what your looking for I suggest you look more into BufferedImageOp's.

This is would also be more efficient since you would not need to do the calculations multiple times on different images. Or do the calculations over again on different BufferedImages as long as the R1,G1,B1 values don't change.

Bernie Perez
A: 

Sorry to wake this one up. But I'm still completely lost here.

    int Y = 0.3*R + 0.59*G + 0.11*B 

    for (short i = 0; i < 256; i++) { 
        alpha[i] = i; 
        red[i] = (R1 + i*.3)/2; 
        green[i] = (G1 + i*.59)/2; 
        blue[i] = (B1 + i*.11)/2; 
    } 

And then it gives me an error about how Y isn't a double. I change it to double, and then it yells at me because the arrays can't be double, they have to be short.

However every time I try and convert them my entire image is covered with the same pixel. Is that how it's supposed to work? I figured it would just colorize the image, but keep the depth in the colors so the image was visible.

Virux