I\'m trying to figure out how to feather the edges of an image using Pillow with Python.
I need something like this cute cat (ignore the visible edges):
Have a look at this example:
from PIL import Image
from PIL import ImageFilter
RADIUS = 10
# Open an image
im = Image.open(INPUT_IMAGE_FILENAME)
# Paste image on white background
diam = 2*RADIUS
back = Image.new('RGB', (im.size[0]+diam, im.size[1]+diam), (255,255,255))
back.paste(im, (RADIUS, RADIUS))
# Create blur mask
mask = Image.new('L', (im.size[0]+diam, im.size[1]+diam), 255)
blck = Image.new('L', (im.size[0]-diam, im.size[1]-diam), 0)
mask.paste(blck, (diam, diam))
# Blur image and paste blurred edge according to mask
blur = back.filter(ImageFilter.GaussianBlur(RADIUS/2))
back.paste(blur, mask=mask)
back.save(OUTPUT_IMAGE_FILENAME)
Original image (author - Irene Mei):
Pasted on white background:
Blur region (paste mask):
Result:
Providing modified solution with gradient paste mask (as requested by @Crickets).
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFilter
RADIUS = 10
# Open an image
im = Image.open(INPUT_IMAGE_FILENAME)
# Paste image on white background
diam = 2*RADIUS
back = Image.new('RGB', (im.size[0]+diam, im.size[1]+diam), (255,255,255))
back.paste(im, (RADIUS, RADIUS))
# Create paste mask
mask = Image.new('L', back.size, 0)
draw = ImageDraw.Draw(mask)
x0, y0 = 0, 0
x1, y1 = back.size
for d in range(diam+RADIUS):
x1, y1 = x1-1, y1-1
alpha = 255 if d<RADIUS else int(255*(diam+RADIUS-d)/diam)
draw.rectangle([x0, y0, x1, y1], outline=alpha)
x0, y0 = x0+1, y0+1
# Blur image and paste blurred edge according to mask
blur = back.filter(ImageFilter.GaussianBlur(RADIUS/2))
back.paste(blur, mask=mask)
back.save(OUTPUT_IMAGE_FILENAME)
Paste mask:
Result: