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入门教程 超详细1小时学会Python

Python入门教程 超详细1小时学会Python

为什么使用Python    假设我们有这么一项任务:简单测试局域网中的电脑是否连通.这些电脑的ip范围从192.168.0.101到192.168.0.200.&nbs...

关于pymysql模块的使用以及代码详解

pymysql模块的使用 查询一条数据fetchone() from pymysql import * conn = connect( host='127.0.0.1',...

Python中正反斜杠(‘/’和‘\’)的意义与用法

刚刚在学习些测试报告的时候,出现一个路径的问题,找了很久的原因,竟然是少了一个反斜杠引起的,在此顺便记录一下正反斜杠的作用。 在Python中,记录路径时有以下几种写法,如:(大家都知道...

Python分割指定页数的pdf文件方法

如下所示: from PyPDF2 import PdfFileWriter, PdfFileReader # 开始页 start_page = 0 # 截止页 end_page...

python读取一个目录下所有txt里面的内容方法

实例如下所示: import os allFileNum = 0 def printPath(level, path): global allFileNum ''''' 打印一...