一、隨機噪聲、高斯噪聲和椒鹽噪聲
1、效果展示
2、代碼部分
import cv2 import numpy as np from PyQt5.QtCore import QThread import random class Noise(QThread): def __init__(self): super(Noise, self).__init__() pass def random_noise(self, image, noise_num): ''' 添加隨機噪點(實際上就是隨機在圖像上將像素點的灰度值變為255即白色) :param image: 需要加噪的圖片 :param noise_num: 添加的噪音點數目,一般是上千級別的 :return: img_noise ''' # # 參數image:,noise_num: img = cv2.imread(image) img_noise = img # cv2.imshow("src", img) rows, cols, chn = img_noise.shape # 加噪聲 for i in range(noise_num): x = np.random.randint(0, rows) # 隨機生成指定范圍的整數 y = np.random.randint(0, cols) img_noise[x, y, :] = 255 return img_noise def sp_noise(self, image, prob): ''' 添加椒鹽噪聲 image:原始圖片 prob:噪聲比例 ''' image = cv2.imread(image) output = np.zeros(image.shape, np.uint8) noise_out = np.zeros(image.shape, np.uint8) thres = 1 - prob for i in range(image.shape[0]): for j in range(image.shape[1]): rdn = random.random() # 隨機生成0-1之間的數字 if rdn < prob: # 如果生成的隨機數小於噪聲比例則將該像素點添加黑點,即椒噪聲 output[i][j] = 0 noise_out[i][j] = 0 elif rdn > thres: # 如果生成的隨機數大於(1-噪聲比例)則將該像素點添加白點,即鹽噪聲 output[i][j] = 255 noise_out[i][j] = 255 else: output[i][j] = image[i][j] # 其他情況像素點不變 noise_out[i][j] = 100 result = [noise_out, output] # 返回椒鹽噪聲和加噪圖像 return result def gasuss_noise(self, image, mean=0, var=0.001): ''' 添加高斯噪聲 image:原始圖像 mean : 均值 var : 方差,越大,噪聲越大 ''' image = cv2.imread(image) image = np.array(image/255, dtype=float)#將原始圖像的像素值進行歸一化,除以255使得像素值在0-1之間 noise = np.random.normal(mean, var ** 0.5, image.shape)#創建一個均值為mean,方差為var呈高斯分布的圖像矩陣 out = image + noise#將噪聲和原始圖像進行相加得到加噪后的圖像 if out.min() < 0: low_clip = -1. else: low_clip = 0. out = np.clip(out, low_clip, 1.0)#clip函數將元素的大小限制在了low_clip和1之間了,小於的用low_clip代替,大於1的用1代替 out = np.uint8(out*255)#解除歸一化,乘以255將加噪后的圖像的像素值恢復 #cv.imshow("gasuss", out) noise = noise*255 return [noise,out]