高斯滤波是对整幅图像进行加权平均的过程,每一个像素点的值,都由其本身和邻域内的其他像素值经过加权平均后得到。其滤波核的值由如下公式得到(用当前点与中心点的欧式距离的平方代替下面的( x 2 + y 2 x^2+y^2 x2+y2):
G ( x , y ) = 1 2 Π σ e − x 2 + y 2 2 σ 2 G\text{(}x,y\text{)}=\frac{1}{\sqrt{2\varPi}\sigma }e^{-\frac{x^2+y^2}{2\sigma ^2}} G(x,y)=2Πσ1e−2σ2x2+y2
在高斯滤波中,对每一个元素而言,则用它周围邻域和自身的加权求和代替它自身的值,
假设滤波核是 3 × 3 3\times 3 3×3, a 5 a_5 a5为当前元素,
它周围8联通的像素值分别是 a 1 、 a 2 、 a 3 、 a 4 、 a 6 、 a 7 、 a 8 、 a 9 a_1、a_2、a_3、a_4、a_6、a_7、a_8、a_9 a1、a2、a3、a4、a6、a7、a8、a9,
它对应的权值分别是 w 1 、 w 2 、 w 3 、 w 4 、 w 5 、 w 6 、 w 7 、 w 8 、 w 9 w_1、w_2、w_3、w_4、w_5、w_6、w_7、w_8、w_9 w1、w2、w3、w4、w5、w6、w7、w8、w9,
则有
其中权值矩阵的值是由该高斯的空间距离公式决定的
G ( x , y ) = 1 2 Π σ e − x 2 + y 2 2 σ 2 G\text{(}x,y\text{)}=\frac{1}{\sqrt{2\varPi}\sigma }e^{-\frac{x^2+y^2}{2\sigma ^2}} G(x,y)=2Πσ1e−2σ2x2+y2
import cv2 as cv
import numpy as np
import math
import copy
gauss = np.array([1,2,1,2,4,2,1,2,1])
def spilt( a ):
if a/2 == 0:
x1 = x2 = a/2
else:
x1 = math.floor( a/2 )
x2 = a - x1
return -x1,x2
def gaussian_b0x(a, b):
judge = 10
sum = 0
box =[]
x1, x2 = spilt(a)
y1, y2 = spilt(b)
for i in range (x1, x2 ):
for j in range(y1, y2):
t = i*i + j*j
re = math.e ** (-t/(2*judge*judge))
sum = sum + re
box.append(re)
box = np.array(box)
box = box / sum
# for x in box :
# print (x)
return box
def original (i, j, k,a, b,img):
x1, x2 = spilt(a)
y1, y2 = spilt(b)
temp = np.zeros(a * b)
count = 0
for m in range(x1, x2):
for n in range(y1, y2):
if i + m < 0 or i + m > img.shape[0] - 1 or j + n < 0 or j + n > img.shape[1] - 1:
temp[count] = img[i, j, k]
else:
temp[count] = img[i + m, j + n, k]
count += 1
return temp
def gaussian_function(a, b, img, gauss_fun ):
img0 = copy.copy(img)
for i in range (0 , img.shape[0] ):
for j in range (2 ,img.shape[1] ):
for k in range (img.shape[2]):
temp = original(i, j, k, a, b, img0)
img[i,j,k] = np.average(temp ,weights = gauss_fun)#按权分配
return img
def main():
gauss_new = gaussian_b0x(3 , 3)
img0 = cv.imread(r"noise.jpg")
gauss_img = gaussian_function(3, 3, copy.copy(img0), copy.copy(gauss_new))
cv.imshow("guassian_img", gauss_img)
cv.imshow("yuantu", img0)
cv.waitKey(0)
cv.destroyAllWindows()
if __name__ == "__main__":
main()