Otor
Otor

Reputation: 420

Make blur all around a rectangle in image with PIL

I was wondering if it was possible to do a blur all around a rectangle with the PIL module on python. I've tried things and as this post shows, you can do masks in order to isolate a certain area. In this post he is doing the opposite of what I want but I didn't manage to find the solution.

Here is my code working with only blurring the rectangle :

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

# Open an image
im = Image.open('3055.png')

x1=810
y1=97
x2=1177
y2=992

# Create rectangle mask
mask = Image.new('L', im.size, 0)
draw = ImageDraw.Draw(mask)
draw.rectangle([ (x1,y1), (x2,y2) ], fill=255)
mask.save('mask.png')

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

# Paste blurred region and save result
im.paste(blurred, mask=mask)
im.save("blurredImg.png")

The images :

originalImage

blurredImg

To sum up, I just want to have the outside of the pink box blurred but not the inside.

Upvotes: 4

Views: 3235

Answers (2)

Zsolt Voroshazi
Zsolt Voroshazi

Reputation: 21

Thanks. Your code snippet helps me a lot. During my probes I've found another solution as:

mask = Image.new('L', im.size, 255)  # set color value 0 -> 255
draw = ImageDraw.Draw(mask) #unchanged
draw.rectangle([ (x1,y1), (x2,y2) ], fill=0)  # set fill level 255 -> 0
#this will create and inverted B/W mask

Upvotes: 2

lenik
lenik

Reputation: 23498

You may replace the last 3 lines of your code with this:

# Paste blurred region and save result
blurred.paste(im, mask=mask)
blurred.save("blurredImg.png")

effectively pasting the original image over the blurred using mask, and saving the result.

Upvotes: 4

Related Questions