Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

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

1 Answer

0 votes
by (25.1k points)

The problem is that you are pasting the blurred image and then masking it. You need to paste the original image and then mask it.

In the last second line instead of this:

im.paste(blurred, mask=mask)

use this:

blurred.paste(im, mask=mask)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...