python – How to make a blur like in the photo using pillow


blur_width = image.width // blur_width_constant #blur_width_constant is  user defined
mask = Image.new('L', (image.width, image.height), 0)
mask_np = np.array(mask)
for i in range(blur_width):
    mask_np[:, i] = int(255 * (i / blur_width))  
mask = Image.fromarray(mask_np)

blurred_image = image.filter(ImageFilter.GaussianBlur(blur_radius))#blur_width is  user defined
final_image = Image.composite(blurred_image, image, mask)

This is the best I can provide with the limited context. Things to take care I have added a masking layer for blurring so you can blur out the area which you want by changing the mask.

import numpy as np
from PIL import Image, ImageDraw, ImageFilter
img = Image.new('RGB', (300, 200), color="white")
d = ImageDraw.Draw(img)
d.rectangle([50, 50, 150, 150], outline="black", fill="blue")
img.save('sample_image.jpg')

##################################Generated a image
image = Image.open('sample_image.jpg')
blur_width = image.width // 10  

mask = Image.new('L', (image.width, image.height), 0)
mask_np = np.array(mask)
for i in range(blur_width):
    mask_np[:, i] = int(255 * (i / blur_width))  
mask = Image.fromarray(mask_np)

blurred_image = image.filter(ImageFilter.GaussianBlur(25))  
final_image = Image.composite(blurred_image, image, mask)
final_image.show()

where I guess the blur_radius of gaussian blur is self explanatory. But coming to blur_width_constant it is how much are from right you wanted to be blurred. It is getting used for generation of mask but mask can be as per your design, but once the mask is generated then the same flow can be followed as per requirement.

Sample output:

enter image description here



Source link

Leave a Comment