import cv2 as cvimport numpy as npimport matplotlib.pyplot as pltimg = cv.imread("../SampleImages/pomeranian.png", cv.IMREAD_COLOR)rows,cols,channels = img.shapeprint(rows,cols,channels)#为图像添加高斯噪声#使用np.random.normal(loc=0.0, scale=1.0, size=None)# loc: 高斯分布中心点,分布的均值# scale: 高斯分布的宽度,分布的标准差# size:维度。如果给定维度是(m,n,k)则从分布中抽取m*n*k个样本#参考资料:https://blog.csdn.net/wzy628810/article/details/103807829# https://blog.csdn.net/sinat_29957455/article/details/123977298def AddGaussianNoise(image, mean=0, var=0.005):image = np.array(image/255, dtype=float)#将像素值归一noise = np.random.normal(mean, var ** 0.5, image.shape) #产生高斯噪声out = image + noise #直接将归一化的图片与噪声相加if out.min() < 0:low_clip = -1.else:low_clip = 0.out = np.clip(out, low_clip, 1.0)out = np.uint8(out*255)return outimg_gaussian_noise = img.copy()gauss_mean = 0gauss_sigma = 0.003#增加高斯噪声到图像img_gaussian_noise = AddGaussianNoise(img_gaussian_noise, gauss_mean, gauss_sigma)#高斯滤波(高斯模糊)#cv.GaussianBlur(src, ksize, sigmaX, sigmaY, borderType)#src: 输入图像#ksize: kernel大小,高斯卷积和大小。注意卷积核的宽度和高度可以不同,但必须为正数且为奇数,也可以为零。#sigmaX/Y: X和Y方向上的高斯标准差#参考资料:https://blog.csdn.net/weixin_52012241/article/details/122284713img_gaussian_blur_origin = cv.GaussianBlur(img, (3,3), 0)img_gaussian_blur_noise = cv.GaussianBlur(img_gaussian_noise, (13,13), 0.006)#显示图像fig,axes = plt.subplots(nrows=2, ncols=2, figsize=(10,10), dpi=100)axes[0][0].imshow(img[:,:,::-1])axes[0][0].set_title("Original")axes[0][1].imshow(img_gaussian_blur_origin[:,:,::-1])axes[0][1].set_title("Original Gaussian Blurred")axes[1][0].imshow(img_gaussian_noise[:,:,::-1])axes[1][0].set_title("Add Gaussian Noise")axes[1][1].imshow(img_gaussian_blur_noise[:,:,::-1])axes[1][1].set_title("Gaussian Noise Blurred")