【问题标题】:What's the appropriate way to colorize a grayscale image with transparency in Java?在Java中为具有透明度的灰度图像着色的适当方法是什么?
【发布时间】:2011-11-29 02:57:35
【问题描述】:

我正在制作一个头像生成器,其中头像组件来自具有透明度的 PNG 文件。这些文件类似于body_1.png 或legs_5.png。透明度在零件周围但不在零件内,并且图像都是灰度的。零件分层很好,我可以得到一个灰度头像。

我希望能够为这些部分动态着色,但到目前为止我运气不佳。我尝试将像素数据从 RGB 转换为 HSL 并使用原始像素的 L 值,同时提供新颜色的 H 值,但结果并不好。

我看过Colorize grayscale image,但我似乎无法使他所说的在Java 中工作。我最终得到了一张到处都有相当明亮的霓虹色的图像。

我想要的是保持透明度,同时为灰度部分着色。黑色轮廓仍应为黑色,白色高光区域仍应为白色(我认为)。

有没有人有办法做到这一点?

编辑:

这是我可能会尝试着色的图像:

再次,我想保持灰度图像的亮度级别(这样轮廓保持黑暗,渐变可见,白色斑块是白色的)。

我已经能够让 LookupOp 在某种程度上基于Colorizing images in Java 工作,但颜色总是看起来单调和黑暗。

这是我的输出示例:

使用的颜色是这个(注意亮度差异):http://www.color-hex.com/color/b124e7

这是我的查找操作

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 < 30; i++) {
    alpha[i] = i;
        red[i] = i;
        green[i] = i;
        blue[i] = i;
}

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

    }


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

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

编辑 2:我将 LookupOp 更改为使用以下内容,并获得了更好看的颜色:

red[i] = (short)((R1)*(float)i/255.0);
green[i] = (short)((G1)*(float)i/255.0);
blue[i] = (short)((B1)*(float)i/255.0);

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖SSCCE。在 SSCCE 中使用图像很棘手。您可以热链接到 Internet 上的图像,或在代码中生成。

标签: java image-processing


【解决方案1】:

似乎对你有用的是这样的:

for each pixel
    if pixel is white, black or transparent then leave it alone
    else
        apply desired H and S and make grayscale value the L
        convert new HSL back to RGB

编辑:看到你的图片后,我有几个 cmets:

您似乎想对较深的色调进行特殊处理,因为您不会对低于 30 的任何颜色进行着色。按照相同的逻辑,您是否也应该免除对较高值进行着色?这将防止白色和接近白色的颜色染上颜色。

您不应该将 Alpha 值与 RGB 一起设置。应始终保留原始图像的 alpha 值。您的查找表算法应该只影响 RGB。

虽然您说您尝试过 HSL,但这不在您发布的代码中。您应该在 HSL 中进行着色,然后将生成的颜色转换为 RGB 用于查找表,因为这将保留灰度的原始亮度。您的查找表创建可能是这样的:

short H = ??; // your favorite hue
short S = ??; // your favorite saturation
for (short i = 0; i < 256; i++) {
    if (i < 30 || i > 226) {
        red[i] = green[i] = blue[i] = i; // don't do alpha here
    }
    else {
        HSL_to_RGB(H, S, i, red[i], green[i], blue[i])
    }
}

注意:您必须提供 HSL 到 RGB 的转换功能。有关源代码的链接,请参阅我在 Colorize grayscale image 上的回答。

【讨论】:

    猜你喜欢
    • 2023-02-22
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 2012-11-23
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多