pose-micro / train /pose_data.py
eoinedge's picture
PoseMicro from GitHub run 3
ce7fc72 verified
Raw History Blame Contribute Delete
7.86 kB
#!/usr/bin/env python3
# Copyright (c) 2026 Eoin Jordan
# SPDX-License-Identifier: Apache-2.0
"""Single-person crops from COCO keypoints, for training and scoring PoseMicro.
A crop is a square around one annotated person, 1.25 times the longer side of
the person's box, resized to 112 x 112 (the model takes 96 x 96; the margin is
for the scale and rotation jitter of training). Only people with at least 8
labelled keypoints and a box of 64 pixels or more are taken: a model this
small has nothing to learn from a figure of twenty pixels.
Pictures are fetched one by one from images.cocodataset.org and only the
crops are kept, so the 18 GB archive is never downloaded.
Writes, in train/data/:
pose_<split>.u8 crops, uint8 [n][112][112][3], RGB
pose_<split>_kpts.npy keypoints in crop pixels, float32 [n][17][3]: x, y, v
(v as in COCO: 0 not labelled, 1 hidden, 2 visible)
pose_<split>_meta.json per crop: annotation, picture, licence, scale, area
python train/pose_data.py --split val
python train/pose_data.py --split train # about 49,000 pictures
python train/pose_data.py --split train --minutes 20 # stop early, keep what arrived
"""
import argparse
import concurrent.futures as cf
import io
import json
import pathlib
import random
import sys
import time
import urllib.request
import zipfile
import numpy as np
from PIL import Image
REPO = pathlib.Path(__file__).resolve().parents[1]
DATA = REPO / "train" / "data"
SIDE = 112 # stored crop
MARGIN = 1.25 # crop side over the longer side of the person's box
MIN_KEYPOINTS = 8
MIN_BOX = 64
ANNOTATIONS = "http://images.cocodataset.org/annotations/annotations_trainval2017.zip"
PICTURES = "http://images.cocodataset.org/{split}2017/{name}"
def annotations(split: str) -> dict:
path = DATA / "annotations" / f"person_keypoints_{split}2017.json"
if not path.exists():
DATA.mkdir(parents=True, exist_ok=True)
archive = DATA / "annotations_trainval2017.zip"
if not archive.exists():
print(f"downloading {ANNOTATIONS} (241 MB)")
urllib.request.urlretrieve(ANNOTATIONS, archive)
with zipfile.ZipFile(archive) as z:
for name in z.namelist():
if name.startswith("annotations/person_keypoints_"):
z.extract(name, DATA)
with open(path) as f:
return json.load(f)
def select(coco: dict) -> dict:
"""picture id -> its usable person annotations."""
by_picture = {}
for a in coco["annotations"]:
if a["iscrowd"] or a["num_keypoints"] < MIN_KEYPOINTS or max(a["bbox"][2:]) < MIN_BOX:
continue
by_picture.setdefault(a["image_id"], []).append(a)
return by_picture
def fetch(url: str) -> bytes:
for attempt in range(4):
try:
with urllib.request.urlopen(url, timeout=30) as reply:
return reply.read()
except Exception: # a dropped connection: try again
if attempt == 3:
raise
time.sleep(1 + attempt)
raise RuntimeError("unreachable")
def crops_of(picture: dict, people: list, split: str):
"""[(crop uint8 [112][112][3], keypoints float32 [17][3], meta dict)] for one picture."""
image = Image.open(io.BytesIO(fetch(PICTURES.format(split=split, name=picture["file_name"])))).convert("RGB")
out = []
for a in people:
x, y, w, h = a["bbox"]
side = MARGIN * max(w, h)
x0, y0 = x + w / 2 - side / 2, y + h / 2 - side / 2
box = (round(x0), round(y0), round(x0 + side), round(y0 + side))
scale = SIDE / (box[2] - box[0])
crop = image.crop(box).resize((SIDE, SIDE), Image.BILINEAR) # outside the picture is black
k = np.asarray(a["keypoints"], np.float32).reshape(17, 3).copy()
k[:, 0] = (k[:, 0] - box[0]) * scale
k[:, 1] = (k[:, 1] - box[1]) * scale
k[k[:, 2] == 0, :2] = 0
out.append((np.asarray(crop, np.uint8), k, {
"annotation": a["id"], "picture": picture["id"], "file": picture["file_name"],
"license": picture.get("license"), "flickr_url": picture.get("flickr_url"),
"scale": scale, "area": a["area"], "box": a["bbox"],
}))
return out
def main() -> None:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--split", choices=["train", "val"], required=True)
p.add_argument("--limit", type=int, default=0, help="stop after this many pictures")
p.add_argument("--minutes", type=float, default=0, help="stop after this long and keep what arrived")
p.add_argument("--threads", type=int, default=48)
p.add_argument("--seed", type=int, default=0)
args = p.parse_args()
coco = annotations(args.split)
pictures = {im["id"]: im for im in coco["images"]}
by_picture = select(coco)
order = sorted(by_picture)
random.Random(args.seed).shuffle(order) # so a run stopped early is still an unbiased sample
if args.limit:
order = order[: args.limit]
most = sum(len(by_picture[i]) for i in order)
print(f"{args.split}: {most} people in {len(order)} pictures")
path = DATA / f"pose_{args.split}.u8"
store = np.lib.format.open_memmap(path.with_suffix(".tmp.npy"), "w+", np.uint8, (most, SIDE, SIDE, 3))
kpts = np.zeros((most, 17, 3), np.float32)
meta = []
n = failed = 0
start = shown = time.time()
with cf.ThreadPoolExecutor(args.threads) as pool:
jobs = (pool.submit(crops_of, pictures[i], by_picture[i], args.split) for i in order)
pending = set()
done_pictures = 0
stop = False
for job in jobs:
pending.add(job)
if len(pending) < 4 * args.threads:
continue
finished, pending = cf.wait(pending, return_when=cf.FIRST_COMPLETED)
for f in finished:
done_pictures += 1
try:
for crop, k, m in f.result():
store[n], kpts[n] = crop, k
meta.append(m)
n += 1
except Exception as e:
failed += 1
if failed <= 5:
print(f" a picture failed: {e}", file=sys.stderr)
if time.time() - shown > 30:
shown = time.time()
rate = done_pictures / (shown - start)
print(f" {done_pictures}/{len(order)} pictures, {n} crops, {rate:.0f} pictures/s", flush=True)
if args.minutes and time.time() - start > 60 * args.minutes:
stop = True
break
if stop:
for f in pending:
f.cancel()
for f in cf.as_completed([f for f in pending if not f.cancelled()]):
try:
for crop, k, m in f.result():
store[n], kpts[n] = crop, k
meta.append(m)
n += 1
except Exception:
failed += 1
store.flush()
del store
# keep only the crops that arrived, as a raw file the trainer memory-maps
full = np.load(path.with_suffix(".tmp.npy"), mmap_mode="r")
with open(path, "wb") as f:
for i in range(0, n, 4096):
f.write(np.ascontiguousarray(full[i:min(i + 4096, n)]).tobytes())
del full
path.with_suffix(".tmp.npy").unlink()
np.save(DATA / f"pose_{args.split}_kpts.npy", kpts[:n])
with open(DATA / f"pose_{args.split}_meta.json", "w") as f:
json.dump({"side": SIDE, "margin": MARGIN, "count": n, "crops": meta}, f)
print(f"{args.split}: {n} crops written to {path} in {(time.time() - start) / 60:.1f} min, {failed} pictures failed")
if __name__ == "__main__":
main()