# 圖片雜訊處理（二）

``````import cv2
import numpy as np

def white_noise(image, min_noise, max_noise):
img = np.copy(image)
noise = np.random.randint(min_noise, max_noise, img.shape)
return np.clip(img + noise, 0, 255).astype('uint8')

noisy = white_noise(img, -5, 5)

cv2.imshow('White Noise', noisy)

cv2.waitKey(0)
cv2.destroyAllWindows()
``````

``````import cv2
import numpy as np
import matplotlib.pyplot as plt

width = 250
height = 250

img = np.random.randint(0, 255, (height, width)).astype('uint8')

cv2.imshow('White Noise', img)

plt.hist(img.ravel(), 256, [0, 256])
plt.show())
``````

（後續文件會看到，灰階圖像的灰階值，可以分解為數個週期變化，與那些週期相對的就是頻率，那些頻率就是指圖像的頻率。）

`white_noise` 給定的範圍大，每個像素彼此間的雜訊變化大，也就構成了高頻訊號，就這點來看，之前看過的椒鹽雜訊就是高頻訊號。

``````import cv2
import numpy as np

def gaussian_noise(image, mean = 0, sigma = 1):
img = np.copy(image)
noise = np.random.normal(mean, sigma, img.shape)
return np.clip(img + noise, 0, 255).astype('uint8')

mean = 0            # 平均值
sigma = 15          # 標準差

noisy = gaussian_noise(img, mean, sigma)

cv2.imshow('Gaussian Noise',  noisy)

cv2.waitKey(0)
cv2.destroyAllWindows()
``````

``````import cv2
import numpy as np
import matplotlib.pyplot as plt

width = 250
height = 250
mean = 0
sigma = 15

img = np.random.normal(mean, sigma, (height, width))
cv2.imshow('Gaussian Noise', img)

a, b = np.min(img), np.max(img)
plt.hist(img.ravel(), int(b - a), [a, b])
plt.show()
``````