用枕头在图像上的羽毛边缘

时间:2018-06-10 20:52:28

标签: image python-3.6 pillow

我试图弄清楚如何使用Pillow with Python来炫耀图像的边缘。

我需要像这只可爱的猫一样(忽略可见的边缘):

enter image description here

我尝试了im.filter(ImageFilter.BLUR)但不是我想要的。

2 个答案:

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

Kitty

粘贴在白色背景上:

Kitty pasted on white background

模糊区域(粘贴蒙版):

Blur region

结果:

Image of a kitty with feathered (blurred) edges

答案 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)

粘贴面膜:

Blurred black rectangle

结果:

Feathered portrait of a cat