File size: 6,894 Bytes
e2f75d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
REFUGE2 adapter — disc/cup segmentation + glaucoma binary label (train only).

Inputs:
    {input_root}/REFUGE2/{train,val,test}/images/*.jpg
    {input_root}/REFUGE2/{train,val,test}/mask/*.{bmp,png}    (pixel 0/128/255 = bg/disc/cup)

File naming encodes split AND label:
    train/  g0001..g0040 = glaucoma,   n0001..n0360 = non-glaucoma     (mask: .bmp)
    val/    V0001..V0400                                                (mask: .png)
    test/   T0001..T0400                                                (mask: .bmp)
val/test glaucoma label is held-out by the challenge (severity=unknown for those).

Outputs (under {output_root}):
    extracted/public_refuge2_disc_cup/{hash[:2]}/{hash}/
        fundus_color.jpg
        disc_cup_mask.png         (preserves 0/128/255 — 3 classes)
        meta.json
    manifest/public_refuge2_disc_cup_images.parquet
    captions/public_refuge2_disc_cup_captions.parquet
"""
import argparse
import json
from pathlib import Path

import numpy as np
import pandas as pd
from PIL import Image

from public_common import (
    IMAGE_SCHEMA_COLUMNS, CAPTION_SCHEMA_COLUMNS,
    study_hash_for, default_base_fields,
    caption_l1_public, caption_l3_public,
    study_dir_for, rel_file_path, write_meta, coerce_image_row,
)

COHORT = "public_refuge2_disc_cup"
COHORT_PHRASE = "REFUGE2 optic disc and cup segmentation dataset"


def _split_and_label(filename: str) -> tuple:
    """Returns (split, glaucoma) from filename prefix.
    glaucoma: True / False / None (unknown for val/test)."""
    p = filename[0]
    if p == "g": return ("train", True)
    if p == "n": return ("train", False)
    if p == "V": return ("val", None)
    if p == "T": return ("test", None)
    return ("unknown", None)


def _save_disc_cup_mask(src: Path, dst: Path):
    """Preserve 3 classes (0/128/255). Coerce non-{0,128,255} values to nearest."""
    arr = np.array(Image.open(src).convert("L"))
    out = np.zeros_like(arr)
    out[(arr > 64) & (arr < 192)] = 128
    out[arr >= 192] = 255
    Image.fromarray(out, mode="L").save(dst, "PNG", optimize=True)


def process_one(image_path: Path, mask_path: Path, out_root: Path, force: bool):
    basename = image_path.stem  # g0001 / n0001 / V0001 / T0001
    split, glaucoma = _split_and_label(basename)
    sh = study_hash_for(COHORT, f"{split}_{basename}")
    sdir = study_dir_for(out_root, COHORT, sh)
    sdir.mkdir(parents=True, exist_ok=True)

    meta_p = sdir / "meta.json"
    if meta_p.exists() and not force:
        try:
            meta = json.loads(meta_p.read_text())
            if meta.get("status") == "ok":
                return _row_and_caps(meta)
        except Exception:
            pass

    img = Image.open(image_path).convert("RGB")
    w, h = img.size
    img.save(sdir / "fundus_color.jpg", "JPEG", quality=95)
    _save_disc_cup_mask(mask_path, sdir / "disc_cup_mask.png")

    meta = {
        "status": "ok", "cohort": COHORT, "study_hash": sh,
        "source_basename": basename, "split": split,
        "image_height_px": int(h), "image_width_px": int(w),
        "eye": "unknown",
        "glaucoma": glaucoma,  # True / False / None
        "has_disc_mask": True,
        "has_cup_mask": True,
    }
    write_meta(sdir, meta)
    return _row_and_caps(meta)


def _row_and_caps(meta: dict):
    sh = meta["study_hash"]
    image_id = f"{COHORT}_{sh}_fundus_color"
    row = default_base_fields(COHORT, sh, eye=meta["eye"])

    glaucoma = meta.get("glaucoma")
    if glaucoma is True:
        row["diagnosis_group"] = ["glaucoma"]
        row["severity"] = "unknown"  # REFUGE2 gives binary label only, no grade
        row["diagnosis_source"] = "expert_label"
    elif glaucoma is False:
        row["diagnosis_group"] = []
        row["severity"] = "none"
        row["diagnosis_source"] = "expert_label"
    else:
        row["diagnosis_source"] = "none"

    row.update({
        "image_id": image_id,
        "file_path": rel_file_path(COHORT, sh, "fundus_color.jpg"),
        "file_format": "jpg",
        "modality": "fundus_color",
        "anatomy": "optic_disc",
        "device_technology": "fundus_camera",
        "scan_protocol": "single_shot",
        "image_height_px": meta["image_height_px"],
        "image_width_px": meta["image_width_px"],
        "has_segmentation": True,
        "n_layers_visible": 0,
        "is_valid": True,
    })

    caps = caption_l1_public(image_id, COHORT_PHRASE, "fundus_color", meta["eye"])
    parts = [f"A color fundus photograph from the REFUGE2 dataset ({meta['split']} split)",
             "with optic disc and optic cup segmentation masks"]
    if glaucoma is True:
        parts.append("glaucomatous eye")
    elif glaucoma is False:
        parts.append("non-glaucomatous eye")
    l3 = ", ".join(parts) + "."
    caps.append(caption_l3_public(image_id, l3, "manifest_fields+disc_cup_mask"))
    return row, caps


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--input-root", required=True,
                    help="Path to .../Generation/REFUGE2 (contains REFUGE2/{train,val,test}/...)")
    ap.add_argument("--output-root", required=True)
    ap.add_argument("--force", action="store_true")
    ap.add_argument("--limit", type=int, default=None)
    args = ap.parse_args()

    in_root = Path(args.input_root)
    out_root = Path(args.output_root)
    rows, caps = [], []
    for split in ("train", "val", "test"):
        img_dir = in_root / "REFUGE2" / split / "images"
        mask_dir = in_root / "REFUGE2" / split / "mask"
        # mask extension differs by split: train/test = .bmp, val = .png
        for ip in sorted(img_dir.glob("*.jpg")):
            stem = ip.stem
            mp = mask_dir / f"{stem}.bmp"
            if not mp.exists():
                mp = mask_dir / f"{stem}.png"
            if not mp.exists():
                print(f"  skip {ip.name}: no mask found")
                continue
            row, cap = process_one(ip, mp, out_root, args.force)
            rows.append(row)
            caps.extend(cap)
            if args.limit and len(rows) >= args.limit:
                break
        if args.limit and len(rows) >= args.limit:
            break

    if not rows:
        print(f"[{COHORT}] no rows")
        return

    mdir = out_root / "manifest"; cdir = out_root / "captions"
    mdir.mkdir(parents=True, exist_ok=True); cdir.mkdir(parents=True, exist_ok=True)
    imgs_df = pd.DataFrame([coerce_image_row(r) for r in rows])[IMAGE_SCHEMA_COLUMNS]
    imgs_df.to_parquet(mdir / f"{COHORT}_images.parquet", index=False)
    caps_df = pd.DataFrame(caps)[CAPTION_SCHEMA_COLUMNS]
    caps_df.to_parquet(cdir / f"{COHORT}_captions.parquet", index=False)
    print(f"[{COHORT}] wrote {len(imgs_df)} images, {len(caps_df)} captions")
    print(imgs_df.groupby(["severity"]).size().to_string())


if __name__ == "__main__":
    main()