Python PIL:用颜色轮廓填充图像

6
我有一张PNG格式的图片,没有背景。我的目标是将这个图像填充为黄色,直到边缘。 图片1是我现在拥有的,图片2是我想要的。picture 1 enter image description here 我不确定如何实现这个目标或如何开始它。因为图片的背景和内部都是透明的。
希望有一个功能,可以告诉Python找到边缘并在内部填充直到边缘。
from PIL import Image, ImageFilter

image = Image.open('picture1.png')
image = image.filter(ImageFilter.FIND_EDGES).fill(yellow)
image.save('new_name.png') 

如果你有最新版本的Pillow,那么就有一个PIL.ImageDraw.floodfill方法,但我自己从未使用过,并且文档警告说它是实验性的。 - PM 2Ring
如果您采用边缘检测方法,这篇文章可能会对您有所帮助。 - Reti43
尝试使用imagedrawfloodfill,但没有成功。是否有其他程序可以完成这个任务? - ben olsen
能否反转图像颜色?我有一张彩色图片,想要只保留白色。这可行吗? - shakthydoss
https://stackoverflow.com/questions/45397540/python-pil-cut-words-out-so-it-becomes-transparent-png/45398565#45398565 - ben olsen
1个回答

7
在我的情况下,ImageDraw的"floodfill"函数完美运作。你遇到了什么问题?
import os.path
import sys

from PIL import Image, ImageDraw, PILLOW_VERSION


def get_img_dir() -> str:
    pkg_dir = os.path.dirname(__file__)
    img_dir = os.path.join(pkg_dir, '..', '..', 'img')
    return img_dir


if __name__ == '__main__':
    input_img = os.path.join(get_img_dir(), 'star_transparent.png')
    image = Image.open(input_img)
    width, height = image.size
    center = (int(0.5 * width), int(0.5 * height))
    yellow = (255, 255, 0, 255)
    ImageDraw.floodfill(image, xy=center, value=yellow)
    output_img = os.path.join(get_img_dir(), 'star_yellow.png')
    image.save(output_img)

    print('Using Python version {}'.format(sys.version))
    print('Using Pillow version {}'.format(PILLOW_VERSION))

输出图像:

上述程序的输出

版本信息:

Using Python version 3.6.2 (default, Aug  3 2017, 13:46:16) 
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)]
Using Pillow version 4.3.0

当我运行我的代码时,出现了无法解压文件的错误。你的代码运行得非常顺畅。谢谢。 - ben olsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接