File size: 2,218 Bytes
29671af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""data/images/<split>/metadata.jsonl を作る。

Usage:
    python3 scripts/make_metadata.py .        # リポジトリのルートで実行する

YOLO の正規化座標 (cx cy w h) を、HF imagefolder が期待する COCO 形式の
絶対座標 (x y w h) に直して書き出す。先に make_pid_split.py を実行して
data/pid_assignment.json を作っておくこと。
"""
import json, sys
from pathlib import Path
from PIL import Image

ROOT = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
NAMES = ["1_overall", "2_handwritten", "3_typography", "4_illustration", "5_stamp"]
assign = json.load(open(ROOT / "data/pid_assignment.json"))  # PID -> split

total = 0
for split in ("train", "val", "test"):
    d = ROOT / "data/images" / split
    rows = []
    for img in sorted(d.glob("*.jpg")):
        with Image.open(img) as im:
            W, H = im.size
        lab = ROOT / "data/labels" / split / (img.stem + ".txt")
        bbox, cats = [], []
        for line in lab.read_text().splitlines():
            line = line.strip()
            if not line:
                continue
            c, cx, cy, w, h = line.split()
            c = int(c)
            cx, cy, w, h = float(cx) * W, float(cy) * H, float(w) * W, float(h) * H
            x0 = max(0.0, cx - w / 2); y0 = max(0.0, cy - h / 2)
            x1 = min(float(W), cx + w / 2); y1 = min(float(H), cy + h / 2)
            bbox.append([round(x0, 2), round(y0, 2), round(x1 - x0, 2), round(y1 - y0, 2)])
            cats.append(c)
        pid, page = img.stem.split("_", 1)
        rows.append({
            "file_name": img.name,
            "objects": {"bbox": bbox, "categories": cats},
            "category_names": [NAMES[c] for c in cats],
            "pid": pid,
            "page": page,
            "width": W,
            "height": H,
            "num_objects": len(cats),
            "pid_split": assign[pid],
        })
    (d / "metadata.jsonl").write_text(
        "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows))
    total += sum(r["num_objects"] for r in rows)
    print(f"{split:5s} {len(rows):4d} 画像 / {sum(r['num_objects'] for r in rows):6d} 矩形")
print("矩形 合計:", total)