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

yipeiwu_com6年前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参数即可

四、效果
原图:

处理后的:

相关文章

python解析xml文件操作实例

本文实例讲述了python解析xml文件操作的实现方法。分享给大家供大家参考。具体方法如下: xml文件内容如下: <?xml version="1.0" ?&...

Python中函数的多种格式和使用实例及小技巧

这里先解释一下几个概念 - 位置参数:按位置设置的参数,隐式用元组保存对应形参.平时我们用的大多数是按位置传参.比如有函数def func(a,b,c),调用func(1,2,3).即...

python根据出生日期获得年龄的方法

本文实例讲述了python根据出生日期获得年龄的方法。分享给大家供大家参考。具体如下: 这段代码可以根据用户的出生日期获得其年龄,born参数为date类型 def calculat...

python 变量初始化空列表的例子

python 不能写new_loss=old_loss=[] 这样 两个变量实际上是同一个list 要分开写new_loss=[] Old_loss=[] 以下列数据文件为例: de...

Python入门篇之函数

Pythond 的函数是由一个新的语句编写,即def,def是可执行的语句--函数并不存在,直到Python运行了def后才存在。 函数是通过赋值传递的,参数通过赋值传递给函数 def语...