简体   繁体   English

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

[英]Python PIL Fill an image with a color outline

I have a picture that is in PNG format with no background. 我有一张PNG格式的图片,没有背景。 What I am trying to do is fill this image with yellow only till the edges. 我想要做的是用黄色填充这个图像,直到边缘。 Picture 1 is what I have and Picture 2 is what I want. 图1是我的,图2是我想要的。 图片1

在此输入图像描述

I am not really sure how to achieve this goal or how to start it. 我不确定如何实现这一目标或如何启动它。 because both the background and the inside of the pic is transparent. 因为pic的背景和内部都是透明的。

I wish there was a function where I can tell python find edges and fill inside till edges 我希望有一个函数,我可以告诉python找到边缘并填充内部直到边缘

from PIL import Image, ImageFilter

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

In my case, the ImageDraw floodfill works like a charm. 就我而言,ImageDraw floodfill就像一个魅力。 What is not working for you? 什么不适合你?

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))

Output image: 输出图像:

上述程序的输出

Version information: 版本信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM