How can I feather an image horizontally using Python?

我的梦境 提交于 2020-08-10 19:25:21

问题


I need to feather an image horizontally (and not vertically), using Python.

I have used Feathered edges on image with Pillow as a starting point and got to the below, which removes the additional white at the top and bottom of the image, but does not prevent the feathering at the top and bottom.

How should I modify the script further to avoid the top and bottom of the image being blurred?

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFilter

RADIUS = 25

INPUT_IMAGE_FILENAME = 'MY_INPUT_PATH'
OUTPUT_IMAGE_FILENAME = 'MY_OUTPUT_PATH'

# 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]), (255,255,255))
back.paste(im, (RADIUS, 0))

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

Example input:

Example output (note unwanted blurring at top and bottom):

来源:https://stackoverflow.com/questions/63016750/how-can-i-feather-an-image-horizontally-using-python

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