Search code examples
pythonpython-imaging-libraryoutline

How to outline an image and leave only the outline


I have a problem similar to this, but I want only the outline to remain. This is the image I'm trying to outline, any ideas?

I tried all the programs on the other threads, but none did what I wanted it to besides the one using ImageMagick, and I'm a Windows user who wants to avoid external downloads if possible. Can some one help using PIL or another python module to help?


Solution

  • If you have a binary mask of the image (and you need one, anyway, just to define what is the thing you want to "outline". But the criteria to compute one is specific to each image. It may be from the background color. Or, in your case, since it is has a transparent background, from alpha channel), then that is a mathematical morphology operation. OpenCV, for example, contains mathemathical morphology operators

    You need to read about this, since that is not just some code to copy and paste.

    But for your specific question, and specific example, it is as simple as

    import cv2
    import numpy as np
    from PIL import Image
    img=np.asarray(Image.open("image.png"))
    outline = cv2.morphologyEx(img[...,3], cv2.MORPH_GRADIENT, np.ones((5,5)))
    

    img[...,3] being the alpha channel. Here, 0 everywhere but on the central figure where it is 255. (5,5) is the size of the kernel (read about morphology to understand it), 5 being the parameter to tune to choose the thickness of the outline

    enter image description here