程序示例:
from torchvision import transforms from PIL import Image import torch def gaussian(img, mean, std): c, h, w = img.shape noise = torch.randn([c, h, w])*std + mean return noise img_jpg = Image.open('C:/Users/admin/Desktop/bird.jpg').convert('RGB') to_tensor = transforms.ToTensor() img_tensor = to_tensor(img_jpg) noise_tensor = gaussian(img_tensor, 0, 0.05) noise_img_tensor = img_tensor + noise_tensor for i in range(img_tensor.shape[0]): # min-max normalization noise_tensor[i] = (noise_tensor[i] - noise_tensor[i].min() ) / (noise_tensor[i].max() - noise_tensor[i].min()) noise_img_tensor[i] = (noise_img_tensor[i] - noise_img_tensor[i].min() ) / (noise_img_tensor[i].max() - noise_img_tensor[i].min()) to_PILimage = transforms.ToPILImage() noise = to_PILimage(noise_tensor) noise_img = to_PILimage(noise_img_tensor) noise.save('C:/Users/admin/Desktop/noise0.05.jpg') noise_img.save('C:/Users/admin/Desktop/noise_img0.05.jpg') print('Done.')
图像: