在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)

相关文章

Python实现栈的方法

本文实例讲述了Python实现栈的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python #定义一个列表来模拟栈 stack = [] #进...

教你学会使用Python正则表达式

教你学会使用Python正则表达式

今天写爬虫偶然想到了初学正则表达式时候,看过一篇文章非常不错。检索一下还真的找到了。 re模块 re.search 经常用match = re.search(pat, str)的形式...

浅谈django model postgres的json字段编码问题

django model的json字段的编码器不能有效编码诸如uuid,datetime等数据类型,当直接存储此类型的对象到json字段中为抛出编码异常,这时可以通过JSONField字...

浅谈Python 的枚举 Enum

枚举是常用的功能,看看Python的枚举. from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'A...

Python入门_浅谈for循环、while循环

Python入门_浅谈for循环、while循环

Python中有两种循环,分别为:for循环和while循环。 1. for循环 for循环可以用来遍历某一对象(遍历:通俗点说,就是把这个循环中的第一个元素到最后一个元素依次访问一次)...