在 Java 中着色图像 [英] Colorizing images in Java

查看:25
本文介绍了在 Java 中着色图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些代码来为 Java 中的图像着色.基本上我想做的是与 GIMP 的 colorize 命令类似的事情,这样如果我有一个 BufferedImage 和一个颜色,我就可以用给定的颜色对图像进行着色.有人有任何想法吗?我目前最好的猜测是获取 BufferedImage 中每个像素的 rgb 值,并将颜色的 RGB 值与一些缩放因子相加.

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.

推荐答案

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

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.

使用上面的 Nicks 示例,我将如何做.

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

让 Y = 0.3*R + 0.59*G + 0.11*B 对于每个像素

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

(R1,G1,B1) 是您要着色的内容与

(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 如果掩码布尔值为真,这将屏蔽每种颜色.

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

调用起来也很简单.

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

如果这不是您想要的,我建议您多看看 BufferedImageOp.

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

这也会更有效率,因为您不需要对不同的图像进行多次计算.或者在不同的 BufferedImages 上重新计算,只要 R1、G1、B1 值不改变.

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.

这篇关于在 Java 中着色图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆