'Python PIL Outline image increase thicknesses

I know how to find the edges from a picture. But I would like to have the outline edges be thicker for example width 9.

    from PIL import Image, ImageFilter

    image = Image.open('your_image.png')
    image = image.filter(ImageFilter.FIND_EDGES, width=9)
    image.save('new_name.png') 

is that possible?



Solution 1:[1]

You can find edges and fatten them like this:

#!/usr/bin/env python3

from PIL import Image, ImageMorph, ImageFilter

# Open star image and ensure greyscale
im = Image.open('star.png').convert('L')

# Detect edges and save
edges = im.filter(ImageFilter.FIND_EDGES)
edges.save('DEBUG-edges.png')

# Make fatter edges and save
fatEdges = edges.filter(ImageFilter.MaxFilter)
fatEdges.save('DEBUG-fatEdges.png')

# Make very fat edges and save
veryFatEdges = edges.filter(ImageFilter.MaxFilter(7))
veryFatEdges.save('DEBUG-veryFatEdges.png')

enter image description here

Top-left=original, top-right=edges, bottom-left=fat edges, bottom-right=very fat edges.

You could use ImageMorph module for more controlled morphology, but the maximum filter is very effective as it is.

Solution 2:[2]

It's never too late to share a solution. Try this ...

def change_img_edge(image, thickness, edge_color = (0,255,0, 200)):
    # Iterate thickness-times.
    # When image is filtered in next cycle, the detected edge moves outwards
    for t in range(thickness):
        msk = image.filter(ImageFilter.FIND_EDGES)
        msk_data, img_data  = msk.getdata(), image.getdata()
        
        # Get image size
        w, h = img_data.size
        
        output = []
        for y in range(0, h):
            for x in range(0, w):
                idx = x + w*y
                curr_pxl = (0,0,0,0)
                
                if msk_data[index][3]>0:
                    curr_pxl = edge_color 
                else:
                    curr_pxl = img_data[idx]
                output.append(curr_pxl)
        
        img.putdata(output)
    return image

# Example usage
image = Image.open('your_image.png')
image = image.convert("RGBA")
image = change_img_edge(image, 5, (0,255,255, 200))
image.save('new_name.png')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sorcerer