| |
| |
|
|
| """ |
| 噪声效果预览脚本:展示不同类型和强度的噪声对图像的影响 |
| """ |
|
|
| import os |
| import torch |
| import numpy as np |
| import matplotlib.pyplot as plt |
| import torchvision |
| import torchvision.transforms as transforms |
| import random |
|
|
| def add_noise_for_preview(image, noise_type, level): |
| """向图像添加不同类型的噪声的预览 |
| |
| Args: |
| image: 输入图像 (Tensor: C x H x W),范围[0,1] |
| noise_type: 噪声类型 (int, 1-3) |
| level: 噪声强度 (float) |
| |
| Returns: |
| noisy_image: 添加噪声后的图像 (Tensor: C x H x W) |
| """ |
| |
| img_np = image.cpu().numpy() |
| img_np = np.transpose(img_np, (1, 2, 0)) |
| |
| |
| if noise_type == 1: |
| noise = np.random.normal(0, level, img_np.shape) |
| noisy_img = img_np + noise |
| noisy_img = np.clip(noisy_img, 0, 1) |
| |
| elif noise_type == 2: |
| |
| noisy_img = img_np.copy() |
| mask = np.random.random(img_np.shape[:2]) |
| |
| noisy_img[mask < level/2] = 0 |
| |
| noisy_img[mask > 1 - level/2] = 1 |
| |
| elif noise_type == 3: |
| |
| lam = np.maximum(img_np * 10.0, 0.0001) |
| noisy_img = np.random.poisson(lam) / 10.0 |
| noisy_img = np.clip(noisy_img, 0, 1) |
| |
| else: |
| noisy_img = img_np |
| |
| |
| noisy_img = np.transpose(noisy_img, (2, 0, 1)) |
| noisy_tensor = torch.from_numpy(noisy_img.astype(np.float32)) |
| return noisy_tensor |
|
|
| def preview_noise_effects(num_samples=5, save_dir='../results'): |
| """展示不同类型和强度噪声的对比效果 |
| |
| Args: |
| num_samples: 要展示的样本数量 |
| save_dir: 保存结果的目录 |
| """ |
| |
| os.makedirs(save_dir, exist_ok=True) |
| |
| |
| transform = transforms.Compose([transforms.ToTensor()]) |
| testset = torchvision.datasets.CIFAR10(root='../dataset', train=False, download=True, transform=transform) |
| |
| |
| indices = random.sample(range(len(testset)), num_samples) |
| |
| |
| noise_configs = [ |
| {"name": "高斯噪声(强)", "type": 1, "level": 0.2}, |
| {"name": "高斯噪声(弱)", "type": 1, "level": 0.1}, |
| {"name": "椒盐噪声(强)", "type": 2, "level": 0.15}, |
| {"name": "椒盐噪声(弱)", "type": 2, "level": 0.05}, |
| {"name": "泊松噪声(强)", "type": 3, "level": 1.0}, |
| {"name": "泊松噪声(弱)", "type": 3, "level": 0.5} |
| ] |
| |
| |
| classes = ('飞机', '汽车', '鸟', '猫', '鹿', '狗', '青蛙', '马', '船', '卡车') |
| |
| |
| for i, idx in enumerate(indices): |
| |
| img, label = testset[idx] |
| |
| |
| fig, axes = plt.subplots(1, len(noise_configs) + 1, figsize=(18, 3)) |
| plt.subplots_adjust(wspace=0.3) |
| |
| |
| img_np = img.permute(1, 2, 0).cpu().numpy() |
| axes[0].imshow(img_np) |
| axes[0].set_title(f"原始图像\n类别: {classes[label]}") |
| axes[0].axis('off') |
| |
| |
| for j, noise_config in enumerate(noise_configs): |
| noisy_img = add_noise_for_preview(img, noise_config["type"], noise_config["level"]) |
| noisy_img_np = noisy_img.permute(1, 2, 0).cpu().numpy() |
| axes[j+1].imshow(np.clip(noisy_img_np, 0, 1)) |
| axes[j+1].set_title(noise_config["name"]) |
| axes[j+1].axis('off') |
| |
| |
| plt.tight_layout() |
| plt.savefig(os.path.join(save_dir, f'noise_preview_{i+1}.png'), dpi=150) |
| plt.close() |
| |
| print(f"噪声对比预览已保存到 {save_dir} 目录") |
|
|
| if __name__ == "__main__": |
| |
| preview_noise_effects(num_samples=10, save_dir='.') |
|
|