Colorizing images in Java

前端 未结 4 1913
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 23:52

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 Buffered

4条回答
  •  孤街浪徒
    2020-12-04 00:32

    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.

提交回复
热议问题