在Python中使用PIL模块对图片进行高斯模糊处理的教程

yipeiwu_com5年前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根据文件名批量转移图片的方法

下面是在深度学习数据集处理过程中可能会用到的一个小程序,帮助我们根据图片文件的名字来分开图片: import os import shutil path_img='读取图片的路径'...

django的model操作汇整详解

django的model操作汇整详解

单表操作 增加数据 auther_obj = {"auther_name":"崔皓然","auther_age":1} models.auther.objects.create(...

python中map()与zip()操作方法

对于map()它的原型是:map(function,sequence),就是对序列sequence中每个元素都执行函数function操作。 比如之前的a,b,c = map(int,r...

pytorch逐元素比较tensor大小实例

如下所示: import torch a = torch.tensor([[0.01, 0.011], [0.009, 0.9]]) mask = a.gt(0.01) print(...

Python实现约瑟夫环问题的方法

本文实例讲述了Python实现约瑟夫环问题的方法。分享给大家供大家参考,具体如下: 题目:0,1,...,n-1这n个数字排成一个圆圈,从数字0开始每次从这个圆圈里删除第m个数字。求出这...