Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PIL Fill an image with a color outline

I have a picture that is in PNG format with no background. 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. picture 1

enter image description here

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.

I wish there was a function where I can tell python find edges and fill inside till edges

from PIL import Image, ImageFilter

image = Image.open('picture1.png')
image = image.filter(ImageFilter.FIND_EDGES).fill(yellow)
image.save('new_name.png') 
like image 613
ben olsen Avatar asked Oct 13 '17 08:10

ben olsen


People also ask

How do you change the color of an image in Python?

Using the ImageColor module, we can also convert colors to RGB format(RGB tuple) as RGB is very convenient to perform different operations. To do this we will use ImageColor. getgrb() method. The ImageColor.


1 Answers

In my case, the ImageDraw floodfill works like a charm. 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:

Output of the program above

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
like image 51
physicalattraction Avatar answered Sep 28 '22 16:09

physicalattraction