|
|
|
|
|
""" |
|
|
BraTS2023 数据预处理脚本 |
|
|
将3D NIfTI医学数据转换为SAM3可处理的帧序列格式 |
|
|
""" |
|
|
|
|
|
import os |
|
|
import argparse |
|
|
import numpy as np |
|
|
import nibabel as nib |
|
|
from pathlib import Path |
|
|
from tqdm import tqdm |
|
|
import cv2 |
|
|
from PIL import Image |
|
|
import json |
|
|
import multiprocessing as mp |
|
|
|
|
|
|
|
|
def normalize_intensity(volume, low_percentile=0.5, high_percentile=99.5): |
|
|
""" |
|
|
对体积数据进行强度归一化 |
|
|
""" |
|
|
low = np.percentile(volume[volume > 0], low_percentile) |
|
|
high = np.percentile(volume[volume > 0], high_percentile) |
|
|
volume = np.clip(volume, low, high) |
|
|
volume = (volume - low) / (high - low + 1e-8) |
|
|
return volume |
|
|
|
|
|
|
|
|
def load_brats_case(case_dir): |
|
|
""" |
|
|
加载单个BraTS病例的所有模态 |
|
|
|
|
|
Args: |
|
|
case_dir: 病例文件夹路径 |
|
|
|
|
|
Returns: |
|
|
data: 形状为 (4, D, H, W) 的numpy数组,4个模态 |
|
|
seg: 形状为 (D, H, W) 的分割标签 |
|
|
affine: NIfTI仿射矩阵 |
|
|
""" |
|
|
case_dir = Path(case_dir) |
|
|
case_name = case_dir.name |
|
|
|
|
|
|
|
|
modalities = ['t1c', 't1n', 't2f', 't2w'] |
|
|
|
|
|
data = [] |
|
|
affine = None |
|
|
|
|
|
for mod in modalities: |
|
|
|
|
|
possible_names = [ |
|
|
f"{mod}.nii.gz", |
|
|
f"{case_name}-{mod}.nii.gz", |
|
|
f"{case_name}_{mod}.nii.gz" |
|
|
] |
|
|
|
|
|
nii_path = None |
|
|
for name in possible_names: |
|
|
p = case_dir / name |
|
|
if p.exists(): |
|
|
nii_path = p |
|
|
break |
|
|
|
|
|
if nii_path is None: |
|
|
raise FileNotFoundError(f"Cannot find {mod} file in {case_dir}") |
|
|
|
|
|
nii = nib.load(str(nii_path)) |
|
|
if affine is None: |
|
|
affine = nii.affine |
|
|
|
|
|
volume = nii.get_fdata().astype(np.float32) |
|
|
volume = normalize_intensity(volume) |
|
|
data.append(volume) |
|
|
|
|
|
data = np.stack(data, axis=0) |
|
|
|
|
|
|
|
|
seg_names = [ |
|
|
"seg.nii.gz", |
|
|
f"{case_name}-seg.nii.gz", |
|
|
f"{case_name}_seg.nii.gz" |
|
|
] |
|
|
|
|
|
seg = None |
|
|
for name in seg_names: |
|
|
p = case_dir / name |
|
|
if p.exists(): |
|
|
seg_nii = nib.load(str(p)) |
|
|
seg = seg_nii.get_fdata().astype(np.int32) |
|
|
break |
|
|
|
|
|
return data, seg, affine |
|
|
|
|
|
|
|
|
def convert_to_frames(data, output_dir, case_name, modality_idx=0, target_size=(512, 512)): |
|
|
""" |
|
|
将3D数据转换为帧序列(JPEG图像) |
|
|
|
|
|
Args: |
|
|
data: 形状为 (4, D, H, W) 的数据 |
|
|
output_dir: 输出目录 |
|
|
case_name: 病例名称 |
|
|
modality_idx: 使用哪个模态 (0=t1c, 1=t1n, 2=t2f, 3=t2w) |
|
|
target_size: 目标图像大小 |
|
|
""" |
|
|
frames_dir = Path(output_dir) / case_name / "frames" |
|
|
frames_dir.mkdir(parents=True, exist_ok=True) |
|
|
|
|
|
|
|
|
volume = data[modality_idx] |
|
|
|
|
|
|
|
|
|
|
|
if volume.shape[0] > volume.shape[2]: |
|
|
volume = np.transpose(volume, (2, 0, 1)) |
|
|
|
|
|
num_slices = volume.shape[0] |
|
|
|
|
|
for i in range(num_slices): |
|
|
slice_2d = volume[i] |
|
|
|
|
|
|
|
|
slice_2d = (slice_2d * 255).astype(np.uint8) |
|
|
|
|
|
|
|
|
slice_rgb = np.stack([slice_2d, slice_2d, slice_2d], axis=-1) |
|
|
|
|
|
|
|
|
if target_size is not None: |
|
|
slice_rgb = cv2.resize(slice_rgb, target_size, interpolation=cv2.INTER_LINEAR) |
|
|
|
|
|
|
|
|
frame_path = frames_dir / f"{i:05d}.jpg" |
|
|
Image.fromarray(slice_rgb).save(str(frame_path), quality=95) |
|
|
|
|
|
return frames_dir, num_slices |
|
|
|
|
|
|
|
|
def save_segmentation_masks(seg, output_dir, case_name, target_size=(512, 512)): |
|
|
""" |
|
|
保存分割标签为帧序列 |
|
|
|
|
|
BraTS标签: |
|
|
0: 背景 |
|
|
1: NCR (Necrotic Core) - 坏死核心 |
|
|
2: ED (Edema) - 水肿 |
|
|
3: ET (Enhancing Tumor) - 强化肿瘤 |
|
|
|
|
|
合并为: |
|
|
- Whole Tumor (WT): 1+2+3 |
|
|
- Tumor Core (TC): 1+3 |
|
|
- Enhancing Tumor (ET): 3 |
|
|
""" |
|
|
if seg is None: |
|
|
return None |
|
|
|
|
|
masks_dir = Path(output_dir) / case_name / "masks" |
|
|
masks_dir.mkdir(parents=True, exist_ok=True) |
|
|
|
|
|
|
|
|
if seg.shape[0] > seg.shape[2]: |
|
|
seg = np.transpose(seg, (2, 0, 1)) |
|
|
|
|
|
num_slices = seg.shape[0] |
|
|
|
|
|
|
|
|
for i in range(num_slices): |
|
|
slice_seg = seg[i] |
|
|
|
|
|
|
|
|
wt_mask = ((slice_seg == 1) | (slice_seg == 2) | (slice_seg == 3)).astype(np.uint8) * 255 |
|
|
|
|
|
|
|
|
if target_size is not None: |
|
|
wt_mask = cv2.resize(wt_mask, target_size, interpolation=cv2.INTER_NEAREST) |
|
|
|
|
|
|
|
|
mask_path = masks_dir / f"{i:05d}.png" |
|
|
Image.fromarray(wt_mask).save(str(mask_path)) |
|
|
|
|
|
return masks_dir |
|
|
|
|
|
|
|
|
def get_tumor_bbox_and_center(seg, slice_idx=None): |
|
|
""" |
|
|
获取肿瘤的边界框和中心点 |
|
|
|
|
|
Args: |
|
|
seg: 分割标签 (D, H, W) |
|
|
slice_idx: 指定切片索引,如果为None则找最大肿瘤面积的切片 |
|
|
|
|
|
Returns: |
|
|
slice_idx: 选中的切片索引 |
|
|
bbox: (x_min, y_min, x_max, y_max) |
|
|
center: (x, y) |
|
|
""" |
|
|
if seg is None: |
|
|
return None, None, None |
|
|
|
|
|
|
|
|
if seg.shape[0] > seg.shape[2]: |
|
|
seg = np.transpose(seg, (2, 0, 1)) |
|
|
|
|
|
|
|
|
tumor_mask = (seg > 0) |
|
|
|
|
|
|
|
|
if slice_idx is None: |
|
|
tumor_areas = tumor_mask.sum(axis=(1, 2)) |
|
|
slice_idx = int(np.argmax(tumor_areas)) |
|
|
|
|
|
|
|
|
slice_tumor = tumor_mask[slice_idx] |
|
|
|
|
|
if slice_tumor.sum() == 0: |
|
|
return slice_idx, None, None |
|
|
|
|
|
|
|
|
rows = np.any(slice_tumor, axis=1) |
|
|
cols = np.any(slice_tumor, axis=0) |
|
|
y_min, y_max = np.where(rows)[0][[0, -1]] |
|
|
x_min, x_max = np.where(cols)[0][[0, -1]] |
|
|
|
|
|
bbox = (int(x_min), int(y_min), int(x_max), int(y_max)) |
|
|
center = ((x_min + x_max) // 2, (y_min + y_max) // 2) |
|
|
|
|
|
return slice_idx, bbox, center |
|
|
|
|
|
|
|
|
def save_prompt_info(output_dir, case_name, slice_idx, bbox, center, |
|
|
original_size, target_size=(512, 512)): |
|
|
""" |
|
|
保存提示信息(用于SAM3推理) |
|
|
""" |
|
|
info_dir = Path(output_dir) / case_name |
|
|
info_dir.mkdir(parents=True, exist_ok=True) |
|
|
|
|
|
|
|
|
scale_x = target_size[0] / original_size[1] |
|
|
scale_y = target_size[1] / original_size[0] |
|
|
|
|
|
|
|
|
if bbox is not None: |
|
|
scaled_bbox = ( |
|
|
int(bbox[0] * scale_x), |
|
|
int(bbox[1] * scale_y), |
|
|
int(bbox[2] * scale_x), |
|
|
int(bbox[3] * scale_y) |
|
|
) |
|
|
else: |
|
|
scaled_bbox = None |
|
|
|
|
|
if center is not None: |
|
|
scaled_center = ( |
|
|
int(center[0] * scale_x), |
|
|
int(center[1] * scale_y) |
|
|
) |
|
|
else: |
|
|
scaled_center = None |
|
|
|
|
|
info = { |
|
|
'slice_idx': slice_idx, |
|
|
'bbox': scaled_bbox, |
|
|
'center': scaled_center, |
|
|
'original_size': original_size, |
|
|
'target_size': target_size, |
|
|
'scale': (scale_x, scale_y) |
|
|
} |
|
|
|
|
|
np.save(str(info_dir / 'prompt_info.npy'), info, allow_pickle=True) |
|
|
|
|
|
return info |
|
|
|
|
|
|
|
|
def process_single_case(case_dir, output_dir, modality_idx=0, target_size=(512, 512)): |
|
|
""" |
|
|
处理单个病例 |
|
|
""" |
|
|
case_name = Path(case_dir).name |
|
|
print(f"Processing {case_name}...") |
|
|
|
|
|
try: |
|
|
|
|
|
data, seg, affine = load_brats_case(case_dir) |
|
|
original_size = data.shape[2:4] |
|
|
|
|
|
|
|
|
frames_dir, num_slices = convert_to_frames( |
|
|
data, output_dir, case_name, |
|
|
modality_idx=modality_idx, |
|
|
target_size=target_size |
|
|
) |
|
|
|
|
|
|
|
|
masks_dir = save_segmentation_masks(seg, output_dir, case_name, target_size=target_size) |
|
|
|
|
|
|
|
|
slice_idx, bbox, center = get_tumor_bbox_and_center(seg) |
|
|
|
|
|
|
|
|
prompt_info = save_prompt_info( |
|
|
output_dir, case_name, slice_idx, bbox, center, |
|
|
original_size, target_size |
|
|
) |
|
|
|
|
|
print(f" - {num_slices} slices processed") |
|
|
print(f" - Tumor center slice: {slice_idx}") |
|
|
if bbox: |
|
|
print(f" - BBox: {prompt_info['bbox']}") |
|
|
print(f" - Center: {prompt_info['center']}") |
|
|
|
|
|
return True |
|
|
|
|
|
except Exception as e: |
|
|
print(f"Error processing {case_name}: {e}") |
|
|
import traceback |
|
|
traceback.print_exc() |
|
|
return False |
|
|
|
|
|
|
|
|
def _make_splits(case_names, train_ratio: float, val_ratio: float, test_ratio: float, seed: int): |
|
|
"""Deterministic case-level split into train/val/test.""" |
|
|
if not (0 < train_ratio < 1) or not (0 <= val_ratio < 1) or not (0 <= test_ratio < 1): |
|
|
raise ValueError("ratios must be in [0,1) and train_ratio in (0,1)") |
|
|
if abs((train_ratio + val_ratio + test_ratio) - 1.0) > 1e-6: |
|
|
raise ValueError(f"train/val/test ratios must sum to 1.0, got {train_ratio+val_ratio+test_ratio:.6f}") |
|
|
|
|
|
case_names = list(case_names) |
|
|
rng = np.random.RandomState(seed) |
|
|
rng.shuffle(case_names) |
|
|
|
|
|
n = len(case_names) |
|
|
n_train = int(round(n * train_ratio)) |
|
|
n_val = int(round(n * val_ratio)) |
|
|
|
|
|
n_train = min(max(n_train, 0), n) |
|
|
n_val = min(max(n_val, 0), n - n_train) |
|
|
n_test = n - n_train - n_val |
|
|
|
|
|
train = case_names[:n_train] |
|
|
val = case_names[n_train : n_train + n_val] |
|
|
test = case_names[n_train + n_val :] |
|
|
return {"train": train, "val": val, "test": test} |
|
|
|
|
|
|
|
|
def _already_processed(output_dir: Path, case_name: str) -> bool: |
|
|
"""Heuristic for resuming: prompt_info.npy exists AND frames/masks dirs exist.""" |
|
|
case_dir = output_dir / case_name |
|
|
if not (case_dir / "prompt_info.npy").exists(): |
|
|
return False |
|
|
if not (case_dir / "frames").is_dir(): |
|
|
return False |
|
|
if not (case_dir / "masks").is_dir(): |
|
|
return False |
|
|
return True |
|
|
|
|
|
|
|
|
def _worker_process_case(args): |
|
|
case_dir, output_dir, modality_idx, target_size, skip_existing = args |
|
|
case_name = Path(case_dir).name |
|
|
output_dir = Path(output_dir) |
|
|
if skip_existing and _already_processed(output_dir, case_name): |
|
|
return case_name, True, "skipped" |
|
|
ok = process_single_case(case_dir, output_dir, modality_idx=modality_idx, target_size=target_size) |
|
|
return case_name, ok, "processed" if ok else "failed" |
|
|
|
|
|
|
|
|
def main(): |
|
|
parser = argparse.ArgumentParser(description='Preprocess BraTS data for SAM3') |
|
|
parser.add_argument('--input_dir', type=str, required=True, |
|
|
help='Input directory containing BraTS cases') |
|
|
parser.add_argument('--output_dir', type=str, required=True, |
|
|
help='Output directory for processed data') |
|
|
parser.add_argument('--modality', type=int, default=0, |
|
|
help='Modality index: 0=t1c, 1=t1n, 2=t2f, 3=t2w') |
|
|
parser.add_argument('--target_size', type=int, nargs=2, default=[512, 512], |
|
|
help='Target image size (width height)') |
|
|
parser.add_argument('--num_cases', type=int, default=None, |
|
|
help='Number of cases to process (None for all)') |
|
|
parser.add_argument('--num_processes', type=int, default=1, |
|
|
help='Number of parallel worker processes for preprocessing') |
|
|
parser.add_argument('--skip_existing', action='store_true', |
|
|
help='Skip cases that already have frames/masks/prompt_info.npy in output_dir') |
|
|
|
|
|
|
|
|
parser.add_argument('--write_splits', action='store_true', |
|
|
help='Write train/val/test split json to output_dir/splits.json') |
|
|
parser.add_argument('--train_ratio', type=float, default=0.7) |
|
|
parser.add_argument('--val_ratio', type=float, default=0.1) |
|
|
parser.add_argument('--test_ratio', type=float, default=0.2) |
|
|
parser.add_argument('--seed', type=int, default=42) |
|
|
|
|
|
args = parser.parse_args() |
|
|
|
|
|
input_dir = Path(args.input_dir) |
|
|
output_dir = Path(args.output_dir) |
|
|
output_dir.mkdir(parents=True, exist_ok=True) |
|
|
|
|
|
|
|
|
case_dirs = sorted([d for d in input_dir.iterdir() if d.is_dir()]) |
|
|
|
|
|
if args.num_cases is not None: |
|
|
case_dirs = case_dirs[:args.num_cases] |
|
|
|
|
|
print(f"Found {len(case_dirs)} cases to process") |
|
|
|
|
|
|
|
|
if args.write_splits: |
|
|
splits = _make_splits( |
|
|
[Path(d).name for d in case_dirs], |
|
|
train_ratio=args.train_ratio, |
|
|
val_ratio=args.val_ratio, |
|
|
test_ratio=args.test_ratio, |
|
|
seed=args.seed, |
|
|
) |
|
|
split_path = output_dir / "splits.json" |
|
|
with open(split_path, "w") as f: |
|
|
json.dump( |
|
|
{ |
|
|
"seed": args.seed, |
|
|
"train_ratio": args.train_ratio, |
|
|
"val_ratio": args.val_ratio, |
|
|
"test_ratio": args.test_ratio, |
|
|
"splits": splits, |
|
|
}, |
|
|
f, |
|
|
indent=2, |
|
|
) |
|
|
print( |
|
|
f"Wrote splits to {split_path} " |
|
|
f"(train={len(splits['train'])}, val={len(splits['val'])}, test={len(splits['test'])})" |
|
|
) |
|
|
|
|
|
success_count = 0 |
|
|
target_size = tuple(args.target_size) |
|
|
|
|
|
if args.num_processes <= 1: |
|
|
for case_dir in tqdm(case_dirs, desc="Processing cases"): |
|
|
case_name = Path(case_dir).name |
|
|
if args.skip_existing and _already_processed(output_dir, case_name): |
|
|
continue |
|
|
if process_single_case(case_dir, output_dir, modality_idx=args.modality, target_size=target_size): |
|
|
success_count += 1 |
|
|
else: |
|
|
work = [ |
|
|
(str(case_dir), str(output_dir), int(args.modality), target_size, bool(args.skip_existing)) |
|
|
for case_dir in case_dirs |
|
|
] |
|
|
with mp.get_context("spawn").Pool(processes=int(args.num_processes)) as pool: |
|
|
for case_name, ok, status in tqdm( |
|
|
pool.imap_unordered(_worker_process_case, work), |
|
|
total=len(work), |
|
|
desc="Processing cases (mp)", |
|
|
): |
|
|
if ok and status != "skipped": |
|
|
success_count += 1 |
|
|
|
|
|
print(f"\nProcessed {success_count}/{len(case_dirs)} cases successfully") |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |
|
|
|