Python中使用PIL库实现图片高斯模糊实例

yipeiwu_com5年前Python基础

一、安装PIL

PIL是Python Imaging Library简称,用于处理图片。PIL中已经有图片高斯模糊处理类,但有个bug(目前最新的1.1.7bug还存在),就是模糊半径写死的是2,不能设置。在源码ImageFilter.py的第160行:

所以,我们在这里自己改一下就OK了。

项目地址:http://www.pythonware.com/products/pil/

二、修改后的代码

代码如下:

复制代码 代码如下:

#-*- 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)

三、调用

复制代码 代码如下:

simg = 'demo.jpg'
dimg = 'demo_blur.jpg'
image = Image.open(simg)
image = image.filter(MyGaussianBlur(radius=30))
image.save(dimg)
print dimg, 'success'

如果只需要处理某个区域,传入bounds参数即可

四、效果
原图:

处理后的:

相关文章

对django xadmin自定义菜单的实例详解

1、 自定义菜单 adminx.py class GlobalSetting(object): site_title = u'xxx后台' def kuF_site_menu...

对python 多个分隔符split 的实例详解

python中.split()只能用指定一个分隔符 例如: text='3.14:15' print text.split('.') 输出结果如下: ['3', '14:15'...

Python中的枚举类型示例介绍

起步 Python 的原生类型中并不包含枚举类型。为了提供更好的解决方案,Python 通过 PEP 435 在 3.4 版本中添加了 enum 标准库。 枚举类型可以看作是一种标签或...

Python使用chardet判断字符编码

本文实例讲述了Python使用chardet判断字符编码的方法。分享给大家供大家参考。具体分析如下: Python中chardet 用来实现字符串/文件编码检测模板 1、chardet下...

Python的Tornado框架异步编程入门实例

Python的Tornado框架异步编程入门实例

Tornado Tornado 是一款非阻塞可扩展的使用Python编写的web服务器和Python Web框架, 可以使用Tornado编写Web程序并不依赖任何web服务器直接提供高...