File size: 7,479 Bytes
c52fe89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#读取数据集,在../dataset/raw_data下按照数据集的完整排序,1.png,2.png,3.png,...保存

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)
    """
    # 将图像从Tensor转为Numpy数组
    img_np = image.cpu().numpy()
    img_np = np.transpose(img_np, (1, 2, 0))  # C x H x W -> H x W x C
    
    # 根据噪声类型添加噪声
    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
    
    # 将噪声图像从Numpy数组转回Tensor
    noisy_img = np.transpose(noisy_img, (2, 0, 1))  # H x W x C -> C x H x W
    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:
                # 转换为tensor
                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)
                # 转回numpy并保存
                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)