| 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) |
| |
| |
| 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): |
| |
| 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 = { |
| "channel_names": { |
| "0": "CT" |
| }, |
| |
| |
| |
| |
| |
| |
| "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 |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| 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/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()) |