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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
#!/usr/bin/env python3
"""
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
    
    # BraTS2023 模态
    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)  # (4, D, H, W)
    
    # 加载分割标签
    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]  # (D, H, W)
    
    # 转换为 (D, H, W) 格式,D为深度(切片数)
    # BraTS数据通常是 (H, W, D),需要转置
    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]  # (H, W)
        
        # 归一化到 0-255
        slice_2d = (slice_2d * 255).astype(np.uint8)
        
        # 转为RGB(SAM3需要RGB输入)
        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)
        
        # 保存为JPEG
        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]
    
    # 创建不同区域的mask
    for i in range(num_slices):
        slice_seg = seg[i]  # (H, W)
        
        # Whole Tumor (包含所有肿瘤区域)
        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
        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))
    
    # 获取该切片的肿瘤mask
    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]
    
    # 缩放bbox和center
    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]  # (H, W)
        
        # 转换为帧
        frames_dir, num_slices = convert_to_frames(
            data, output_dir, case_name, 
            modality_idx=modality_idx, 
            target_size=target_size
        )
        
        # 保存mask
        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))
    # ensure non-negative and all used
    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')

    # split file generation (case-level)
    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")

    # write split file (based on all available case dirs)
    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()