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

yipeiwu_com6年前Python基础

从一篇文章中看到,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()

可以看下效果:

201555170400852.jpg (500×667)

201555170538214.jpg (500×667)

相关文章

使用tensorflow DataSet实现高效加载变长文本输入

DataSet是tensorflow 1.3版本推出的一个high-level的api,在1.3版本还只是处于测试阶段,1.4版本已经正式推出。 在网上搜了一遍,发现关于使用DataSe...

Python入门之三角函数tan()函数实例详解

描述 tan() 返回x弧度的正弦值。 语法 以下是 tan() 方法的语法: import math math.tan(x) 注意:tan()是不能直接访问的,需要导入 m...

Django中celery执行任务结果的保存方法

如下所示: pip3 install django-celery-results INSTALLED_APPS = ( ..., 'django_celery_results',) #...

windows下python安装pip图文教程

windows下python安装pip图文教程

windows下python安装pip 简易教程,具体内容如下 1.前提 你要已经安装了 某个 版本的 python, 下载地址) 安装后,需要配置python.exe 的环境变量,否则...

Python之PyUnit单元测试实例

本文实例讲述了Python之PyUnit单元测试,与erlang eunit单元测试很像,分享给大家供大家参考。具体方法如下: 1.widget.py文件如下: 复制代码 代码如下:#!...