Python 图像加噪
骊山道童 人气:0内容简介
展示如何给图像叠加不同等级的椒盐噪声和高斯噪声的代码,相应的叠加噪声的已编为对应的类,可实例化使用。以下主要展示自己编写的:
加噪声的代码(高斯噪声,椒盐噪声)
add_noise.py
#代码中的noisef为信号等级,例如我需要0.7的噪声,传入参数我传入的是1-0.7 from PIL import Image import numpy as np import random import torchvision.transforms as transforms norm_mean = (0.5, 0.5, 0.5) norm_std = (0.5, 0.5, 0.5) class AddPepperNoise(object): """增加椒盐噪声 Args: snr (float): Signal Noise Rate p (float): 概率值,依概率执行该操作 """ def __init__(self, snr, p=0.9): assert isinstance(snr, float) and (isinstance(p, float)) # 2020 07 26 or --> and self.snr = snr self.p = p def __call__(self, img): """ Args: img (PIL Image): PIL Image Returns: PIL Image: PIL image. """ if random.uniform(0, 1) < self.p: img_ = np.array(img).copy() h, w, c = img_.shape signal_pct = self.snr noise_pct = (1 - self.snr) mask = np.random.choice((0, 1, 2), size=(h, w, 1), p=[signal_pct, noise_pct/2., noise_pct/2.]) mask = np.repeat(mask, c, axis=2) img_[mask == 1] = 255 # 盐噪声 img_[mask == 2] = 0 # 椒噪声 return Image.fromarray(img_.astype('uint8')).convert('RGB') else: return img class Gaussian_noise(object): """增加高斯噪声 此函数用将产生的高斯噪声加到图片上 传入: img : 原图 mean : 均值 sigma : 标准差 返回: gaussian_out : 噪声处理后的图片 """ def __init__(self, mean, sigma): self.mean = mean self.sigma = sigma def __call__(self, img): """ Args: img (PIL Image): PIL Image Returns: PIL Image: PIL image. """ # 将图片灰度标准化 img_ = np.array(img).copy() img_ = img_ / 255.0 # 产生高斯 noise noise = np.random.normal(self.mean, self.sigma, img_.shape) # 将噪声和图片叠加 gaussian_out = img_ + noise # 将超过 1 的置 1,低于 0 的置 0 gaussian_out = np.clip(gaussian_out, 0, 1) # 将图片灰度范围的恢复为 0-255 gaussian_out = np.uint8(gaussian_out*255) # 将噪声范围搞为 0-255 # noise = np.uint8(noise*255) return Image.fromarray(gaussian_out).convert('RGB') def image_transform(noisef): """对训练集和测试集的图片作预处理转换 train_transform:加噪图 _train_transform:原图(不加噪) test_transform:测试图(不加噪) """ train_transform = transforms.Compose([ transforms.Resize((256, 256)), # 重设大小 #transforms.RandomCrop(32,padding=4), AddPepperNoise(noisef, p=0.9), #加椒盐噪声 #Gaussian_noise(0, noisef), # 加高斯噪声 transforms.ToTensor(), # 转换为张量 # transforms.Normalize(norm_mean,norm_std), ]) _train_transform = transforms.Compose([ transforms.Resize((256, 256)), #transforms.RandomCrop(32,padding=4), transforms.ToTensor(), # transforms.Normalize(norm_mean,norm_std), ]) test_transform = transforms.Compose([ transforms.Resize((256, 256)), #transforms.RandomCrop(32,padding=4), transforms.ToTensor(), # transforms.Normalize(norm_mean,norm_std), ]) return train_transform, _train_transform, test_transform
在pytorch中如何使用
# 图像变换和加噪声train_transform为加噪图,_train_transform为原图,test_transform为测试图 noisef为传入的噪声等级
train_transform,_train_transform,test_transform = image_transform(noisef)
training_data=FabricDataset_file(data_dir=train_dir,transform=train_transform)
_training_data=FabricDataset_file(data_dir=_train_dir,transform=_train_transform)
testing_data=FabricDataset_file(data_dir=test_dir,transform=test_transform)
补充
图像添加随机噪声
随机噪声就是通过随机函数在图像上随机地添加噪声点
def random_noise(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
img_noise = random_noise("colorful_lena.jpg",3000) cv2.imshow('random_noise',img_noise) cv2.waitKey(0)
加载全部内容