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

四、效果
原图:

处理后的:

相关文章

Python编码类型转换方法详解

本文实例讲述了Python编码类型转换方法。分享给大家供大家参考,具体如下: 1:Python和unicode 为了正确处理多语言文本,Python在2.0版后引入了Unicode字符串...

python getopt模块使用实例解析

这篇文章主要介绍了python getopt模块使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 官方介绍地址: ...

Python探索之SocketServer详解

SocketServer,网络通信服务器,是Python标准库中的一个模块,其作用是创建网络服务器。SocketServer模块定义了一些类来处理诸如TCP、UDP、UNIX流和UNIX...

Python自定义简单图轴简单实例

Python自定义简单图轴简单实例

简单定义图轴: import numpy as np import matplotlib.pyplot as plt 创建一个简单的matplotlib实例: fig = pl...

Python FtpLib模块应用操作详解

本文实例讲述了Python FtpLib模块应用操作。分享给大家供大家参考,具体如下: Python之FtpLib模块应用 工厂中有这样的应用场景: 需要不间断地把设备电脑生成的数据文件...