pose-micro / train /pose_predict.py
eoinedge's picture
PoseMicro from GitHub run 3
ce7fc72 verified
Raw History Blame Contribute Delete
3.53 kB
#!/usr/bin/env python3
# Copyright (c) 2026 Eoin Jordan
# SPDX-License-Identifier: Apache-2.0
"""Find the pose in a picture on a PC, with the program the firmware runs.
The picture is cut to its centre square (or to a square around --box, a
person's x,y,w,h, with the margin the model was trained with), reduced to
96 x 96 and given to firmware/model/pose_micro.pte through the ExecuTorch
Python runtime. Prints the line the firmware would print and, with --out,
saves the square with the skeleton drawn on it.
python train/pose_predict.py person.jpg --out pose.jpg
python train/pose_predict.py street.jpg --box 220,80,140,330 --out pose.jpg
"""
import argparse
import pathlib
import sys
import numpy as np
import torch
from PIL import Image, ImageDraw
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from pose_model import SIDE, SKELETON, THRESHOLD, decode, pose_line # noqa: E402
REPO = pathlib.Path(__file__).resolve().parents[1]
MARGIN = 1.25
LEFT, RIGHT, NOSE, LIMB = (70, 150, 255), (255, 50, 40), (255, 255, 255), (250, 190, 60)
def square(image: Image.Image, box) -> Image.Image:
"""The part of the picture the model is shown."""
if box:
x, y, w, h = box
side = MARGIN * max(w, h)
x0, y0 = x + w / 2 - side / 2, y + h / 2 - side / 2
else:
side = min(image.size)
x0, y0 = (image.width - side) / 2, (image.height - side) / 2
return image.crop((round(x0), round(y0), round(x0 + side), round(y0 + side)))
def draw(picture: Image.Image, kpts: np.ndarray, size: int = 384, threshold: float = THRESHOLD) -> Image.Image:
"""The picture, enlarged, with the keypoints that were found and the limbs between them."""
canvas = picture.resize((size, size), Image.BILINEAR)
pen = ImageDraw.Draw(canvas)
at = [(float(x) * size, float(y) * size) for x, y, _ in kpts]
ok = kpts[:, 2] >= threshold
for a, b in SKELETON:
if ok[a] and ok[b]:
pen.line([at[a], at[b]], fill=LIMB, width=3)
for i, (x, y) in enumerate(at):
if ok[i]:
colour = NOSE if i == 0 else (LEFT if i % 2 else RIGHT)
pen.ellipse([x - 5, y - 5, x + 5, y + 5], fill=colour, outline=(0, 0, 0))
return canvas
def main() -> None:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("picture", type=pathlib.Path)
p.add_argument("--box", help="x,y,w,h of the person in the picture's pixels")
p.add_argument("--pte", type=pathlib.Path, default=REPO / "firmware" / "model" / "pose_micro.pte")
p.add_argument("--out", type=pathlib.Path)
p.add_argument("--threshold", type=float, default=THRESHOLD,
help="heat a keypoint needs to count as found and be drawn (default: %(default)s)")
args = p.parse_args()
from executorch.runtime import Runtime
box = [float(v) for v in args.box.split(",")] if args.box else None
shown = square(Image.open(args.picture).convert("RGB"), box)
small = shown.resize((SIDE, SIDE), Image.BILINEAR)
x = torch.from_numpy(np.asarray(small, np.uint8).copy()).permute(2, 0, 1)[None].float() / 255.0
method = Runtime.get().load_program(args.pte).load_method("forward")
kpts = decode(method.execute([x.contiguous()])[0][0].numpy())
print(pose_line(kpts, threshold=args.threshold))
if args.out:
draw(shown, kpts, threshold=args.threshold).save(args.out)
print(f"wrote {args.out}")
if __name__ == "__main__":
main()