簡體   English   中英

如何使用Python PIL模糊非矩形或圓形圖像區域?

[英]How to blur non-rectangular or circular area of image with Python PIL?

在Python中使用PIL,我將PNG圖像疊加在另一個更大的圖像上。 較小的圖像是半透明的。

我希望較小圖像背后的區域在較大的圖像上模糊。 以下代碼模糊了一個矩形區域:

box = (3270, 1150, 4030, 2250)      # (x1, y1, x2, y2)
ic = outputImage.crop(box)
ic = ic.filter(ImageFilter.BoxBlur(20))
outputImage.paste(ic, box)

但是,我需要模糊一個有圓角的矩形區域。

這就是疊加圖像的樣子:

那么,是否可以為PIL中的裁剪區域定義自定義形狀?

如果沒有,是否有可能至少裁剪圓形區域? (對於完全覆蓋並且沒有任何懸垂,我的區域將不得不分解為6個子區域:4個圓圈和2個矩形。完成所有這些將減慢我的代碼,但我會采取任何我能得到的解決方案。)

我知道這可以用Numpy來完成 ,但是我更喜歡使用PIL,因為這個腳本中的其他內容都已經用PIL編碼了。

看一下這個例子( 這里的 rounded_rectangle函數):

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

def rounded_rectangle(draw, xy, rad, fill=None):
    x0, y0, x1, y1 = xy
    draw.rectangle([ (x0, y0 + rad), (x1, y1 - rad) ], fill=fill)
    draw.rectangle([ (x0 + rad, y0), (x1 - rad, y1) ], fill=fill)
    draw.pieslice([ (x0, y0), (x0 + rad * 2, y0 + rad * 2) ], 180, 270, fill=fill)
    draw.pieslice([ (x1 - rad * 2, y1 - rad * 2), (x1, y1) ], 0, 90, fill=fill)
    draw.pieslice([ (x0, y1 - rad * 2), (x0 + rad * 2, y1) ], 90, 180, fill=fill)
    draw.pieslice([ (x1 - rad * 2, y0), (x1, y0 + rad * 2) ], 270, 360, fill=fill)

# Open an image
im = Image.open(INPUT_IMAGE_FILENAME)

# Create rounded rectangle mask
mask = Image.new('L', im.size, 0)
draw = ImageDraw.Draw(mask)
rounded_rectangle(draw, (im.size[0]//4, im.size[1]//4, im.size[0]//4*3, im.size[1]//4*3), rad=40, fill=255)
mask.save('mask.png')

# Blur image
blurred = im.filter(ImageFilter.GaussianBlur(20))

# Paste blurred region and save result
im.paste(blurred, mask=mask)
im.save(OUTPUT_IMAGE_FILENAME)

輸入圖片:

可樂在海灘上(在烏克蘭)

面具:

與圓角落的白色長方形在黑背景

輸出圖像:

被弄臟的罐頭在海灘的可樂

用Python 2.7.12和Pillow 3.1.2測試(它沒有BoxBlur)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM