Download Code/divide_dataset.py from JasonXU-1998/ITF_pelvic: direct link, hf CLI and curl.
- Browser
- Download file 7.72 kB
-
https://huggingface.co/datasets/JasonXU-1998/ITF_pelvic/resolve/main/Code/divide_dataset.py
- Command line
-
hf download hf://datasets/JasonXU-1998/ITF_pelvic/Code/divide_dataset.py
-
curl -L -o divide_dataset.py https://huggingface.co/datasets/JasonXU-1998/ITF_pelvic/resolve/main/Code/divide_dataset.py
7.72 kB
| 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()) |