File size: 7,719 Bytes
71cf8b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import os
import json
import shutil
from pathlib import Path

def convert_to_nnunet_format(
    input_images_path, 
    input_labels_path, 
    output_path, 
    dataset_name="Dataset001_pelvic",
    train_ratio=0.8,
    test_ratio=0.2
):
    """
    将CT文件和标签转换为nnU-Net格式
    
    Args:
        input_images_path: CT文件路径 (路径A)
        input_labels_path: 标签文件路径 (路径B)
        output_path: 输出路径
        dataset_name: 数据集名称
        train_ratio: 训练集比例
        test_ratio: 测试集比例
    """
    
    # 创建输出目录结构
    dataset_path = Path(output_path) / dataset_name
    imagesTr_path = dataset_path / "imagesTr"
    labelsTr_path = dataset_path / "labelsTr"
    imagesTs_path = dataset_path / "imagesTs"
    
    # 创建目录
    imagesTr_path.mkdir(parents=True, exist_ok=True)
    labelsTr_path.mkdir(parents=True, exist_ok=True)
    imagesTs_path.mkdir(parents=True, exist_ok=True)
    
    # 获取所有.mha文件
    input_images = Path(input_images_path)
    input_labels = Path(input_labels_path)
    
    image_files = sorted(list(input_images.glob("*.mha")))
    print(f"找到 {len(image_files)} 个图像文件")
    
    if len(image_files) == 0:
        raise ValueError(f"在路径 {input_images_path} 中没有找到.mha文件")
    
    # 验证对应的标签文件是否存在
    valid_pairs = []
    for img_file in image_files:
        # 假设标签文件与图像文件同名
        label_file = input_labels / img_file.name
        if label_file.exists():
            valid_pairs.append((img_file, label_file))
        else:
            print(f"警告: 图像文件 {img_file.name} 没有对应的标签文件")
    
    print(f"找到 {len(valid_pairs)} 对有效的图像-标签文件")
    
    if len(valid_pairs) == 0:
        raise ValueError("没有找到有效的图像-标签文件对")
    
    # 计算训练集和测试集数量
    total_files = len(valid_pairs)
    num_train = int(total_files * train_ratio)
    num_test = total_files - num_train
    
    print(f"训练集: {num_train} 个文件")
    print(f"测试集: {num_test} 个文件")
    
    # 复制文件并重命名
    train_cases = []
    test_cases = []
    
    for i, (img_file, label_file) in enumerate(valid_pairs):
        # nnU-Net命名格式: case_identifier_0000.nii.gz
        case_id = f"{dataset_name.split('_')[1]}_{i:03d}"
        
        if i < num_train:
            # 训练集
            # 复制图像文件
            dst_img = imagesTr_path / f"{case_id}_0000.mha"
            shutil.copy2(img_file, dst_img)
            
            # 复制标签文件
            dst_label = labelsTr_path / f"{case_id}.mha"
            shutil.copy2(label_file, dst_label)
            
            train_cases.append(case_id)
            
        else:
            # 测试集
            dst_img = imagesTs_path / f"{case_id}_0000.mha"
            shutil.copy2(img_file, dst_img)
            
            test_cases.append(case_id)
    
    print(f"文件复制完成")
    print(f"训练集文件: {len(train_cases)} 个")
    print(f"测试集文件: {len(test_cases)} 个")
    
    # 创建dataset.json
    dataset_json = {
        "channel_names": {
            "0": "CT"
        },
        # "labels": {
        #     "background": 0,
        #     "middle": 1,
        #     "right": 2,
        #     "left": 3
        # },
        "labels": {
            "background": 0,
            "1": 1,
            "2": 2,
            "3": 3,
            "4": 4,
            "5": 5,
            "6": 6,
            "7": 7,
            "8": 8,
            "9": 9,
            "10": 10,
            "11": 11
        },
        "numTraining": len(train_cases),
        "file_ending": ".mha",
        "dataset_name": dataset_name,
        "reference": "Pelvic CT Dataset",
        "description": "Pelvic CT segmentation dataset",
        "tensorImageSize": "4D",
        "modality": {
            "0": "CT"
        },
        "dim": 3
    }
    
    # 如果你有多个标签类别,请修改labels字段,例如:
    # "labels": {
    #     "background": 0,
    #     "bone": 1,
    #     "muscle": 2,
    #     "organ": 3
    # }
    
    # 保存dataset.json
    json_path = dataset_path / "dataset.json"
    with open(json_path, 'w', encoding='utf-8') as f:
        json.dump(dataset_json, f, indent=4, ensure_ascii=False)
    
    print(f"dataset.json 已创建: {json_path}")
    
    # 打印最终目录结构
    print("\n创建的目录结构:")
    print(f"{dataset_path}/")
    print(f"├── dataset.json")
    print(f"├── imagesTr/ ({len(train_cases)} files)")
    print(f"├── imagesTs/ ({len(test_cases)} files)")
    print(f"└── labelsTr/ ({len(train_cases)} files)")
    
    return dataset_path

def main():
    # 直接定义路径参数
    # images_path = "/research/phd_y3/pelvic_project/Data/images"
    # labels_path = "/research/phd_y3/pelvic_project/Data/3_part_labels"
    # output_path = "/research/phd_y3/pelvic_project/Code/for_nnUNet/nnUNet_raw_data"
    # dataset_name = "Dataset001_pelvic_three_parts"
    
    # images_path = "/research/phd_y3/pelvic_project/Data/mid_sacrum_bbox_images"
    # labels_path = "/research/phd_y3/pelvic_project/Data/mid_sacrum_bbox_labels"
    # output_path = "/research/phd_y3/pelvic_project/Code/for_nnUNet/nnUNet_raw_data"
    # dataset_name = "Dataset002_mid_sacrum"
    
    # images_path = "/research/phd_y3/pelvic_project/Data/right_hip_bbox_images"
    # labels_path = "/research/phd_y3/pelvic_project/Data/right_hip_bbox_labels"
    # output_path = "/research/phd_y3/pelvic_project/Code/for_nnUNet/nnUNet_raw_data"
    # dataset_name = "Dataset003_right_hip"
    
    # images_path = "/research/phd_y3/pelvic_project/Data/left_hip_bbox_images"
    # labels_path = "/research/phd_y3/pelvic_project/Data/left_hip_bbox_labels"
    # output_path = "/research/phd_y3/pelvic_project/Code/for_nnUNet/nnUNet_raw_data"
    # dataset_name = "Dataset004_left_hip"
    
    images_path = "/research/phd_y3/pelvic_project/Data/images"
    labels_path = "/research/phd_y3/pelvic_project/Data/organ+3_part_label_fixed"
    output_path = "/research/phd_y3/pelvic_project/Code/for_nnUNet/nnUNet_raw_data"
    dataset_name = "Dataset005_organ_pelvic"
    
    train_ratio = 0.7
    test_ratio = 0.3
    
    print(f"开始处理数据集转换:")
    print(f"图像路径: {images_path}")
    print(f"标签路径: {labels_path}")
    print(f"输出路径: {output_path}")
    print(f"数据集名称: {dataset_name}")
    print(f"训练集比例: {train_ratio}")
    print(f"测试集比例: {test_ratio}")
    print("-" * 50)
    
    # 验证输入路径
    if not os.path.exists(images_path):
        print(f"❌ 图像路径不存在: {images_path}")
        return 1
    
    if not os.path.exists(labels_path):
        print(f"❌ 标签路径不存在: {labels_path}")
        return 1
    
    # 转换数据
    try:
        result_path = convert_to_nnunet_format(
            images_path, 
            labels_path, 
            output_path, 
            dataset_name,
            train_ratio,
            test_ratio
        )
        print(f"\n✅ 转换完成! 数据集保存在: {result_path}")
        print(f"\n下一步:")
        print(f"1. 设置环境变量: export nnUNet_raw_data_base='{Path(output_path).absolute()}'")
        print(f"2. 运行nnU-Net预处理: nnUNet_plan_and_preprocess -t {dataset_name.split('_')[0].replace('Dataset', '')}")
        
    except Exception as e:
        print(f"❌ 转换失败: {str(e)}")
        return 1
    
    return 0

if __name__ == "__main__":
    exit(main())