1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| import cv2 import math import matplotlib.pyplot as plt import numpy as np
def my_gaussian(img, sigma): H, W = img.shape noise = np.random.randn(H,W) gaussian_noises = np.sqrt(2*math.pi*sigma**2)*np.exp((-(noise-np.mean(noise))**2)/(2*sigma**2)) img = img /255 gaussian_out = img + gaussian_noises gaussian_out = np.clip(gaussian_out,0,1) gaussian_out = np.uint8(gaussian_out*255) return gaussian_out, gaussian_noises def gaussian_noise(img, mean, sigma): ''' 此函数用将产生的高斯噪声加到图片上 传入: img : 原图 mean : 均值 sigma : 标准差 返回: gaussian_out : 噪声处理后的图片 noise : 对应的噪声 ''' img = img / 255 noise = np.random.normal(mean, sigma, img.shape) gaussian_out = img + noise gaussian_out = np.clip(gaussian_out, 0, 1) gaussian_out = np.uint8(gaussian_out*255) return gaussian_out, noise
if __name__=="__main__":
src = cv2.imread('img.png', 0) fig_out = plt.figure(figsize=(4, 2), dpi=370) fig_noise = plt.figure(figsize=(4, 2), dpi=370)
for i in range(0, 8):
gaussian_out, noise = my_gaussian(src, 0.03*i) ax_out = fig_out.add_subplot(i+241) ax_noise = fig_noise.add_subplot(i+241) ax_out.axis('off') ax_noise.axis('off') ax_out.set_title('$\sigma$ = '+str(0.03*i), loc='left', fontsize=3, fontstyle='italic') ax_noise.set_title('$\sigma$ = '+str(0.03*i), loc='left', fontsize=3, fontstyle='italic') ax_out.imshow(gaussian_out, cmap='gray') ax_noise.imshow((noise+1)/2, cmap='gray')
fig_out.savefig('1_Peppers_noise.png') fig_noise.savefig('1_Guassion_noise.png') plt.show()
|