Initial upload: public_fundus (198k images, 42 shards) + manifest + captions + code
e2f75d1 verified | #!/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() | |