Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter part of image using PIL, python

I can't understand how to apply blur filter to part of an image using PIL. I've tried to search with google and read PIL documentation but didn't find anything useful. Thanks for help.

like image 988
matvey.co Avatar asked Mar 14 '12 11:03

matvey.co


People also ask

How do you blur an image in Python PIL?

PIL. ImageFilter. BoxBlur(): Blurs the image by setting each pixel to the average value of the pixels in a square box extending radius pixels in each direction.

Is PIL and Pillow the same?

What is PIL/Pillow? PIL (Python Imaging Library) adds many image processing features to Python. Pillow is a fork of PIL that adds some user-friendly features.


2 Answers

You can crop out a section of the image, blur it, and stick it back in. Like this:

box = (30, 30, 110, 110)
ic = image.crop(box)
for i in range(10):  # with the BLUR filter, you can blur a few times to get the effect you're seeking
    ic = ic.filter(ImageFilter.BLUR)
image.paste(ic, box)

enter image description here

Below is the full code I used to generate the chess board, save the image, etc. (This isn't the most efficient way to generate a chessboard, etc, it's just for the demo.)

import Image, ImageDraw, ImageFilter
from itertools import cycle

def draw_chessboard(n=8, pixel_width=200):
    "Draw an n x n chessboard using PIL."
    def sq_start(i):
        "Return the x/y start coord of the square at column/row i."
        return i * pixel_width / n

    def square(i, j):
        "Return the square corners, suitable for use in PIL drawings" 
        return map(sq_start, [i, j, i + 1, j + 1])

    image = Image.new("L", (pixel_width, pixel_width))
    draw_square = ImageDraw.Draw(image).rectangle
    squares = (square(i, j)
               for i_start, j in zip(cycle((0, 1)), range(n))
               for i in range(i_start, n, 2))
    for sq in squares:
        draw_square(sq, fill='white')
    image.save("chessboard-pil.png")
    return image

image = draw_chessboard()

box = (30, 30, 110, 110)

ic = image.crop(box)

for i in range(10):
    ic = ic.filter(ImageFilter.BLUR)

image.paste(ic, box)

image.save("blurred.png")
image.show()

if __name__ == "__main__":
    draw_chessboard()
like image 191
tom10 Avatar answered Oct 12 '22 23:10

tom10


I am just adding to the above answer posted by @tom10.

# importing PILLOW library.
from PIL import Image, ImageFilter

image = Image.open('path/to/image_file')
box = (30, 30, 110, 110)
crop_img = image.crop(box)
# Use GaussianBlur directly to blur the image 10 times. 
blur_image = crop_img.filter(ImageFilter.GaussianBlur(radius=10))
image.paste(blur_image, box)
image.save('path/to/save_image_file')

I have just replaced the ImageFilter.Blur with ImageFilter.GaussianBlur(radius=10). You can change the amount of blur by changing the radius value.

like image 43
Amanpreet Avatar answered Oct 12 '22 23:10

Amanpreet