Feathered edges on image with Pillow

谁说我不能喝 提交于 2019-12-22 09:40:34

问题


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):

I tried im.filter(ImageFilter.BLUR) but is not what I'm looking for.


回答1:


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:




回答2:


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:



来源:https://stackoverflow.com/questions/50787948/feathered-edges-on-image-with-pillow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!