簡體   English   中英

Python PIL使用顏色輪廓填充圖像

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

我有一張PNG格式的圖片,沒有背景。 我想要做的是用黃色填充這個圖像,直到邊緣。 圖1是我的,圖2是我想要的。 圖片1

在此輸入圖像描述

我不確定如何實現這一目標或如何啟動它。 因為pic的背景和內部都是透明的。

我希望有一個函數,我可以告訴python找到邊緣並填充內部直到邊緣

from PIL import Image, ImageFilter

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

就我而言,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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM