欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在Python中使用PIL模块对图片进行高斯模糊处理的教程

程序员文章站 2022-04-30 21:08:13
从一篇文章中看到,pil 1.1.5 已经内置了高斯模糊,但是并没有在文档中提及,而且pil的高斯模糊中 radius 是硬编码, 虽然构造方法中有传入 radius 参数...

从一篇文章中看到,pil 1.1.5 已经内置了高斯模糊,但是并没有在文档中提及,而且pil的高斯模糊中 radius 是硬编码, 虽然构造方法中有传入 radius 参数,但压根就没有用到 (),所以需要自己进行改造,当然,知道了原因, 修改起来自然非常简单了。

结合帖子中的需求,对局部进行高斯模糊,所以还需要结合使用 crop paste 方法实现局部使用滤镜。

代码如下:

#-*- coding: utf-8 -*-

from pil import image, imagefilter

class mygaussianblur(imagefilter.filter):
  name = "gaussianblur"

  def __init__(self, radius=2, bounds=none):
    self.radius = radius
    self.bounds = bounds

  def filter(self, image):
    if self.bounds:
      clips = image.crop(self.bounds).gaussian_blur(self.radius)
      image.paste(clips, self.bounds)
      return image
    else:
      return image.gaussian_blur(self.radius)

bounds = (150, 130, 280, 230)
image = image.open('source.jpg')
image = image.filter(mygaussianblur(radius=29, bounds=bounds))
image.show()

可以看下效果:

在Python中使用PIL模块对图片进行高斯模糊处理的教程

在Python中使用PIL模块对图片进行高斯模糊处理的教程