File size: 22,681 Bytes
34a4bcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
#!/usr/bin/env python3
"""
BraTS2023 数据集类 - 用于SAM3训练
将3D医学数据转换为SAM3可处理的视频格式
"""

import os
import random
import numpy as np
import torch
from torch.utils.data import Dataset
import nibabel as nib
from pathlib import Path
from PIL import Image
import cv2
import json
from typing import Optional, List, Dict, Tuple, Any


def normalize_intensity(volume, low_percentile=0.5, high_percentile=99.5):
    """对体积数据进行强度归一化"""
    mask = volume > 0
    if mask.sum() == 0:
        return volume
    low = np.percentile(volume[mask], low_percentile)
    high = np.percentile(volume[mask], high_percentile)
    volume = np.clip(volume, low, high)
    volume = (volume - low) / (high - low + 1e-8)
    return volume


class BraTSVideoDataset(Dataset):
    """
    BraTS数据集 - 将3D医学数据作为视频序列处理
    
    每个3D体积的切片作为视频帧,支持SAM3视频训练
    """
    
    def __init__(
        self,
        data_root: str,
        split: str = 'train',
        modality: int = 0,  # 0=t1c, 1=t1n, 2=t2f, 3=t2w
        target_size: Tuple[int, int] = (512, 512),
        num_frames: int = 8,  # 每个视频样本的帧数
        frame_stride: int = 1,  # 帧间隔
        augment: bool = True,
        train_ratio: float = 0.9,
        val_ratio: float = 0.1,
        test_ratio: float = 0.0,
        seed: int = 42,
        split_json: Optional[str] = None,
        normalize_mean: Tuple[float, ...] = (0.5, 0.5, 0.5),
        normalize_std: Tuple[float, ...] = (0.5, 0.5, 0.5),
    ):
        """
        Args:
            data_root: BraTS数据根目录
            split: 'train' 或 'val'
            modality: 使用的模态索引 (0=t1c, 1=t1n, 2=t2f, 3=t2w)
            target_size: 目标图像大小
            num_frames: 每个训练样本的帧数
            frame_stride: 帧采样间隔
            augment: 是否进行数据增强
            train_ratio: 训练集比例
            seed: 随机种子
        """
        super().__init__()
        
        self.data_root = Path(data_root)
        self.split = split
        self.modality = modality
        self.modality_names = ['t1c', 't1n', 't2f', 't2w']
        self.target_size = target_size
        self.num_frames = num_frames
        self.frame_stride = frame_stride
        self.augment = augment and (split == 'train')
        self.normalize_mean = normalize_mean
        self.normalize_std = normalize_std
        
        # 获取所有病例(case-level)
        all_cases = sorted([d for d in self.data_root.iterdir() if d.is_dir()])

        def _validate_ratios(tr, vr, ter):
            s = float(tr) + float(vr) + float(ter)
            if abs(s - 1.0) > 1e-6:
                raise ValueError(f"train/val/test ratios must sum to 1.0, got {s}")

        def _split_by_ratio(case_list: List[Path], tr: float, vr: float, ter: float, sd: int):
            _validate_ratios(tr, vr, ter)
            case_list = list(case_list)
            rng = random.Random(sd)
            rng.shuffle(case_list)
            n = len(case_list)
            n_train = int(round(n * tr))
            n_val = int(round(n * vr))
            n_train = min(max(n_train, 0), n)
            n_val = min(max(n_val, 0), n - n_train)
            train = case_list[:n_train]
            val = case_list[n_train : n_train + n_val]
            test = case_list[n_train + n_val :]
            return {"train": train, "val": val, "test": test}

        def _split_by_json(case_list: List[Path], split_file: str):
            with open(split_file, "r") as f:
                cfg = json.load(f)
            splits = cfg.get("splits", cfg)
            # support either {"train":[...],...} or {"splits":{"train":[...],...}}
            wanted = splits.get(self.split)
            if wanted is None:
                raise KeyError(f"split '{self.split}' not found in split json: {split_file}")
            wanted = set(wanted)
            return [c for c in case_list if c.name in wanted]

        if split_json:
            self.cases = _split_by_json(all_cases, split_json)
        else:
            parts = _split_by_ratio(all_cases, train_ratio, val_ratio, test_ratio, seed)
            if split not in parts:
                raise ValueError(f"split must be one of train/val/test, got: {split}")
            self.cases = parts[split]
        
        print(f"BraTS {split} set: {len(self.cases)} cases")
        
        # 预先加载所有数据的元信息
        self.case_info = self._preload_case_info()
    
    def _preload_case_info(self) -> List[Dict]:
        """预加载病例信息"""
        case_info = []
        for case_dir in self.cases:
            case_name = case_dir.name
            
            # 检查文件是否存在
            mod_name = self.modality_names[self.modality]
            possible_paths = [
                case_dir / f"{mod_name}.nii.gz",
                case_dir / f"{case_name}-{mod_name}.nii.gz",
            ]
            
            mod_path = None
            for p in possible_paths:
                if p.exists():
                    mod_path = p
                    break
            
            if mod_path is None:
                continue
            
            # 检查分割标签
            seg_paths = [
                case_dir / "seg.nii.gz",
                case_dir / f"{case_name}-seg.nii.gz",
            ]
            
            seg_path = None
            for p in seg_paths:
                if p.exists():
                    seg_path = p
                    break
            
            if seg_path is None:
                continue
            
            case_info.append({
                'case_name': case_name,
                'mod_path': str(mod_path),
                'seg_path': str(seg_path),
            })
        
        return case_info
    
    def __len__(self) -> int:
        return len(self.case_info)
    
    def _load_volume(self, path: str) -> np.ndarray:
        """加载NIfTI体积数据"""
        nii = nib.load(path)
        volume = nii.get_fdata().astype(np.float32)
        return volume
    
    def _get_tumor_slices(self, seg: np.ndarray) -> List[int]:
        """获取包含肿瘤的切片索引"""
        # 转置使得切片在第一维
        if seg.shape[0] > seg.shape[2]:
            seg = np.transpose(seg, (2, 0, 1))
        
        tumor_mask = (seg > 0)
        tumor_areas = tumor_mask.sum(axis=(1, 2))
        tumor_slices = np.where(tumor_areas > 0)[0].tolist()
        
        return tumor_slices
    
    def _sample_frames(self, tumor_slices: List[int], total_slices: int) -> List[int]:
        """采样帧索引"""
        if len(tumor_slices) == 0:
            # 如果没有肿瘤,随机采样
            center = total_slices // 2
            tumor_slices = list(range(max(0, center - 20), min(total_slices, center + 20)))
        
        # 计算需要的范围
        needed_range = self.num_frames * self.frame_stride
        
        # 选择一个包含肿瘤的起始点
        if len(tumor_slices) > 0:
            center_slice = tumor_slices[len(tumor_slices) // 2]
        else:
            center_slice = total_slices // 2
        
        # 计算起始和结束索引
        half_range = needed_range // 2
        start_idx = max(0, center_slice - half_range)
        end_idx = min(total_slices, start_idx + needed_range)
        
        # 如果范围不够,调整
        if end_idx - start_idx < needed_range:
            start_idx = max(0, end_idx - needed_range)
        
        # 采样帧
        available = list(range(start_idx, end_idx, self.frame_stride))
        
        if len(available) < self.num_frames:
            # 如果帧数不够,重复最后一帧
            available = available + [available[-1]] * (self.num_frames - len(available))
        else:
            available = available[:self.num_frames]
        
        return available
    
    def _process_slice(self, slice_2d: np.ndarray) -> np.ndarray:
        """处理单个切片"""
        # 归一化到 0-1
        slice_2d = normalize_intensity(slice_2d)
        
        # 转为 uint8
        slice_2d = (slice_2d * 255).astype(np.uint8)
        
        # 转为RGB
        slice_rgb = np.stack([slice_2d, slice_2d, slice_2d], axis=-1)
        
        # 调整大小
        if self.target_size is not None:
            slice_rgb = cv2.resize(slice_rgb, self.target_size, interpolation=cv2.INTER_LINEAR)
        
        return slice_rgb
    
    def _process_mask(self, mask_2d: np.ndarray, num_classes: int = 4) -> np.ndarray:
        """处理单个mask切片
        
        BraTS 标签:
            0: 背景
            1: NCR (Necrotic tumor core)
            2: ED (Peritumoral Edema)  
            3: ET (Enhancing tumor)
        
        Args:
            mask_2d: 原始标签
            num_classes: 类别数 (4 = 背景 + 3类肿瘤)
        """
        # 保持原始类别 (0, 1, 2, 3)
        mask_2d = mask_2d.astype(np.uint8)
        
        # 调整大小
        if self.target_size is not None:
            mask_2d = cv2.resize(mask_2d, self.target_size, interpolation=cv2.INTER_NEAREST)
        
        return mask_2d
    
    def _get_bbox_from_mask(self, mask: np.ndarray) -> Optional[Tuple[float, float, float, float]]:
        """从mask获取归一化的bbox"""
        if mask.sum() == 0:
            return None
        
        rows = np.any(mask, axis=1)
        cols = np.any(mask, axis=0)
        
        y_indices = np.where(rows)[0]
        x_indices = np.where(cols)[0]
        
        if len(y_indices) == 0 or len(x_indices) == 0:
            return None
        
        y_min, y_max = y_indices[0], y_indices[-1]
        x_min, x_max = x_indices[0], x_indices[-1]
        
        h, w = mask.shape
        
        # 归一化坐标
        return (x_min / w, y_min / h, x_max / w, y_max / h)
    
    def _augment(self, frames: List[np.ndarray], masks: List[np.ndarray]) -> Tuple[List[np.ndarray], List[np.ndarray]]:
        """数据增强"""
        if not self.augment:
            return frames, masks
        
        # 随机水平翻转
        if random.random() > 0.5:
            frames = [np.fliplr(f).copy() for f in frames]
            masks = [np.fliplr(m).copy() for m in masks]
        
        # 随机垂直翻转
        if random.random() > 0.5:
            frames = [np.flipud(f).copy() for f in frames]
            masks = [np.flipud(m).copy() for m in masks]
        
        # 随机旋转 (90度的倍数)
        if random.random() > 0.5:
            k = random.choice([1, 2, 3])
            frames = [np.rot90(f, k).copy() for f in frames]
            masks = [np.rot90(m, k).copy() for m in masks]
        
        return frames, masks
    
    def __getitem__(self, idx: int) -> Dict[str, Any]:
        """
        获取一个训练样本
        
        Returns:
            Dict containing:
                - frames: (T, C, H, W) 视频帧
                - masks: (T, H, W) 分割mask
                - bboxes: (T, 4) 边界框 (归一化坐标)
                - frame_indices: 帧索引
                - case_name: 病例名称
        """
        info = self.case_info[idx]
        
        # 加载数据
        volume = self._load_volume(info['mod_path'])
        seg = self._load_volume(info['seg_path'])
        
        # 转置使得切片在第一维
        if volume.shape[0] > volume.shape[2]:
            volume = np.transpose(volume, (2, 0, 1))
            seg = np.transpose(seg, (2, 0, 1))
        
        total_slices = volume.shape[0]
        
        # 获取肿瘤切片并采样
        tumor_slices = self._get_tumor_slices(seg)
        frame_indices = self._sample_frames(tumor_slices, total_slices)
        
        # 提取帧和mask
        frames = []
        masks = []
        
        for idx in frame_indices:
            frame = self._process_slice(volume[idx])
            mask = self._process_mask(seg[idx])
            frames.append(frame)
            masks.append(mask)
        
        # 数据增强
        frames, masks = self._augment(frames, masks)
        
        # 计算每帧的bbox
        bboxes = []
        for mask in masks:
            bbox = self._get_bbox_from_mask(mask)
            if bbox is None:
                bbox = (0.0, 0.0, 1.0, 1.0)  # 默认全图
            bboxes.append(bbox)
        
        # 转换为tensor
        # frames: (T, H, W, C) -> (T, C, H, W)
        frames_tensor = torch.stack([
            torch.from_numpy(f).permute(2, 0, 1).float() / 255.0
            for f in frames
        ])
        
        # 归一化
        mean = torch.tensor(self.normalize_mean).view(1, 3, 1, 1)
        std = torch.tensor(self.normalize_std).view(1, 3, 1, 1)
        frames_tensor = (frames_tensor - mean) / std
        
        masks_tensor = torch.stack([
            torch.from_numpy(m).long() for m in masks
        ])
        
        bboxes_tensor = torch.tensor(bboxes, dtype=torch.float32)
        
        return {
            'frames': frames_tensor,  # (T, C, H, W)
            'masks': masks_tensor,    # (T, H, W)
            'bboxes': bboxes_tensor,  # (T, 4)
            'frame_indices': torch.tensor(frame_indices),
            'case_name': info['case_name'],
            'num_frames': len(frame_indices),
        }


class BraTSImageDataset(Dataset):
    """
    BraTS数据集 - 2D切片版本,用于图像级别的训练
    """
    
    def __init__(
        self,
        data_root: str,
        split: str = 'train',
        modality: int = 0,
        target_size: Tuple[int, int] = (512, 512),
        augment: bool = True,
        train_ratio: float = 0.9,
        val_ratio: float = 0.1,
        test_ratio: float = 0.0,
        seed: int = 42,
        split_json: Optional[str] = None,
        only_tumor_slices: bool = True,
        normalize_mean: Tuple[float, ...] = (0.5, 0.5, 0.5),
        normalize_std: Tuple[float, ...] = (0.5, 0.5, 0.5),
    ):
        super().__init__()
        
        self.data_root = Path(data_root)
        self.split = split
        self.modality = modality
        self.modality_names = ['t1c', 't1n', 't2f', 't2w']
        self.target_size = target_size
        self.augment = augment and (split == 'train')
        self.only_tumor_slices = only_tumor_slices
        self.normalize_mean = normalize_mean
        self.normalize_std = normalize_std
        
        # 获取所有病例(case-level)
        all_cases = sorted([d for d in self.data_root.iterdir() if d.is_dir()])

        def _validate_ratios(tr, vr, ter):
            s = float(tr) + float(vr) + float(ter)
            if abs(s - 1.0) > 1e-6:
                raise ValueError(f"train/val/test ratios must sum to 1.0, got {s}")

        def _split_by_ratio(case_list: List[Path], tr: float, vr: float, ter: float, sd: int):
            _validate_ratios(tr, vr, ter)
            case_list = list(case_list)
            rng = random.Random(sd)
            rng.shuffle(case_list)
            n = len(case_list)
            n_train = int(round(n * tr))
            n_val = int(round(n * vr))
            n_train = min(max(n_train, 0), n)
            n_val = min(max(n_val, 0), n - n_train)
            train = case_list[:n_train]
            val = case_list[n_train : n_train + n_val]
            test = case_list[n_train + n_val :]
            return {"train": train, "val": val, "test": test}

        def _split_by_json(case_list: List[Path], split_file: str):
            with open(split_file, "r") as f:
                cfg = json.load(f)
            splits = cfg.get("splits", cfg)
            wanted = splits.get(self.split)
            if wanted is None:
                raise KeyError(f"split '{self.split}' not found in split json: {split_file}")
            wanted = set(wanted)
            return [c for c in case_list if c.name in wanted]

        if split_json:
            cases = _split_by_json(all_cases, split_json)
        else:
            parts = _split_by_ratio(all_cases, train_ratio, val_ratio, test_ratio, seed)
            if split not in parts:
                raise ValueError(f"split must be one of train/val/test, got: {split}")
            cases = parts[split]
        
        # 构建切片索引
        self.samples = self._build_sample_index(cases)
        print(f"BraTS {split} set: {len(self.samples)} slices from {len(cases)} cases")
    
    def _build_sample_index(self, cases: List[Path]) -> List[Dict]:
        """构建切片级别的索引"""
        samples = []
        
        for case_dir in cases:
            case_name = case_dir.name
            
            # 查找文件
            mod_name = self.modality_names[self.modality]
            mod_path = None
            for name in [f"{mod_name}.nii.gz", f"{case_name}-{mod_name}.nii.gz"]:
                p = case_dir / name
                if p.exists():
                    mod_path = str(p)
                    break
            
            seg_path = None
            for name in ["seg.nii.gz", f"{case_name}-seg.nii.gz"]:
                p = case_dir / name
                if p.exists():
                    seg_path = str(p)
                    break
            
            if mod_path is None or seg_path is None:
                continue
            
            # 加载分割来确定切片
            seg = nib.load(seg_path).get_fdata()
            if seg.shape[0] > seg.shape[2]:
                seg = np.transpose(seg, (2, 0, 1))
            
            for slice_idx in range(seg.shape[0]):
                has_tumor = (seg[slice_idx] > 0).any()
                
                if self.only_tumor_slices and not has_tumor:
                    continue
                
                samples.append({
                    'case_name': case_name,
                    'mod_path': mod_path,
                    'seg_path': seg_path,
                    'slice_idx': slice_idx,
                    'has_tumor': has_tumor,
                })
        
        return samples
    
    def __len__(self) -> int:
        return len(self.samples)
    
    def __getitem__(self, idx: int) -> Dict[str, Any]:
        sample = self.samples[idx]
        
        # 加载数据
        volume = nib.load(sample['mod_path']).get_fdata().astype(np.float32)
        seg = nib.load(sample['seg_path']).get_fdata().astype(np.float32)
        
        if volume.shape[0] > volume.shape[2]:
            volume = np.transpose(volume, (2, 0, 1))
            seg = np.transpose(seg, (2, 0, 1))
        
        # 获取切片
        slice_idx = sample['slice_idx']
        image = volume[slice_idx]
        mask = seg[slice_idx]
        
        # 处理
        image = normalize_intensity(image)
        image = (image * 255).astype(np.uint8)
        image = np.stack([image, image, image], axis=-1)
        
        if self.target_size is not None:
            image = cv2.resize(image, self.target_size, interpolation=cv2.INTER_LINEAR)
            mask = cv2.resize(mask, self.target_size, interpolation=cv2.INTER_NEAREST)
        
        # 保持原始 4 类标签 (0=背景, 1=NCR, 2=ED, 3=ET)
        mask = mask.astype(np.uint8)
        
        # 数据增强
        if self.augment:
            if random.random() > 0.5:
                image = np.fliplr(image).copy()
                mask = np.fliplr(mask).copy()
            if random.random() > 0.5:
                image = np.flipud(image).copy()
                mask = np.flipud(mask).copy()
        
        # 计算bbox
        bbox = self._get_bbox_from_mask(mask)
        if bbox is None:
            bbox = (0.0, 0.0, 1.0, 1.0)
        
        # 转为tensor
        image_tensor = torch.from_numpy(image).permute(2, 0, 1).float() / 255.0
        mean = torch.tensor(self.normalize_mean).view(3, 1, 1)
        std = torch.tensor(self.normalize_std).view(3, 1, 1)
        image_tensor = (image_tensor - mean) / std
        
        mask_tensor = torch.from_numpy(mask).long()
        bbox_tensor = torch.tensor(bbox, dtype=torch.float32)
        
        return {
            'image': image_tensor,    # (C, H, W)
            'mask': mask_tensor,      # (H, W)
            'bbox': bbox_tensor,      # (4,)
            'case_name': sample['case_name'],
            'slice_idx': slice_idx,
            'has_tumor': sample['has_tumor'],
        }
    
    def _get_bbox_from_mask(self, mask: np.ndarray) -> Optional[Tuple[float, float, float, float]]:
        if mask.sum() == 0:
            return None
        
        rows = np.any(mask, axis=1)
        cols = np.any(mask, axis=0)
        
        y_indices = np.where(rows)[0]
        x_indices = np.where(cols)[0]
        
        if len(y_indices) == 0 or len(x_indices) == 0:
            return None
        
        y_min, y_max = y_indices[0], y_indices[-1]
        x_min, x_max = x_indices[0], x_indices[-1]
        
        h, w = mask.shape
        return (x_min / w, y_min / h, x_max / w, y_max / h)


def collate_fn_brats(batch: List[Dict]) -> Dict[str, Any]:
    """自定义collate函数"""
    # 视频数据
    if 'frames' in batch[0]:
        return {
            'frames': torch.stack([b['frames'] for b in batch]),  # (B, T, C, H, W)
            'masks': torch.stack([b['masks'] for b in batch]),    # (B, T, H, W)
            'bboxes': torch.stack([b['bboxes'] for b in batch]),  # (B, T, 4)
            'case_names': [b['case_name'] for b in batch],
        }
    # 图像数据
    else:
        return {
            'images': torch.stack([b['image'] for b in batch]),  # (B, C, H, W)
            'masks': torch.stack([b['mask'] for b in batch]),    # (B, H, W)
            'bboxes': torch.stack([b['bbox'] for b in batch]),   # (B, 4)
            'case_names': [b['case_name'] for b in batch],
        }


if __name__ == "__main__":
    # 测试
    data_root = "/data/yty/brats2023/ASNR-MICCAI-BraTS2023-GLI-Challenge-TrainingData"
    
    print("Testing BraTSVideoDataset...")
    video_ds = BraTSVideoDataset(data_root, split='train', num_frames=8)
    print(f"  Total samples: {len(video_ds)}")
    
    sample = video_ds[0]
    print(f"  frames shape: {sample['frames'].shape}")
    print(f"  masks shape: {sample['masks'].shape}")
    print(f"  bboxes shape: {sample['bboxes'].shape}")
    
    print("\nTesting BraTSImageDataset...")
    image_ds = BraTSImageDataset(data_root, split='train')
    print(f"  Total slices: {len(image_ds)}")
    
    sample = image_ds[0]
    print(f"  image shape: {sample['image'].shape}")
    print(f"  mask shape: {sample['mask'].shape}")
    print(f"  bbox: {sample['bbox']}")