我实现了一种检测面部的算法,我想模糊面部。我正在使用PIL来模糊它。
image = Image.open(path_img)
draw = ImageDraw.Draw(image)
draw.ellipse((top, left, bottom, right), fill = 'white', outline ='white')
我用我的代码得到了这个
我想用:
blurred_image = cropped_image.filter(ImageFilter.GaussianBlur(radius=10 ))
但我无法使用它,因为我使用的是ImageDraw,它只适用于Image类。如何用脸上的椭圆(圆形)模糊?
谢谢
模糊椭圆是最好的方法
使用Pillow,最好的方法是使用模糊的椭圆作为composite
的混合蒙版。
from PIL import Image, ImageDraw, ImageFilter
def make_ellipse_mask(size, x0, y0, x1, y1, blur_radius):
img = Image.new("L", size, color=0)
draw = ImageDraw.Draw(img)
draw.ellipse((x0, y0, x1, y1), fill=255)
return img.filter(ImageFilter.GaussianBlur(radius=blur_radius))
kitten_image = Image.open("kitten.jpg")
overlay_image = Image.new("RGB", kitten_image.size, color="orange") # This could be a bitmap fill too, but let's just make it orange
mask_image = make_ellipse_mask(kitten_image.size, 150, 70, 350, 250, 5)
masked_image = Image.composite(overlay_image, kitten_image, mask_image)
masked_image.show()
给定this adorable kitten作为输入,输出为
编辑:灵感来自Mark Setchell的答案,只需将overlay_image
线更改为
overlay_image = kitten_image.filter(ImageFilter.GaussianBlur(radius=15))
给我们这个模糊变体(模糊的边缘光滑:))
不确定是否要在图像上合成某些内容以隐藏内容或模糊内容。这更模糊:-)
从帕丁顿开始:
您可以像这样进入“Stealth Mode”:
#!/usr/bin/env python3
from PIL import Image, ImageDraw, ImageFilter
import numpy as np
# Open image
im = Image.open('paddington.png')
# Make a mask the same size as the image filled with black
mask = Image.new('RGB',im.size)
# Draw a filled white circle onto the black mask
draw = ImageDraw.Draw(mask)
draw.ellipse([90,40,300,250],fill=(255,255,255))
# Blur the entire image
blurred = im.filter(ImageFilter.GaussianBlur(radius=15))
# Select either the original or the blurred image at each pixel, depending on the mask
res = np.where(np.array(mask)>0,np.array(blurred),np.array(im))
# Convert back to PIL Image and save
Image.fromarray(res).save('result.png')
或者,正如@AKX所建议的那样,您可以删除Numpy依赖项并使代码更小但仍然得到相同的结果:
#!/usr/bin/env python3
from PIL import Image, ImageDraw, ImageFilter
import numpy as np
# Open image
im = Image.open('paddington.png')
# Make a mask the same size as the image filled with black
mask = Image.new('L',im.size)
# Draw a filled white circle onto the black mask
draw = ImageDraw.Draw(mask)
draw.ellipse([90,40,300,250],fill=255)
# Blur the entire image
blurred = im.filter(ImageFilter.GaussianBlur(radius=15))
# Composite blurred image over sharp one within mask
res = Image.composite(blurred, im, mask)
# Save
res.save('result.png')