ndl-layout-dataset / scripts /make_metadata.py
nakamura196's picture
Add PID-level (item-level) split and metadata.jsonl
29671af verified
Raw History Blame Contribute Delete
2.22 kB
#!/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)