我试图弄清楚如何使用Pillow with Python来炫耀图像的边缘。
我需要像这只可爱的猫一样(忽略可见的边缘):
我尝试了im.filter(ImageFilter.BLUR)
但不是我想要的。
答案 0 :(得分:4)
看一下这个例子:
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)
原始图片(作者 - Irene Mei):
粘贴在白色背景上:
模糊区域(粘贴蒙版):
结果:
答案 1 :(得分:3)
提供带有渐变粘贴蒙版的修改后的解决方案(按@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)
粘贴面膜:
结果: