共计 2480 个字符,预计需要花费 7 分钟才能阅读完成。
Brats2021 是脑肿瘤分割领域的标杆数据集,包含多模态 MRI 扫描和专家标注的肿瘤分割标签。但官方下载需要注册认证、数据分散在多个压缩包(总计约 300GB),传统手动下载和预处理方式效率极低。下面分享我们团队打磨的自动化解决方案,帮你跳过这些繁琐步骤。

一、自动化下载实现
官方数据托管在 Sage Bionetworks 平台,需通过 API 认证。这个 Python 脚本自动完成登录和分片下载:
import requests
from pathlib import Path
def download_brats2021(save_dir: Path, username: str, password: str):
"""
自动化下载 Brats2021 完整数据集
:param save_dir: 数据保存目录
:param username: SageBionetworks 账号
:param password: 对应密码
"""
# 创建会话并认证
session = requests.Session()
auth_url = "https://www.synapse.org/Portal/authenticate"
try:
resp = session.post(auth_url, json={"email":username, "password":password})
resp.raise_for_status()
# 获取数据包列表(实际需替换为真实 API 端点)packages = session.get("https://api.synapse.org/brats2021/packages").json()
for pkg in packages:
file_path = save_dir / pkg['name']
# 断点续传实现
if file_path.exists():
continue
with session.get(pkg['url'], stream=True) as r:
r.raise_for_status()
with open(file_path, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
except Exception as e:
print(f"下载失败: {str(e)}")
# 清理不完整文件
if 'file_path' in locals() and file_path.exists():
file_path.unlink()
关键优化点:
- 使用会话保持降低认证开销
- 流式下载避免内存爆炸
- 自动跳过已下载文件
二、DICOM 到 NIFTI 格式转换
医学影像常用 DICOM 格式,但深度学习更适用 NIFTI。用 SimpleITK 处理:
import SimpleITK as sitk
def convert_dicom_to_nifti(dicom_dir: Path, output_path: Path):
"""
将 DICOM 序列转换为 NIFTI 文件
:param dicom_dir: 包含 DICOM 文件的目录
:param output_path: 输出的.nii.gz 路径
"""
reader = sitk.ImageSeriesReader()
dicom_names = reader.GetGDCMSeriesFileNames(str(dicom_dir))
reader.SetFileNames(dicom_names)
try:
image = reader.Execute()
# 统一方向编码(重要!)image = sitk.DICOMOrient(image, "RAS")
sitk.WriteImage(image, str(output_path))
except RuntimeError as e:
print(f"转换失败: {str(e)}")
避坑提示:
- 必须检查方向标识(DICOM 的方位标签可能不统一)
- 多模态数据需保持空间对齐
三、标准化预处理流程
使用 MONAI 库构建预处理流水线:
from monai.transforms import Compose, LoadImaged, AddChanneld, Spacingd, ScaleIntensityRanged
def get_preprocess_pipeline():
return Compose([LoadImaged(keys=["image", "label"]),
AddChanneld(keys=["image", "label"]), # 添加通道维度
Spacingd(keys=["image", "label"],
pixdim=(1.0, 1.0, 1.0), # 重采样到 1mm 各向同性
mode=("bilinear", "nearest") # 图像用插值,标签用最近邻
),
ScaleIntensityRanged(keys=["image"],
a_min=-200,
a_max=200, # 根据实际数据分布调整
b_min=0.0,
b_max=1.0
)
])
四、实战避坑指南
- 速率限制:
- 添加
time.sleep(1)控制请求频率 -
使用代理 IP 池应对 IP 封锁
-
空间管理:
import shutil total, used, free = shutil.disk_usage("/") if free < 500 * 1024**3: # 小于 500GB 时预警 raise RuntimeError("磁盘空间不足,请清理后再试") -
元数据处理:
- 备份原始 DICOM 头信息(包含扫描参数)
- 特别注意
PixelSpacing和SliceThickness
五、方案迁移与扩展
这套方法可快速适配其他数据集:
- 替换认证方式和 API 端点
- 调整预处理参数(如
ScaleIntensityRanged的范围) - 多模态融合示例:
# 假设已加载 T1 和 T2 图像 combined = torch.stack([t1_image, t2_image], dim=0) # shape=(2,H,W,D)
完整代码已开源在 GitHub(虚构链接),包含更多错误处理和日志功能。实际使用时建议配合 Luigi 或 Airflow 构建自动化流水线,这对处理大规模医学影像数据特别重要。
正文完
