【问题标题】:Replace only background color of PNG仅替换 PNG 的背景颜色
【发布时间】:2017-02-17 03:00:36
【问题描述】:

这是我的代码:

#! /usr/bin/env sh
# Generate test image.
convert -size 100x60 xc:blue -fill blue -stroke black -draw "circle 50,30 55,55" in.png

# Make background transparent.
convert in.png -fill none -draw 'matte 0,0 floodfill' -flop  -draw 'matte 0,0 floodfill' -flop out.png
# Replace transparent background with green.
mogrify -background green -flatten out.png

# The wrong way.
convert in.png -transparent blue oops.png
mogrify -background green -flatten oops.png

基于这个sn-p:https://snippets.aktagon.com/snippets/558-how-to-remove-a-background-with-imagemagick

从这里开始:

我想得到这个:

不是这个:

我可以使用单个 convert 命令而不是 convert 后跟 mogrify 来实现此目的吗?

我正在使用 ImageMagick 6.8.9-9。

【问题讨论】:

    标签: imagemagick imagemagick-convert


    【解决方案1】:

    本质上,您正在寻找一个“floodfill”,如下所示:

    convert in.png -fill green  -draw 'color 0,0 floodfill' result.png
    

    这将查看左上角的像素 (0,0),并用绿色填充所有 与其相连的颜色相似的像素。如果您的背景有细微的变化,例如它是 JPEG,添加一些 模糊因子

    convert in.jpg -fuzz 25% ...
    

    请注意,如果您的圆圈接触了顶部和底部边缘,它将防止填充物溢出到图表的右侧。因此,假设您创建了这样的圈子:

    convert -size 100x60 xc:blue -fill blue -stroke black -draw "circle 50,30 50,0" in.png
    

    然后你运行上面的命令,你会得到:

    如果发生这种情况,您可以先添加一个像素宽的边框,让颜色“流动”先通过,然后进行填充,最后再将其移除:

    convert in.png -bordercolor blue -border 1 -fill green  -draw 'color 0,0 floodfill' -shave 1x1 result.png
    

    【讨论】:

    • 要填充透明度而不是颜色,请使用:convert in.png -fill none -draw 'color 0,0 floodfill' result.png
    猜你喜欢
    • 2017-10-29
    • 2010-10-14
    • 2021-07-02
    • 2023-03-18
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    相关资源
    最近更新 更多