高斯模糊對高斯噪聲有抑制作用
假設高斯函數是G(x),對於圖像,假設高斯核是1*3的,則x是-1, 0,1,對應於G(-1),G(0)、G(1),sum=G(-1)+G(0)+G(1),則
G(-1)/sum + G(0)/sum + G(1)/sum = 1
import cv2 as cv
import numpy as np
def clamp(pv):
if pv > 255:
return 255
elif pv < 0:
return 0
else:
return pv
# 定義高斯噪聲
def gaussian_noise(image):
h, w, c = image.shape
for row in range(h):
for col in range(w):
# 產生隨機數,每次隨機產生三個隨機數,給R、G、B三個通道用
s = np.random.normal(0, 20, 3)
b = image[row, col, 0] # blue
g = image[row, col, 1] # green
r = image[row, col, 2] # red
image[row, col, 0] = clamp(b + s[0])
image[row, col, 1] = clamp(g + s[0])
image[row, col, 2] = clamp(r + s[0])
cv.imshow('noise image', image)
src = cv.imread('C:/Users/Y/Pictures/Saved Pictures/demo.png')
cv.namedWindow('input image', cv.WINDOW_AUTOSIZE)
cv.imshow('input image', src)
t1 = cv.getTickCount()
gaussian_noise(src)
t2 = cv.getTickCount()
time = (t2-t1)/cv.getTickFrequency()
print('time: %s ms' % (time*1000))
dst = cv.GaussianBlur(src, (5, 5), 15) # 5*5的卷積核
cv.imshow('Gaussian Blur', dst)
cv.waitKey(0)
cv.destroyAllWindows()