File size: 1,900 Bytes
a852516
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Create ImageFolder symlink views for Kermany2018 from master_labels.csv."""
from __future__ import annotations

import argparse
import os
from pathlib import Path

import pandas as pd


CLASSES = ["CNV", "DME", "DRUSEN", "NORMAL"]


def safe_name(src: Path, i: int) -> str:
    return f"{i:08d}_{src.name}"


def build_split(df: pd.DataFrame, split: str, out_root: Path) -> int:
    sub = df[df["split"] == split].reset_index(drop=True)
    total = 0
    for cls in CLASSES:
        cls_dir = out_root / split / cls
        cls_dir.mkdir(parents=True, exist_ok=True)
        rows = sub[sub["dx"] == cls].reset_index(drop=True)
        for i, row in rows.iterrows():
            src = Path(row["image_path"])
            dst = cls_dir / safe_name(src, i)
            if dst.exists() or dst.is_symlink():
                continue
            os.symlink(src, dst)
            total += 1
    return total


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--labels-csv",
        type=Path,
        default=Path("/data/temp/qinshengqian/c3/kermany_downstream/master_labels.csv"),
    )
    parser.add_argument(
        "--out-root",
        type=Path,
        default=Path("/data/temp/qinshengqian/c3/kermany_imagefolder"),
    )
    args = parser.parse_args()

    df = pd.read_csv(args.labels_csv)
    df = df[df["dx"].isin(CLASSES)].copy()
    args.out_root.mkdir(parents=True, exist_ok=True)

    for split in ["train", "val", "test"]:
        added = build_split(df, split, args.out_root)
        print(f"{split}: added {added}")

    for split in ["train", "val", "test"]:
        print(f"\n{split}")
        for cls in CLASSES:
            n = len(list((args.out_root / split / cls).glob("*")))
            print(f"  {cls}: {n}")
    print(f"\nKERMANY_IMAGEFOLDER_READY {args.out_root}")


if __name__ == "__main__":
    main()