File size: 5,557 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
#!/usr/bin/env python3
"""
DRIVE adapter — vessel segmentation public dataset.

Inputs:
    {input_root}/DRIVE/training/images/NN_training.tif       (20 files)
    {input_root}/DRIVE/training/1st_manual/NN_manual1.gif    (vessel GT)
    {input_root}/DRIVE/training/mask/NN_training_mask.gif    (FOV mask)

Outputs (under {output_root}):
    extracted/public_drive_vessel/{hash[:2]}/{hash}/
        fundus_color.jpg     (re-encoded from .tif)
        vessel_mask.png      (binary 0/255, from 1st_manual)
        fov_mask.png         (binary 0/255, from mask/)
        meta.json
    manifest/public_drive_vessel_images.parquet
    captions/public_drive_vessel_captions.parquet

Test split (also 20 images) intentionally skipped — it lacks vessel GT, only FOV mask.
"""
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_drive_vessel"
COHORT_PHRASE = "DRIVE retinal vessel segmentation dataset"


def _binarize(p: Path) -> np.ndarray:
    arr = np.array(Image.open(p).convert("L"))
    return ((arr > 127).astype(np.uint8) * 255)


def process_one(image_path: Path, vessel_path: Path, fov_path: Path,
                out_root: Path, force: bool):
    basename = image_path.stem  # "21_training"
    sh = study_hash_for(COHORT, basename)
    sdir = study_dir_for(out_root, COHORT, sh)
    sdir.mkdir(parents=True, exist_ok=True)

    meta_path = sdir / "meta.json"
    if meta_path.exists() and not force:
        try:
            meta = json.loads(meta_path.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)

    Image.fromarray(_binarize(vessel_path), mode="L").save(
        sdir / "vessel_mask.png", "PNG", optimize=True)
    Image.fromarray(_binarize(fov_path), mode="L").save(
        sdir / "fov_mask.png", "PNG", optimize=True)

    meta = {
        "status": "ok",
        "cohort": COHORT,
        "study_hash": sh,
        "source_basename": basename,
        "image_height_px": int(h),
        "image_width_px": int(w),
        "has_vessel_mask": True,
        "has_fov_mask": True,
        "eye": "unknown",
    }
    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"])
    row.update({
        "image_id": image_id,
        "file_path": rel_file_path(COHORT, sh, "fundus_color.jpg"),
        "file_format": "jpg",
        "modality": "fundus_color",
        "anatomy": "macula",
        "device_technology": "fundus_camera",
        "scan_protocol": "single_shot",
        "image_height_px": int(meta["image_height_px"]),
        "image_width_px": int(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"])
    l3 = ("A color fundus photograph from the DRIVE dataset, "
          "with manually annotated retinal vessel segmentation mask and field-of-view mask.")
    caps.append(caption_l3_public(image_id, l3, "manifest_fields+vessel_mask"))
    return row, caps


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--input-root", required=True,
                    help="Path to .../Generation/DRIVE (contains DRIVE/training/...)")
    ap.add_argument("--output-root", required=True,
                    help="Public manifest root, e.g. .../c3/public_eye_pretrain")
    ap.add_argument("--force", action="store_true")
    args = ap.parse_args()

    in_root = Path(args.input_root)
    out_root = Path(args.output_root)
    train_dir = in_root / "DRIVE" / "training"
    img_dir = train_dir / "images"
    vessel_dir = train_dir / "1st_manual"
    fov_dir = train_dir / "mask"

    img_files = sorted(img_dir.glob("*_training.tif"))
    print(f"[{COHORT}] {len(img_files)} training images under {img_dir}")

    rows, caps = [], []
    for ip in img_files:
        stem = ip.stem.replace("_training", "")
        vp = vessel_dir / f"{stem}_manual1.gif"
        fp = fov_dir / f"{stem}_training_mask.gif"
        if not (vp.exists() and fp.exists()):
            print(f"  skip {ip.name}: vessel={vp.exists()}, fov={fp.exists()}")
            continue
        row, cap = process_one(ip, vp, fp, out_root, args.force)
        rows.append(row)
        caps.extend(cap)

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

    manifest_dir = out_root / "manifest"
    captions_dir = out_root / "captions"
    manifest_dir.mkdir(parents=True, exist_ok=True)
    captions_dir.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(manifest_dir / f"{COHORT}_images.parquet", index=False)

    caps_df = pd.DataFrame(caps)[CAPTION_SCHEMA_COLUMNS]
    caps_df.to_parquet(captions_dir / f"{COHORT}_captions.parquet", index=False)

    print(f"[{COHORT}] wrote {len(imgs_df)} image rows, {len(caps_df)} caption rows")


if __name__ == "__main__":
    main()