在Java中为图像着色

时间:2020-03-05 18:42:19  来源:igfitidea点击:

我正在研究一些代码来着色Java中的图像。基本上,我想做的就是GIMP的colorize命令,因此,如果我有BufferedImage和Color,则可以使用给定的颜色为Image着色。任何人有任何想法吗?我目前在执行此类操作时的最佳猜测是获取BufferedImage中每个像素的rgb值,并使用一定的缩放因子将Color的RGB值添加到该值。

解决方案

回答

对于图像中的每个像素,让" Y = 0.3 * R + 0.59 * G + 0.11 * B",然后将它们设置为

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

如果(R1,G1,B1)是我们要着色的对象。

回答

我从未使用过GIMP的colorize命令。但是,如果获取每个像素的RGB值并向其添加RGB值,则应真正使用LookupOp。这是我编写的将BufferedImageOp应用于BufferedImage的一些代码。

从上面使用尼克斯的例子,这里我将如何做。

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);
}

它创建一个BufferedImageOp,如果mask布尔值为true,它将屏蔽每种颜色。

调用起来也很简单。

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

如果这不是我们想要的,我建议我们进一步研究BufferedImageOp。

这也将更加有效,因为我们无需对不同的图像进行多次计算。或者只要R1,G1,B1值不变,就在不同的BufferedImages上再次进行计算。