萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> 在Python中使用PIL模塊對圖片進行高斯模糊處理的教程

在Python中使用PIL模塊對圖片進行高斯模糊處理的教程

   這篇文章主要介紹了在Python中使用PIL模塊對圖片進行高斯模糊處理的教程,這個無圖形界面的腳本代碼非常簡單,需要的朋友可以參考下

  從一篇文章中看到,PIL 1.1.5 已經內置了高斯模糊,但是並沒有在文檔中提及,而且PIL的高斯模糊中 radius 是硬編碼, 雖然構造方法中有傳入 radius 參數,但壓根就沒有用到 (看這裡),所以需要自己進行改造,當然,知道了原因, 修改起來自然非常簡單了。

  結合帖子中的需求,對局部進行高斯模糊,所以還需要結合使用 crop 和 paste 方法實現局部使用濾鏡。

  代碼如下:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #-*- 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)
copyright © 萬盛學電腦網 all rights reserved