| |
| |
| """ |
| Unified preprocessing for 7 fundus-image classification datasets. |
| |
| Per dataset it produces: |
| <dataset_root>/ |
| train/<label>/<img> |
| val/<label>/<img> |
| test/<label>/<img> |
| labels.csv (columns: split,filepath,label,class_name,orig_id) |
| and DELETES everything classification-irrelevant (segmentation masks, disc/fovea |
| localization, image-quality columns, extra preprocessing versions, other modalities, |
| upload templates, helper code, original nested folders ...). |
| |
| Split policy (decided with the user): |
| * Datasets WITH a complete official labeled split -> keep it: |
| AIROGS (train/val/test), APTOS (train/val/test), DeepDRiD (train/val/test) |
| * Datasets WITHOUT one -> stratified 7:1:2 (seed=42): |
| MMAC (official has no test -> pool train+val and re-split), |
| ADAM, IDRiD, PAPILA(grouped by patient) |
| Class encodings: |
| MMAC 0..4 myopic-maculopathy grade |
| ADAM 0=Non-AMD 1=AMD |
| AIROGS 0=NRG 1=RG (release-crop version only) |
| PAPILA 0=healthy 1=glaucoma (diagnosis==2 "suspect" dropped; split by patient) |
| IDRiD 0..4 DR grade |
| APTOS 0..4 DR grade |
| DeepDRiD 0..4 DR grade (regular fundus only; per-eye label) |
| |
| Run dry-run first (prints the plan, moves nothing), then with --execute. |
| """ |
| import os, sys, csv, random, shutil |
| from collections import defaultdict |
| import pandas as pd |
|
|
| ROOT = "/mnt/tidal-alsh-share2/dataset/qinshengqian/research/c3/GPT-Image/Dataset" |
| SEED = 42 |
| RATIOS = (0.7, 0.1, 0.2) |
| EXECUTE = "--execute" in sys.argv |
| KEEP = {"train", "val", "test", "labels.csv"} |
|
|
|
|
| |
| def walk_index(root, exts=(".jpg", ".jpeg", ".png", ".tif", ".tiff", ".bmp")): |
| """Map basename-without-extension -> absolute path for every image under root.""" |
| idx = {} |
| for dp, _, files in os.walk(root): |
| for f in files: |
| if f.lower().endswith(exts): |
| idx[os.path.splitext(f)[0]] = os.path.join(dp, f) |
| return idx |
|
|
|
|
| def stratified_split(pairs, ratios=RATIOS, seed=SEED): |
| """pairs: list[(key,label)] -> dict key->split, stratified per label.""" |
| by = defaultdict(list) |
| for k, l in pairs: |
| by[l].append(k) |
| out, rnd = {}, random.Random(seed) |
| for l in sorted(by, key=str): |
| ks = sorted(by[l]) |
| rnd.shuffle(ks) |
| n = len(ks) |
| ntr = int(round(n * ratios[0])) |
| nva = int(round(n * ratios[1])) |
| |
| if n >= 3 and ntr + nva >= n: |
| nva = max(0, n - ntr - 1) |
| for i, k in enumerate(ks): |
| out[k] = "train" if i < ntr else ("val" if i < ntr + nva else "test") |
| return out |
|
|
|
|
| def place(out_dir, records, do_clean_root=True): |
| """records: list of dict(src, split, label, class_name, orig_id). |
| Moves files into out_dir/<split>/<label>/, writes labels.csv, then whitelist-cleans.""" |
| |
| seen, dup = set(), 0 |
| for r in records: |
| key = (r["split"], str(r["label"]), os.path.basename(r["src"])) |
| if key in seen: |
| dup += 1 |
| seen.add(key) |
| counts = defaultdict(int) |
| for r in records: |
| counts[(r["split"], r["label"])] += 1 |
| |
| name = os.path.basename(out_dir.rstrip("/")) |
| total = len(records) |
| print(f" [{name}] total={total} duplicates={dup}") |
| for sp in ("train", "val", "test"): |
| per = {l: c for (s, l), c in sorted(counts.items()) if s == sp} |
| if per: |
| print(f" {sp:5s} n={sum(per.values()):5d} by_class={per}") |
| if dup: |
| print(f" !! {dup} basename collisions in same split/label — aborting this dataset") |
| return |
| if not EXECUTE: |
| return |
| rows = [] |
| for r in records: |
| dd = os.path.join(out_dir, r["split"], str(r["label"])) |
| os.makedirs(dd, exist_ok=True) |
| base = os.path.basename(r["src"]) |
| dst = os.path.join(dd, base) |
| shutil.move(r["src"], dst) |
| rows.append([r["split"], os.path.join(r["split"], str(r["label"]), base), |
| r["label"], r["class_name"], r["orig_id"]]) |
| with open(os.path.join(out_dir, "labels.csv"), "w", newline="") as f: |
| w = csv.writer(f) |
| w.writerow(["split", "filepath", "label", "class_name", "orig_id"]) |
| w.writerows(sorted(rows)) |
| if do_clean_root: |
| for item in os.listdir(out_dir): |
| if item in KEEP: |
| continue |
| p = os.path.join(out_dir, item) |
| shutil.rmtree(p) if os.path.isdir(p) else os.remove(p) |
| print(f" -> moved & cleaned: {out_dir}") |
|
|
|
|
| |
| def do_mmac(): |
| out = os.path.join(ROOT, "Myopia", "Classification_of_Myopic_Maculopathy") |
| base = os.path.join(out, "1. Classification of Myopic Maculopathy") |
| gt = os.path.join(base, "2. Groundtruths") |
| label_map = {} |
| for fn in ["1. MMAC2023_Myopic_Maculopathy_Classification_Training_Labels.csv", |
| "2. MMAC2023_Myopic_Maculopathy_Classification_Validation_Labels.csv"]: |
| df = pd.read_csv(os.path.join(gt, fn)) |
| for _, r in df.iterrows(): |
| label_map[str(r["image"])] = int(r["myopic_maculopathy_grade"]) |
| idx = walk_index(os.path.join(base, "1. Images")) |
| recs, pairs = [], [] |
| for img, g in label_map.items(): |
| key = os.path.splitext(img)[0] |
| if key not in idx: |
| continue |
| pairs.append((key, g)) |
| sp = stratified_split(pairs) |
| for key, g in pairs: |
| recs.append(dict(src=idx[key], split=sp[key], label=g, |
| class_name=f"grade_{g}", orig_id=key)) |
| return out, recs |
|
|
|
|
| def do_adam(): |
| out = os.path.join(ROOT, "AMD", "adamdataset") |
| base = os.path.join(out, "ADAM", "Training400") |
| pairs, srcs = [], {} |
| for sub, lab, cname in [("Non-AMD", 0, "Non-AMD"), ("AMD", 1, "AMD")]: |
| for dp, _, files in os.walk(os.path.join(base, sub)): |
| for f in files: |
| if f.lower().endswith((".jpg", ".jpeg", ".png")): |
| k = os.path.splitext(f)[0] |
| pairs.append((k, lab)) |
| srcs[k] = (os.path.join(dp, f), lab, cname) |
| sp = stratified_split(pairs) |
| recs = [dict(src=srcs[k][0], split=sp[k], label=srcs[k][1], |
| class_name=srcs[k][2], orig_id=k) for k, _ in pairs] |
| return out, recs |
|
|
|
|
| def do_airogs(): |
| out = os.path.join(ROOT, "Glaucoma", "eyepacs-airogs-light") |
| base = os.path.join(out, "release-crop", "release-crop") |
| split_map = {"train": "train", "validation": "val", "test": "test"} |
| cls = {"NRG": (0, "NRG"), "RG": (1, "RG")} |
| recs = [] |
| for osp, nsp in split_map.items(): |
| for c, (lab, cname) in cls.items(): |
| d = os.path.join(base, osp, c) |
| if not os.path.isdir(d): |
| continue |
| for f in os.listdir(d): |
| if f.lower().endswith((".jpg", ".jpeg", ".png")): |
| recs.append(dict(src=os.path.join(d, f), split=nsp, label=lab, |
| class_name=cname, orig_id=os.path.splitext(f)[0])) |
| return out, recs |
|
|
|
|
| def do_papila(): |
| out = os.path.join(ROOT, "Glaucoma", "papila-retinal-fundus-images") |
| base = os.path.join(out, "PapilaDB-PAPILA-17f8fa7746adb20275b5b6a0d99dc9dfe3007e9f") |
| idx = walk_index(os.path.join(base, "FundusImages")) |
| |
| eye_lab = {} |
| for eye, suffix in [("od", "OD"), ("os", "OS")]: |
| df = pd.read_excel(os.path.join(base, "ClinicalData", f"patient_data_{eye}.xlsx"), |
| header=None) |
| for _, r in df.iterrows(): |
| pid = str(r[0]).strip() |
| if not pid.startswith("#"): |
| continue |
| num = int(pid[1:]) |
| diag = r[3] |
| try: |
| diag = int(float(diag)) |
| except (ValueError, TypeError): |
| continue |
| if diag == 2: |
| continue |
| lab = 0 if diag == 0 else 1 |
| key = f"RET{num:03d}{suffix}" |
| if key in idx: |
| eye_lab[key] = (lab, f"RET{num:03d}") |
| |
| pat_lab = defaultdict(int) |
| for k, (lab, pat) in eye_lab.items(): |
| pat_lab[pat] = max(pat_lab[pat], lab) |
| sp = stratified_split(list(pat_lab.items())) |
| recs = [] |
| for k, (lab, pat) in eye_lab.items(): |
| recs.append(dict(src=idx[k], split=sp[pat], label=lab, |
| class_name=("healthy" if lab == 0 else "glaucoma"), orig_id=k)) |
| return out, recs |
|
|
|
|
| def do_idrid(): |
| out = os.path.join(ROOT, "DR", "idrid-dataset") |
| df = pd.read_csv(os.path.join(out, "idrid_labels.csv")) |
| idx = walk_index(os.path.join(out, "Imagenes")) |
| pairs, srcs = [], {} |
| for _, r in df.iterrows(): |
| k = str(r["id_code"]).strip() |
| if k not in idx: |
| continue |
| lab = int(r["diagnosis"]) |
| pairs.append((k, lab)) |
| srcs[k] = lab |
| sp = stratified_split(pairs) |
| recs = [dict(src=idx[k], split=sp[k], label=srcs[k], |
| class_name=f"grade_{srcs[k]}", orig_id=k) for k, _ in pairs] |
| return out, recs |
|
|
|
|
| def do_aptos(): |
| out = os.path.join(ROOT, "DR", "aptos2019") |
| recs = [] |
| for csvname, sp, imgdir in [("train_1.csv", "train", "train_images"), |
| ("valid.csv", "val", "val_images"), |
| ("test.csv", "test", "test_images")]: |
| df = pd.read_csv(os.path.join(out, csvname)) |
| idx = walk_index(os.path.join(out, imgdir)) |
| for _, r in df.iterrows(): |
| k = str(r["id_code"]).strip() |
| if k not in idx: |
| continue |
| lab = int(r["diagnosis"]) |
| recs.append(dict(src=idx[k], split=sp, label=lab, |
| class_name=f"grade_{lab}", orig_id=k)) |
| return out, recs |
|
|
|
|
| def do_deepdrid(): |
| out = os.path.join(ROOT, "DR", "deepdrid") |
| base = os.path.join(out, "DeepDRiD-master", "regular_fundus_images") |
|
|
| def eye_level(row, image_id): |
| col = "left_eye_DR_Level" if "_l" in image_id else "right_eye_DR_Level" |
| v = row.get(col) |
| if pd.isna(v): |
| v = row.get("patient_DR_Level") |
| return None if pd.isna(v) else int(v) |
|
|
| recs = [] |
| |
| for sub, sp in [("regular-fundus-training", "train"), ("regular-fundus-validation", "val")]: |
| d = os.path.join(base, sub) |
| df = pd.read_csv(os.path.join(d, f"{sub}.csv")) |
| idx = walk_index(os.path.join(d, "Images")) |
| for _, r in df.iterrows(): |
| iid = str(r["image_id"]).strip() |
| if iid not in idx: |
| continue |
| lab = eye_level(r, iid) |
| if lab is None or lab < 0 or lab > 4: |
| continue |
| recs.append(dict(src=idx[iid], split=sp, label=lab, |
| class_name=f"grade_{lab}", orig_id=iid)) |
| |
| ev = os.path.join(base, "Online-Challenge1&2-Evaluation") |
| dfx = pd.read_excel(os.path.join(ev, "Challenge1_labels.xlsx")) |
| idx = walk_index(os.path.join(ev, "Images")) |
| col = "DR_Levels" if "DR_Levels" in dfx.columns else dfx.columns[-1] |
| for _, r in dfx.iterrows(): |
| iid = str(r["image_id"]).strip() |
| if iid not in idx or pd.isna(r[col]): |
| continue |
| lab = int(r[col]) |
| if 0 <= lab <= 4: |
| recs.append(dict(src=idx[iid], split="test", label=lab, |
| class_name=f"grade_{lab}", orig_id=iid)) |
| return out, recs |
|
|
|
|
| DATASETS = [("MMAC/Myopia", do_mmac), ("ADAM/AMD", do_adam), |
| ("AIROGS/Glaucoma", do_airogs), ("PAPILA/Glaucoma", do_papila), |
| ("IDRiD/DR", do_idrid), ("APTOS/DR", do_aptos), ("DeepDRiD/DR", do_deepdrid)] |
|
|
|
|
| def main(): |
| only = [a for a in sys.argv[1:] if not a.startswith("--")] |
| print(f"=== prepare_datasets ({'EXECUTE' if EXECUTE else 'DRY-RUN'}) seed={SEED} ===") |
| for name, fn in DATASETS: |
| if only and name.split("/")[0].lower() not in [o.lower() for o in only]: |
| continue |
| print(f"\n### {name}") |
| out, recs = fn() |
| place(out, recs) |
| print("\n=== done ===") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|