zju-eye-pretrain / DATASET_OVERVIEW.md
MaybeRichard's picture
Initial upload: public_fundus (198k images, 42 shards) + manifest + captions + code
e2f75d1 verified
|
Raw
History Blame
28.3 kB
# Eye Pretrain 数据集总览
> 生成时间:2026-05-23
>
> 三批数据,统一 41 列 manifest schema,5 caption/image (4 L1 + 1 L3),cohort 命名空间隔离
---
## 0. 一表见全貌
| 来源 | 总图像 | OCT B-scan | fundus_color | slo_gray | 状态 |
|---|---:|---:|---:|---:|---|
| **私有 Shanghai DRI OCT Triton** | 419,042 | 352,343 | 30,714 | 35,985 | ✅ 已落地 h800 |
| **公开 fundus(6 cohort)** | 198,629 | 51,200 (GAMMA) | 147,429 | 0 | 已落地 (h800) |
| **公开 OCT(19 cohort)** | 488,705 | 488,705 | 0 | 0 | 本地完成 / 打包就绪 |
| **合计** | **1,106,376** | **~913,905** | **~177,429** | **~30,000** | |
**110 万图像**、其中 OCT B-scan **91 万张**
---
## 1. 私有数据集 — Shanghai DRI OCT Triton
### 1.1 来源
- 医院:上海中山医院
- 设备:Topcon DRI OCT Triton(SS-OCT,扫频源 OCT)
- 原始格式:`.fda`(Topcon 专有,约 30,735 个文件)
### 1.2 规模
| 指标 | 数量 |
|---|---:|
| Studies (FDA 文件数) | 30,734 |
| Total images | 419,042 |
| Captions | 2,095,210 (= 419,042 × 5) |
| OCT B-scan rows | **352,343** (主 radial 30,734 study × ~11.3 张/study + ~5k 张 subscan B-scan;部分 study radial 解出失败少于 12 张) |
| Fundus color rows | **30,714** (少 20 个 study 无 fundus) |
| SLO gray rows | **35,985** (主 SLO 30,734 + subscan SLO ~5k) |
`patient_hash = study_hash`(Topcon `@PATIENT_INFO_03` 加密,按 file-level 切分)。
### 1.3 每个 study 的组件
- **12 张径向 OCT B-scan**`scan_protocol=radial_12`, 9 mm/slice, 180°
- **1 张 fundus_color** — 45° 黄斑中心彩照
- **1 张 slo_gray** — 共焦扫描激光检眼镜
- **segmentation.npz** — 10 层 boundaries (ILM/RNFL/GCL+IPL/INL/OPL/ONL/ELM/IS-OS/RPE/BM) + invalid mask
- **可选**:sub-scan(`has_subscan=True` 的 study,约 5k 个),多为 optic disc OCT B-scan + SLO
### 1.4 设备信息(写入 manifest 每行)
| 字段 | 值 |
|---|---|
| device_vendor | topcon |
| device_model | dri_oct_triton |
| device_technology | ss_oct |
| hospital_domain | shanghai_zhongshan_v1 |
| ethnicity | Asian |
### 1.5 路径
| | 路径 |
|---|---|
| 本地 extracted | `/mnt/synology/08.数据/eye_pretrain/extracted/shanghai_drioct_triton/` |
| 本地 packed | `/mnt/synology/08.数据/eye_pretrain/packed/` (256 bucket + manifest, 153 GB, MD5 全) |
| h800 packed | `/mnt/tidal-alsh-share2/dataset/qinshengqian/research/c3/private_eye_pretrain_packed/` |
| **h800 unpack 目标** | `/mnt/tidal-alsh-share2/dataset/qinshengqian/research/c3/Data/Generation1/private_topcon/` |
### 1.6 代码
- `extract_fda.py` — FDA → bscan PNG + fundus JPG + SLO PNG + segmentation NPZ + meta.json
- `extract_subscan.py` — 追加 sub-scan 内容(@SUB_* chunks)
- `build_manifest.py` — meta.json → images_v1.parquet / studies_v1.parquet / patients_v1.parquet / captions_v1.parquet
- `pack.sh` / `unpack.sh` — 256 hash 桶切分 + MD5 校验
---
## 2. 公开 Fundus 数据集(6 cohort,198,629 images)
| Cohort 名 | images | captions | 主任务 | 设备 | mask |
|---|---:|---:|---|---|---|
| `public_drive_vessel` | 20 | 100 | 血管分割 | Unknown | vessel + FOV |
| `public_messidor2_dr` | 1,744 | 8,720 | DR 0-4 + DME + gradable | Unknown | — |
| `public_idrid` | 597 | 2,985 | DR/DME 分级 + 5 类病灶 + OD/fovea 定位 | Unknown | 81 张 seg (5+OD),OD/fovea 坐标 sidecar |
| `public_refuge2_disc_cup` | 1,200 | 6,000 | OD/OC 分割 + glaucoma(train 部分有 g/n 标签) | Unknown | 3 类 mask (bg/disc/cup) |
| `public_eyepacs_combo_dr_aug` | 143,668 | 718,340 | DR 0-4 | Unknown (mixed) | — |
| `public_gamma_multimodal` | 51,400 | 257,000 | 青光眼分级 (non/early/mid_advanced) + OD/OC + fovea | Unknown OCT scanner | DC mask + fovea sidecar |
| **合计** | **198,629** | **993,145** | | | |
### 2.1 GAMMA 特殊结构
- 200 个 sample(100 train + 100 test)
- 每个 sample = **1 张 fundus + 256 张 OCT B-scan**(共享 study_id)
- 标签级别:volume(fundus 和 OCT 共享 glaucoma 分级标签)
- Train 100 个 sample 有 fovea_x/y 坐标 → sidecar parquet
### 2.2 路径
| | 路径(h800) |
|---|---|
| 统一 manifest | `/mnt/tidal-alsh-share2/.../public_eye_pretrain/manifest/public_images_v1.parquet` |
| 统一 captions | `/mnt/tidal-alsh-share2/.../public_eye_pretrain/captions/public_captions_v1.parquet` |
| Studies | `/mnt/tidal-alsh-share2/.../public_eye_pretrain/manifest/public_studies_v1.parquet` (147,429 行) |
| Schema | `/mnt/tidal-alsh-share2/.../public_eye_pretrain/schema_v1.json` |
| extracted_root | `/mnt/tidal-alsh-share2/.../public_eye_pretrain/extracted/` |
| Sidecar (IDRiD) | `/mnt/tidal-alsh-share2/.../public_eye_pretrain/manifest/public_idrid_sidecar.parquet` |
| Sidecar (GAMMA) | `/mnt/tidal-alsh-share2/.../public_eye_pretrain/manifest/public_gamma_multimodal_sidecar.parquet` |
### 2.3 代码(本地)
- `public_common.py` — 41 列 schema + caption_l1_public + study_hash 命名空间
- `adapter_drive.py` / `adapter_messidor2.py` / `adapter_idrid.py` / `adapter_refuge2.py` / `adapter_eyepacs.py` / `adapter_gamma.py`
- `build_public_manifest.py` — concat 6 个 per-cohort parquet 到统一 manifest
---
## 3. 公开 OCT 数据集(19 cohort,488,705 images)
### 3.1 19 cohort 详情
| Cohort 名 | Source | studies | images | Disease | 设备 | Region | mask | Sidecar |
|---|---|---:|---:|---|---|---|---|---|
| `public_oct_kermany` | 1/Kermany 2018 (Cell) | 109,309 | 109,309 | CNV/DME/DRUSEN/NORMAL | Heidelberg Spectralis | USA | — | — |
| `public_oct_octa500` | OCTA500/Li 2024 | 299 (1 vol 损坏跳过) | 119,600 | NORMAL/DR/AMD/CNV(仅 200 vol 有标签) | Optovue RTVue | Asian | **6 类 B-scan mask** | age+sex+eye |
| `public_oct_olives` | 11/OLIVES (NeurIPS 2022) | 1,295 visits | 63,489 | DR / DME longitudinal | Spectralis HRA+OCT | Mixed | — | — |
| `public_oct_nyu_poag` | 10/NYU POAG (Zenodo) | 56,576 | 56,576 | POAG / NORMAL | Unknown (volume) | Unknown | — | — |
| `public_oct_areds2` | 8/AREDS2 (NEI) | 38,382 | 38,382 | AMD / NORMAL | Bioptigen SD-OCT | Mixed | — | — |
| `public_oct_uestc` | UESTC天池/Wu 2023 | 35,280 | 35,280 | (无 disease 标签) | **BM-400K BMizar (Topi 国产)** + Spectralis | China | — | — |
| `public_oct_c8` | C8/Kaggle | 24,000 | 24,000 | 8 class compiled | Unknown | Mixed | — | — |
| `public_oct_neh_ut_2021` | 7/NEH_UT_2021 | 16,810 | 16,810 | CNV/DRUSEN/NORMAL | Heidelberg SD-OCT | Iran | — | patient_id+eye (在 CSV) |
| `public_oct_retouch` | 17/RETOUCH (MICCAI 2017) | 6,936 | 6,936 | AMD/RVO | **3 设备子集** (Cirrus/Spectralis/Topcon) | Europe | **IRF/SRF/PED 3 类** | — |
| `public_oct_oimhs` | 16/OIMHS | 3,859 | 3,859 | MH stage 1-4 | Spectralis SD-OCT | China | layer mask | age+sex+eye+stage |
| `public_oct_srinivasan_2014` | 13/Srinivasan 2014 (Duke) | 3,231 | 3,231 | AMD/DME/NORMAL | Heidelberg Spectralis | Mixed | — | — |
| `public_oct_aroi` | 6/AROI | 3,072 | 3,072 | nAMD | Cirrus 4000 | Croatia | layer mask | — |
| `public_oct_amd_sd` | AMD-SD | 3,049 | 3,049 | wet_AMD | Cirrus 5000 | China | **5 类 (SRF/IRF/PED/SHRM/ISOS)** | — |
| `public_oct_octdl` | 23/OCTDL | 2,064 | 2,064 | 7 类(AMD/DME/ERM/NO/RAO/RVO/VID) | Optovue RTVue | Russia | — | age+sex+patient |
| `public_oct_thoct1800` | 20/THOCT1800 | 1,800 | 1,800 | AMD/DME/NORMAL | Cirrus | China | — | — |
| `public_oct_chiu_dme_2015` | 12/Chiu 2015 (Duke) | 610 | 610 | DME | Heidelberg Spectralis | Unknown | **8 层 + fluid** | — |
| `public_oct_octid` | 3/OCTID | 572 | 572 | DR/MH/CSR/AMD/NORMAL | Cirrus 5000 | India | — | — |
| `public_oct_glaucoma` | 9/Glaucoma OCT | 49 | 49 | Glaucoma | **Stratus TD-OCT (唯一 TD)** | Unknown | ILM + RPE | — |
| `public_oct_sparsity_sdoct_2012` | 14/Sparsity SDOCT 2012 | 17 | 17 | AMD/NORMAL | Bioptigen SD-OCT | Unknown | — | — |
| **合计** | | **307,200** | **488,705** | | | | **126,536 行 has_segmentation=True** | |
### 3.2 路径
| | 路径 |
|---|---|
| 本地输出根 | `/mnt/new/OCT Retinal B-scan数据集汇总/oct_public_pretrain/` |
| 统一 manifest | `.../oct_public_pretrain/manifest/oct_public_images_v1.parquet` |
| 统一 captions | `.../oct_public_pretrain/captions/oct_public_captions_v1.parquet` |
| Studies | `.../oct_public_pretrain/manifest/oct_public_studies_v1.parquet` (307,200) |
| Sidecar | `.../public_oct_oimhs_sidecar.parquet` (3,859), `.../public_oct_octdl_sidecar.parquet` (448), `.../public_oct_octa500_sidecar.parquet` |
| Schema | `.../oct_public_pretrain/schema_v1.json` |
| extracted_root | `.../oct_public_pretrain/extracted/` |
| 打包 (1725 tar) | `.../oct_public_pretrain/packed/` (119 GB, MD5 全) |
### 3.3 代码(本地)
- `oct_public_common.py` — OCT caption_l1_oct + 多 slice study 支持
- `build_oct_public.py` — 19 dataset 处理函数 + dispatcher(基于 `unified_metadata.csv` + OCTA500/UESTC 自定义枚举)
- `build_oct_public_manifest.py` — concat 19 个 per-cohort parquet
- `pack.sh` / `unpack.sh` — 大 cohort 256 hash 桶切分 + MD5
### 3.4 关键约定
- **OLIVES**: `study_id = hash(patient_eye_visit)``patient_hash = hash(patient)` — 跨 visit 一致
- **OCTA500**: 1 vol = 1 study,400 slice 共享 study_id,bscan_index 0–399
- **UESTC**: `scan_protocol` 区分 3 子集 (volume_3d_macula_6x6mm / 20x24mm / spectralis)
- **OIMHS**: `study_basename = oimhs_p{pid}_e{eye_id}_{stem}`(修复同 patient 多 eye 同名文件冲突)
---
## 4. Modality 分布(三批合计)
| Modality | 数量 | 来源 |
|---|---:|---|
| `oct_bscan` | **892,248** | 私有 352,343 + GAMMA 51,200 + OCT public 488,705 |
| `fundus_color` | **178,143** | 私有 30,714 + 公开 fundus 147,429 |
| `slo_gray` | **35,985** | 私有(含 subscan SLO)|
| **总图像** | **1,106,376** | |
---
## 5. OCT 设备 / 厂商分布
| Vendor | Model | Tech | 数量 (OCT B-scan) | Cohorts |
|---|---|---|---:|---|
| **Topcon** | DRI OCT Triton | **SS-OCT** | ~374,000 | private (唯一 SS-OCT) |
| Topcon | Topcon 3D OCT | SD-OCT | 2,688 | RETOUCH (Topcon 子集) |
| **Heidelberg** | Spectralis (含 HRA+OCT) | SD-OCT | ~380,000 | Kermany, OLIVES, NEH_UT, Chiu, Srinivasan, OIMHS, RETOUCH, UESTC Spectralis 子集 |
| Optovue | RTVue series | SD-OCT | ~122,000 | OCTA500 (120k), OCTDL (2k) |
| Bioptigen | Bioptigen SD-OCT | SD-OCT | ~38,400 | AREDS2, Sparsity |
| Zeiss | Cirrus (HD-OCT/4000/5000) | SD-OCT | ~12,000 | AROI, AMD-SD, OCTID, RETOUCH Cirrus, THOCT1800 |
| Zeiss | Stratus | **TD-OCT** | 49 | Glaucoma_OCT (唯一 TD-OCT) |
| Topi 国产 | BM-400K BMizar | SD-OCT | ~33,000 | UESTC BMizar 6×6 + 20×24 |
| 未知 | | | ~80,000 | NYU_POAG (57k) + C8 (24k) |
| GAMMA scanner | unspecified | — | 51,200 | GAMMA OCT volume slices |
---
## 6. 疾病覆盖
按 OCT B-scan 数量粗算(含部分重叠数据集):
| Disease 类别 | 总图像 | 主要来源 |
|---|---:|---|
| NORMAL | ~150,000+ | Kermany, NYU_POAG, AREDS2, C8, NEH_UT, Srinivasan, REFUGE2 train n |
| DR (0-4) | ~150,000+ | EyePACS (143k), Messidor2, IDRiD, OLIVES, AREDS2 部分 |
| AMD / nAMD / wet_AMD | ~80,000 | AREDS2, NEH_UT, AROI, AMD-SD, Srinivasan, OCTID, OCTDL, RETOUCH |
| DME | ~80,000 | OLIVES, Kermany, Chiu, Srinivasan, THOCT1800, OCTDL |
| POAG / Glaucoma | ~57,000 | NYU_POAG (57k), GAMMA, REFUGE2 train g, Glaucoma_OCT, Messidor2 |
| CNV | ~44,000 | Kermany, NEH_UT, OCTID, OCTA500 |
| DRUSEN | ~17,000 | Kermany, NEH_UT |
| MH (含 stage 1-4) | ~8,000+ | OIMHS, OCTID, C8 |
| CSR | ~3,000+ | OCTID, C8 |
| ERM | ~155 | OCTDL |
| RVO / RAO | ~150 | OCTDL, RETOUCH |
| VID | ~76 | OCTDL |
| 无标签 (unsupervised pretraining) | ~35,000+ | UESTC (35k) + OCTA500 未标记 100 vol + APTOS test |
---
## 7. 分割 mask 覆盖
| Mask 类型 | 张数 | 来源 |
|---|---:|---|
| OCT 多层 (10-layer in NPZ) | ~370,000 | 私有 Topcon(每 B-scan 一份 layer) |
| OCT 8-layer + fluid | 610 | Chiu_DME_2015 |
| OCT 层分割 (.tif) | 7,000+ | AROI (3k), OIMHS (3.9k), Glaucoma_OCT (49) |
| OCT 病灶多类 (IRF/SRF/PED) | 6,936 | RETOUCH |
| OCT 病灶 5 类 (SRF/IRF/PED/SHRM/ISOS) | 3,049 | AMD-SD |
| OCT-A B-scan 6 类 mask | 119,600 | OCTA500 |
| Fundus 血管 | 20 | DRIVE training |
| Fundus disc/cup 3 类 | 2,400 | REFUGE2 (1200), GAMMA (200), IDRiD (516+81) |
| Fundus 5 类病灶 (MA/HE/EX/SE) + OD | 81 | IDRiD segmentation |
| **合计带 mask** | **~510,000+ 张** | |
---
## 8. 统一 41 列 manifest schema
三批数据严格对齐以下 41 列。训练侧 `pd.concat` 直接拼。
```
cohort, study_id, patient_hash, visit_date, eye,
device_vendor, device_model, device_serial_hash, device_software_version,
hospital_domain, ethnicity,
image_quality_score, image_quality_band,
diagnosis_group, lesion_tags, lesion_location, layer_involvement, severity,
diagnosis_source, label_confidence, schema_version,
image_id, file_path, file_format,
modality, anatomy, device_technology, scan_protocol,
scan_x_mm, bscan_index,
image_height_px, image_width_px, axial_resolution_um,
has_segmentation, n_layers_visible,
fovea_x_norm, crt_um, choroid_thickness_um,
oct_footprint_bbox_fundus, oct_footprint_bbox_slo,
is_valid
```
**受控值**
- `modality` ∈ {oct_bscan, fundus_color, slo_gray}
- `anatomy` ∈ {macula, optic_disc, secondary_unknown}
- `device_technology` ∈ {ss_oct, sd_oct, td_oct, fundus_camera, slo, unknown}
- `severity` ∈ {none, mild, moderate, severe, proliferative, unknown}
- `scan_protocol` 开值:{radial_12, single_shot, subscan_line, subscan_single_shot, volume_3d_macula, volume_3d_macula_6x6mm, volume_3d_macula_20x24mm, volume_3d_macula_spectralis}
**Captions parquet 列**
```
caption_id, image_id, level, prompt_text, language, generator, grounded_in
```
每图固定 5 条 caption:
- `L1_v1_factual` / `L1_v2_style` / `L1_v3_prefix` / `L1_v4_short`(全 manifest 字段衍生)
- `L3_derived`(含几何/分割附加信息,私有数据集含 CRT/choroid thickness/quality score)
---
## 9. 训练侧路径映射
每个 manifest 自带 `cohort` 列;`file_path` 是相对路径,需要拼 `extracted_root`
| Manifest parquet | extracted_root |
|---|---|
| `Data/Generation1/private_topcon/manifest/images_v1.parquet` | `Data/Generation1/private_topcon/extracted/shanghai_drioct_triton/` |
| `public_eye_pretrain/manifest/public_images_v1.parquet` | `public_eye_pretrain/extracted/` |
| (待上传) `oct_public_pretrain/manifest/oct_public_images_v1.parquet` | `oct_public_pretrain/extracted/` |
**注意**:私有的 `file_path` 不带 cohort 前缀(如 `00/abc.../bscan_radial/000.png`);两个公开的 `file_path` 带 cohort 前缀(如 `public_oct_kermany/00/abc.../bscan.png`)。训练侧根据 manifest 来源选择对应 root。
---
## 10. Code / Scripts 索引
本地代码仓库:`/home/richard/Documents/Code/ZJU/Dataset/`
| 模块 | 用途 |
|---|---|
| `public_common.py` | 41 列 schema + caption_l1_public + study_hash 命名空间 + IO helpers |
| `oct_public_common.py` | OCT caption_l1_oct + 多 slice/study 共享 worker |
| `extract_fda.py` | 私有 Topcon FDA → bscan/fundus/slo/seg/meta.json |
| `extract_subscan.py` | 私有 sub-scan @SUB_* chunks 提取 |
| `build_manifest.py` | 私有 meta.json → 41 列 parquet + captions |
| `adapter_drive.py` ... `adapter_gamma.py` | 6 个公开 fundus adapter |
| `build_public_manifest.py` | concat 公开 fundus 6 parquet → 统一 |
| `build_oct_public.py` | 19 个公开 OCT 数据集统一处理 |
| `build_oct_public_manifest.py` | concat 公开 OCT 19 parquet → 统一 |
| `run.sh` | 三批数据完整流水线命令(顺序执行) |
| `fixup_errors.sh` | 私有数据集 sub-scan 错误重试脚本 |
| `pack.sh` / `unpack.sh` (各两份) | 私有 + OCT public 打包/解包 |
| `INTEGRATION_GUIDE.md` | 公开 fundus 数据集接入手册(如何写新 adapter) |
---
## 11. 进度状态
| 任务 | 状态 |
|---|---|
| 私有 Topcon 处理 | ✅ 完成 |
| 私有 Topcon 打包 (153 GB) | ✅ 完成 |
| 私有 Topcon 上传 h800 | ✅ 完成(含 bucket_2b 重传) |
| 私有 Topcon 解包 (Data/Generation1/private_topcon/) | ✅ 完成,Python 验证全通过 |
| 公开 fundus 处理 + manifest (h800) | ✅ 完成 |
| 公开 OCT 19 cohort 处理 (本地) | ✅ 完成 |
| 公开 OCT 统一 manifest | ✅ 完成 (488,705 images) |
| 公开 OCT 打包 (1,725 tar / 119 GB) | ✅ 完成 |
| 公开 OCT 上传 h800 | ⏸ 等你启动 |
| 训练侧三 parquet 拼接 | ⏸ 后续 |
---
## 12. 训练侧使用指南(核心)
### 12.1 数据加载的三个 manifest + 三个 root
训练 dataloader 要同时读这三份 parquet,**41 列 schema 完全一致,直接 `pd.concat`**
| Source | Manifest parquet | extracted_root (拼 `file_path` 用) |
|---|---|---|
| 私有 Topcon | `Data/Generation1/private_topcon/manifest/images_v1.parquet` | `Data/Generation1/private_topcon/extracted/shanghai_drioct_triton/` |
| 公开 fundus | `public_eye_pretrain/manifest/public_images_v1.parquet` | `public_eye_pretrain/extracted/` |
| 公开 OCT | `oct_public_pretrain/manifest/oct_public_images_v1.parquet` | `oct_public_pretrain/extracted/` |
**关键差异**:私有的 `file_path` 不带 cohort 前缀(如 `00/abc.../bscan_radial/000.png`),两个公开的 `file_path` 带 cohort 前缀(如 `public_oct_kermany/00/abc.../bscan.png`)。因此 dataloader 必须根据每行的 `cohort` 字段选对应 root。
### 12.2 拼接示例代码
```python
import pandas as pd
from pathlib import Path
ROOTS = {
# cohort → extracted_root
"shanghai_drioct_triton": "/mnt/tidal-alsh-share2/.../Data/Generation1/private_topcon/extracted/shanghai_drioct_triton",
# 所有 public_* cohort 共享一个父根
"_public_fundus_": "/mnt/tidal-alsh-share2/.../public_eye_pretrain/extracted",
"_public_oct_": "/mnt/tidal-alsh-share2/.../oct_public_pretrain/extracted",
}
def resolve(row):
c = row["cohort"]
if c == "shanghai_drioct_triton":
return Path(ROOTS["shanghai_drioct_triton"]) / row["file_path"]
elif c.startswith("public_oct_"):
return Path(ROOTS["_public_oct_"]) / row["file_path"] # file_path 已含 cohort 前缀
else: # public_drive_vessel / public_messidor2_dr / ...
return Path(ROOTS["_public_fundus_"]) / row["file_path"]
df_priv = pd.read_parquet("Data/Generation1/private_topcon/manifest/images_v1.parquet")
df_fun = pd.read_parquet("public_eye_pretrain/manifest/public_images_v1.parquet")
df_oct = pd.read_parquet("oct_public_pretrain/manifest/oct_public_images_v1.parquet")
manifest = pd.concat([df_priv, df_fun, df_oct], ignore_index=True)
manifest["abs_path"] = manifest.apply(resolve, axis=1)
# ~ 1.1M rows, 42 columns
```
Captions 同理:
```python
caps_priv = pd.read_parquet("Data/Generation1/private_topcon/captions/captions_v1.parquet")
caps_fun = pd.read_parquet("public_eye_pretrain/captions/public_captions_v1.parquet")
caps_oct = pd.read_parquet("oct_public_pretrain/captions/oct_public_captions_v1.parquet")
captions = pd.concat([caps_priv, caps_fun, caps_oct], ignore_index=True)
# ~ 5.5M rows; image_id 关联到 manifest.image_id
```
### 12.3 PyTorch Dataset 模板
```python
import torch
from torch.utils.data import Dataset
from PIL import Image
import random
class EyePretrainDataset(Dataset):
def __init__(self, manifest_df, captions_df, modality=None, transform=None,
caption_level="L1_v1_factual"):
if modality:
manifest_df = manifest_df[manifest_df.modality.isin(modality)]
self.df = manifest_df.reset_index(drop=True)
# caption_level: L1_v1_factual / L1_v2_style / L1_v3_prefix / L1_v4_short / L3_derived / random
cap_sub = (captions_df if caption_level == "random"
else captions_df[captions_df.level == caption_level])
self.caps = cap_sub.groupby("image_id")["prompt_text"].apply(list).to_dict()
self.caption_level = caption_level
self.transform = transform
def __len__(self): return len(self.df)
def __getitem__(self, i):
r = self.df.iloc[i]
img = Image.open(r["abs_path"]).convert("RGB" if r["modality"] == "fundus_color" else "L")
if self.transform: img = self.transform(img)
caps = self.caps.get(r["image_id"], [""])
text = random.choice(caps) if self.caption_level == "random" else caps[0]
return {
"image": img, "text": text,
"cohort": r["cohort"], "modality": r["modality"],
"anatomy": r["anatomy"], "severity": r["severity"],
"diagnosis_group": list(r["diagnosis_group"]),
"bscan_index": r["bscan_index"],
"has_segmentation": r["has_segmentation"],
"image_id": r["image_id"], "study_id": r["study_id"],
"patient_hash": r["patient_hash"],
}
```
### 12.4 切分策略:**患者级 split**(防泄漏)
> ⚠️ 不要按行(image)随机切 train/val/test —— 同一患者的多张 B-scan 会跨 split 泄漏。
```python
import numpy as np
rng = np.random.default_rng(42)
patients = manifest["patient_hash"].unique()
rng.shuffle(patients)
n = len(patients)
train_p = set(patients[:int(0.9*n)])
val_p = set(patients[int(0.9*n):int(0.95*n)])
test_p = set(patients[int(0.95*n):])
manifest["split"] = manifest.patient_hash.map(
lambda p: "train" if p in train_p else ("val" if p in val_p else "test"))
```
**说明**
- 私有 Topcon:`patient_hash = study_hash`,每个 FDA 一个匿名患者,等价 file-level
- 公开 fundus:多数 cohort 也是 file-level(无 patient_id),少数(OLIVES、IDRiD grading、GAMMA)有真实 patient 共享
- 公开 OCT:Kermany(CNV-NNN-XXX 中段 = patient_id)、NEH_UT、OCTDL 有 patient_id;OLIVES `patient_hash` 跨 visit 一致
- 安全做法:永远按 `patient_hash` 切,cohort-level 也保留这套切分
### 12.5 三种典型训练任务的数据组合
#### (A) 纯无监督生成式预训练(VAE / diffusion / MAE)
```python
# 用全部 ~1.1M 张图像,不需要 label
ds = EyePretrainDataset(manifest, captions, modality=None,
caption_level="random")
# 或单模态预训练:
ds_oct = EyePretrainDataset(manifest, captions,
modality=["oct_bscan"]) # ~892k 张
ds_fun = EyePretrainDataset(manifest, captions,
modality=["fundus_color"]) # ~178k 张
```
#### (B) Caption-conditioned 生成(Stable Diffusion 风格)
```python
# 用 L1 4 个变体做 caption augmentation, L3 做精细条件
ds = EyePretrainDataset(manifest, captions,
modality=["oct_bscan", "fundus_color"],
caption_level="random") # 每 epoch 随机挑一个变体
```
L3_derived 包含具体几何/分割附加信息(私有 OCT 含 CRT、choroidal thickness、quality;公开 OCT 含 mask 类别说明)。如果要训练 **disease-aware** 生成器,建议把 `severity` / `diagnosis_group` 作为额外离散条件 embed。
#### (C) 多模态 / cross-modality 生成(fundus → OCT B-scan、SLO → OCT)
```python
# 按 study_id 分组,挑出同一 study 内多模态配对
groups = manifest.groupby("study_id")
multimodal_studies = []
for sid, g in groups:
mods = set(g["modality"])
if "oct_bscan" in mods and "fundus_color" in mods:
multimodal_studies.append(sid)
# 主要来源:
# 私有 Topcon 30k study (含 fundus+SLO+12 radial OCT)
# GAMMA 200 sample (含 fundus + 256 OCT)
# 配上 oct_footprint_bbox_fundus / oct_footprint_bbox_slo 做空间对齐
```
### 12.6 实操采样建议
**Cohort 不均衡极严重**(最大 Kermany 109k vs 最小 Sparsity 17,差 6400 倍)。直接均匀采样会被大 cohort 主导。常见做法:
```python
# 按 cohort 加权采样(每 cohort 等概率)
from torch.utils.data import WeightedRandomSampler
cohort_counts = manifest.cohort.value_counts()
weights = (1.0 / cohort_counts[manifest.cohort]).values
sampler = WeightedRandomSampler(weights, num_samples=len(manifest), replacement=True)
loader = DataLoader(ds, sampler=sampler, batch_size=64, num_workers=8)
```
或更激进的 **modality-balanced**(每 batch 内 50% OCT / 50% fundus):
```python
# 分两个 dataset, 用 ConcatDataset + RandomSampler 各 50%
```
### 12.7 OCT B-scan 几何条件(私有 + GAMMA + OCTA500 等 volume)
私有 Topcon 12 radial 协议固定:
```python
angle_deg = bscan_index * 15.0 # 0°, 15°, ..., 165°
```
可作为 angle conditioning embedding 输入。对私有 OCT B-scan 行:
```python
# manifest 已有 fovea_x_norm (B-scan 列方向归一化 fovea 位置 0.0-1.0)
# 可作 position embedding
```
对 GAMMA / OCTA500 的 volume slice:`bscan_index` 是 slice 序号(0..255 或 0..399),可做 axial position embedding。
### 12.8 三模态 spatial 配准(私有 Topcon)
每个私有 study 的 fundus / SLO 行 manifest 含:
- `oct_footprint_bbox_fundus` (x0,y0,x1,y1)
- `oct_footprint_bbox_slo`
12 radial B-scan **没有 per-bscan endpoints** 字段,但可推算(见 §1.3 angle conditioning 说明)。
适合用于 **ControlNet-style position embedding** / **共享空间坐标的 cross-attention**;不适合像素级 dense supervision(无 dense warp)。
### 12.9 常用过滤组合速查
| 目标 | 过滤 |
|---|---|
| 仅 OCT B-scan(生成式预训练 OCT) | `modality == "oct_bscan"` → ~892k |
| 仅 fundus_color | `modality == "fundus_color"` → ~178k |
| 仅黄斑中心 OCT | `modality == "oct_bscan" & anatomy == "macula"` |
| 仅视盘 OCT | `modality == "oct_bscan" & anatomy == "optic_disc"` |
| 仅 SS-OCT(私有 Topcon) | `device_technology == "ss_oct"` → 374k |
| 仅 SD-OCT(剔除 TD-OCT 49 张) | `device_technology == "sd_oct"` |
| 仅带 mask(监督分割 / mask-conditioned 生成) | `has_segmentation == True` → ~510k |
| 仅有疾病 grade(弱监督) | `severity in ['mild','moderate','severe','proliferative']` |
| 排除质量差 | `image_quality_band not in ['poor', 'ungradable']`(仅私有有质量分) |
### 12.10 推荐起步配置
| 训练目标 | 数据 | Caption level | Conditions |
|---|---|---|---|
| OCT VAE / MAE 预训练 | OCT 全集 892k | L1 random | cohort, modality, device_technology |
| Fundus diffusion 预训练 | Fundus 全集 178k | L1 random | cohort, severity, eye |
| Multi-modal (fundus → OCT) | 私有 30k + GAMMA 200 study 配对 | L3_derived | bbox + bscan_index |
| Disease-conditional gen | 全集 + diagnosis_group ≠ [] 子集 | L3_derived | severity + diagnosis_group multi-hot |
| Few-shot rare disease (Stargardt / RP / MacTel / RAO / VID) | 公开 OCTDL + IDRiD + (未来)dataset 2 | L3 | diagnosis_group |
### 12.11 注意事项 & 已知坑
1. **私有数据是 SS-OCT,公开多是 SD-OCT** —— 域差异(波长 1050 vs 840nm,脉络膜可见度不同)。生成模型若混训,建议把 `device_technology` 作为强条件 embed。
2. **OCTA500 mask 6 类 vs RETOUCH IRF/SRF/PED 3 类 vs AMD-SD 5 类** —— mask 像素值定义跨数据集**不统一**,需要单独建立 cohort-aware mask encoder 或先做 label 标准化。
3. **Caption 中 cohort 名称会暴露 cohort 标签** —— 如果要做 cohort-invariant 表示学习,需要 caption 改写去掉 cohort phrase(或加 cohort dropout)。
4. **OLIVES 同患者纵向数据** —— 若做 time-series 任务可按 `(patient, eye)` group + `study_meta.visit`(写在 meta.json `study_meta.visit` 但未进 41 列;可读 OLIVES sidecar 或解析 study_basename)。
5. **私有 quality score 仅在私有 cohort 有**(公开 image_quality_band 一律 `unknown`),按 quality 加权采样时只对私有生效。
6. **REFUGE2 val/test、APTOS test、OCTA500 100 vol** —— `severity=unknown`,按 `severity` 筛要小心。
7. **GAMMA OCT 切片是模拟"私有 radial" 的角度替代**:GAMMA OCT 是 volume_3d_macula 256 slices(线性平行扫描),不是 radial。`bscan_index` 语义不同。
8. **路径含中文 + 空格**(私有 `/mnt/synology/08.数据/` + 公开 OCT `/mnt/new/OCT Retinal B-scan数据集汇总/`),bash 一定要加双引号,Python `Path` 直接吞。