python的N個小功能(高斯模糊原理及實踐)


原理:

二維高斯函數

  

1)         為了計算權重矩陣,需要設定σ的值。假定σ=1.5,則模糊半徑為1的權重矩陣如下:

 

2)         這9個點的權重總和等於0.4787147,如果只計算這9個點的加權平均,還必須讓它們的權重之和等於1,因此上面9個值還要分別除以0.4787147,得到最終的權重矩陣。

 

有了權重矩陣,就可以計算高斯模糊的值了。

3)         假設現有9個像素點,灰度值(0-255)如下:

 

4)         每個點乘以自己的權重值:

 

5)         得到

 

將這9個值加起來,就是中心點的高斯模糊的值。

對所有點重復這個過程,就得到了高斯模糊后的圖像。如果原圖是彩色圖片,可以對RGB三個通道分別做高斯模糊。

 

############################################################################################高斯模糊,按照給定的txt文檔每4個數據模糊相應位置#################

###############################################################################

# -*- coding: utf-8 -*-

"""

Created on Tue Mar 07 14:00:00 2017

 

@author: sl

"""

 

 

import os

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) ###圖片的最前頭拷貝一部分圖片(使用crop函數),進行高斯模糊處理

      image.paste(clips, self.bounds)  ###粘貼到需要修改的圖片上,來完成相應覆蓋

      return image

    else:

      return image.gaussian_blur(self.radius)

 

image = Image.open(r"G:\test.jpg")

i=0

a=0

b=0

c=0

d=0

j=0

num=0

 

for line in open(r"G:\a.txt"):

  j=j+1

 

num=j

if num!=0:

  for line in open(r"G:\a.txt"):

    i=i+1

    if((i%4)==1):

      a=int(line)

    elif((i%4)==2):

      b=int(line)

    elif((i%4)==3):

      c=int(line)

    else:

      d=int(line)

      if((i%num)==4):

       

        h=min(20,int((c-a)/4))

        w=min(20,int((d-b)/4))

        bounds = (a+h,b+w,c-h,d-w)

        image = image.filter(MyGaussianBlur(radius=29, bounds=bounds))

      elif((i%num)==8):

        h=min(5,int((c-a)/4))

        w=min(5,int((d-b)/4))

        bounds = (a+h,b+w,c-h,d-w)

        image = image.filter(MyGaussianBlur(radius=29, bounds=bounds))

       

      else:

        h=min(10,int((c-a)/4))

        w=min(10,int((d-b)/4))

        bounds = (a+h,b+w,c-h,d-w)

        image = image.filter(MyGaussianBlur(radius=29, bounds=bounds))

 

if num==16:

  image.save('G:\\aaa.jpg')

else:

  image.save('G:\\pp\\aaa.jpg')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM