| | |
| |
|
| | import os |
| | import yaml |
| | import numpy as np |
| | import torch |
| | import torchvision |
| | import torchvision.transforms as transforms |
| | from PIL import Image |
| | from tqdm import tqdm |
| | import sys |
| |
|
| | def unpickle(file): |
| | """读取CIFAR-10数据文件""" |
| | import pickle |
| | with open(file, 'rb') as fo: |
| | dict = pickle.load(fo, encoding='bytes') |
| | return dict |
| | |
| | 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 save_images_from_cifar10_with_noisy(dataset_path, save_dir): |
| | """从CIFAR-10数据集中保存图像,对指定索引添加噪声 |
| | |
| | Args: |
| | dataset_path: CIFAR-10数据集路径 |
| | save_dir: 图像保存路径 |
| | """ |
| | |
| | os.makedirs(save_dir, exist_ok=True) |
| | |
| | |
| | noise_index_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'dataset', 'noise_index.npy') |
| | if os.path.exists(noise_index_path): |
| | noise_indices = np.load(noise_index_path) |
| | print(f"已加载 {len(noise_indices)} 个噪声样本索引") |
| | else: |
| | noise_indices = [] |
| | print("未找到噪声索引文件,将不添加噪声") |
| | |
| | |
| | config_path = './train.yaml' |
| | with open(config_path, 'r') as f: |
| | config = yaml.safe_load(f) |
| | |
| | |
| | noise_levels = config.get('noise_levels', {}) |
| | gaussian_level = noise_levels.get('gaussian', [0.3]) |
| | salt_pepper_level = noise_levels.get('salt_pepper', [0.1]) |
| | poisson_level = noise_levels.get('poisson', [1.0])[0] |
| | |
| | |
| | train_data = [] |
| | train_labels = [] |
| | |
| | |
| | for i in range(1, 6): |
| | batch_file = os.path.join(dataset_path, f'data_batch_{i}') |
| | if os.path.exists(batch_file): |
| | print(f"读取训练批次 {i}") |
| | batch = unpickle(batch_file) |
| | train_data.append(batch[b'data']) |
| | train_labels.extend(batch[b'labels']) |
| | |
| | |
| | if train_data: |
| | train_data = np.vstack(train_data) |
| | train_data = train_data.reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1) |
| | |
| | |
| | test_file = os.path.join(dataset_path, 'test_batch') |
| | if os.path.exists(test_file): |
| | print("读取测试数据") |
| | test_batch = unpickle(test_file) |
| | test_data = test_batch[b'data'] |
| | test_labels = test_batch[b'labels'] |
| | test_data = test_data.reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1) |
| | else: |
| | test_data = [] |
| | test_labels = [] |
| | |
| | |
| | all_data = np.concatenate([train_data, test_data]) if len(test_data) > 0 and len(train_data) > 0 else (train_data if len(train_data) > 0 else test_data) |
| | all_labels = train_labels + test_labels if len(test_labels) > 0 and len(train_labels) > 0 else (train_labels if len(train_labels) > 0 else test_labels) |
| | |
| | |
| | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
| | |
| | |
| | print(f"保存 {len(all_data)} 张图像...") |
| | |
| | for i, (img, label) in enumerate(tqdm(zip(all_data, all_labels), total=len(all_data))): |
| | |
| | if i in noise_indices: |
| | |
| | noise_type = None |
| | level = None |
| | |
| | if label == 2: |
| | noise_type = 1 |
| | level = gaussian_level[1] |
| | elif label == 3: |
| | noise_type = 1 |
| | level = gaussian_level[0] |
| | elif label == 4: |
| | noise_type = 2 |
| | level = salt_pepper_level[1] |
| | elif label == 5: |
| | noise_type = 2 |
| | level = salt_pepper_level[0] |
| | elif label == 6: |
| | noise_type = 3 |
| | level = poisson_level |
| | elif label == 7: |
| | noise_type = 3 |
| | level = poisson_level |
| | |
| | |
| | if noise_type is not None and level is not None: |
| | |
| | img_tensor = torch.from_numpy(img.astype(np.float32) / 255.0).permute(2, 0, 1).to(device) |
| | |
| | noisy_tensor = add_noise_for_preview(img_tensor, noise_type, level) |
| | |
| | noisy_img = (noisy_tensor.permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8) |
| | noisy_pil = Image.fromarray(noisy_img) |
| | noisy_pil.save(os.path.join(save_dir, f"{i}.png")) |
| | else: |
| | |
| | img_pil = Image.fromarray(img) |
| | img_pil.save(os.path.join(save_dir, f"{i}.png")) |
| | else: |
| | |
| | img_pil = Image.fromarray(img) |
| | img_pil.save(os.path.join(save_dir, f"{i}.png")) |
| | |
| | print(f"完成! {len(all_data)} 张图像已保存到 {save_dir}, 其中 {len(noise_indices)} 张添加了噪声") |
| |
|
| | if __name__ == "__main__": |
| | |
| | dataset_path = "../dataset/cifar-10-batches-py" |
| | save_dir = "../dataset/raw_data" |
| | |
| | |
| | if not os.path.exists(dataset_path): |
| | print("数据集不存在,正在下载...") |
| | os.makedirs("../dataset", exist_ok=True) |
| | transform = transforms.Compose([transforms.ToTensor()]) |
| | trainset = torchvision.datasets.CIFAR10(root="../dataset", train=True, download=True, transform=transform) |
| | |
| | |
| | save_images_from_cifar10_with_noisy(dataset_path, save_dir) |