6

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') 
ben olsen
  • 663
  • 1
  • 14
  • 27
  • If you have the latest version of Pillow there's a [PIL.ImageDraw.floodfill](http://pillow.readthedocs.io/en/4.3.x/reference/ImageDraw.html#PIL.ImageDraw.PIL.ImageDraw.floodfill) method, but I've never used it myself, and the docs warn that it's experimental. – PM 2Ring Oct 13 '17 at 08:23
  • [This](https://stackoverflow.com/questions/9137216/python-edge-detection-and-curvature-calculation) might help if you take the edge detection approach. – Reti43 Oct 13 '17 at 08:58
  • Tried imagedrawfloodfill did not work. Is there another program possible to do this task? – ben olsen Oct 13 '17 at 10:02
  • Is it possible to reverse. I have colored image I want to remove the color just with white. Is it possible. – shakthydoss Sep 26 '18 at 05:30
  • https://stackoverflow.com/questions/45397540/python-pil-cut-words-out-so-it-becomes-transparent-png/45398565#45398565 – ben olsen Sep 27 '18 at 07:22

1 Answers1

7

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
physicalattraction
  • 6,485
  • 10
  • 63
  • 122