仅替换PNG的背景色 [英] Replace only background color of PNG

查看:166
本文介绍了仅替换PNG的背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

#! /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

它基于以下代码段: https://snippets.aktagon.com/snippets/558-how-to-remove-a-background-with-imagemagick

从此开始:

我想要这个:

不是这样的:

我可以用单个convert命令代替convert后跟mogrify来实现此目标吗?

Can I achieve this with a single convert command instead of a convert followed by a mogrify?

我正在使用ImageMagick 6.8.9-9.

I am using ImageMagick 6.8.9-9.

推荐答案

基本上,您正在寻找填充" ,如下所示:

Essentially, you are seeking a "floodfill", like this:

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

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

That will look at the top-left pixel (0,0) and fill all similarly coloured pixels which are connected to it with green. If your background has slight variations in it, e.g. it's a JPEG, add some fuzz factor

convert in.jpg -fuzz 25% ...


请注意,如果您的圆已触及顶部和底部边缘,则可以防止填充物溢出到图的右侧.因此,假设您创建了这样的圈子:


Note that if your circle had touched the top and bottom edges, it would prevent the fill from flooding around to the right side of the diagram. So, let's say you had created your circle like this:

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

然后运行上面的命令,您将获得:

And then you run the above command, you will get:

如果发生这种情况,可以先为颜色添加单个像素宽边框,然后使颜色流" ,然后进行泛洪填充,最后再将其删除:

If that happens, you can add a single pixel wide border all the way around for the colour to "flow" through first, then flood-fill, and finally remove it later:

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

这篇关于仅替换PNG的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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