"""Reference BlazePose pipeline (detector + landmark) on the real MediaPipe TFLite weights, implemented from the MediaPipe graph so it can be ported to C++ 1:1. MediaPipe's own Tasks runtime can't load here (needs libGLESv2), so this reproduces pose_detection_cpu + pose_landmark_by_roi directly and is validated geometrically (landmarks must land on the person). """ import math import sys import cv2 import numpy as np import tensorflow as tf MODELS = "models" def load(name): it = tf.lite.Interpreter(model_path=f"{MODELS}/{name}.tflite") it.allocate_tensors() return it def run(it, x): inp = it.get_input_details()[0] it.set_tensor(inp["index"], x.astype(np.float32)) it.invoke() return [it.get_tensor(o["index"]) for o in it.get_output_details()] def gen_anchors(): # SsdAnchorsCalculator options from pose_detection_cpu. num_layers = 5 min_scale, max_scale = 0.1484375, 0.75 strides = [8, 16, 32, 32, 32] in_h = in_w = 224 off = 0.5 anchors = [] layer = 0 while layer < num_layers: aspect = [] last = layer while last < num_layers and strides[last] == strides[layer]: aspect.append(1.0) # one aspect ratio # interpolated_scale_aspect_ratio == 1.0 -> one extra anchor aspect.append(1.0) last += 1 fm_h = math.ceil(in_h / strides[layer]) fm_w = math.ceil(in_w / strides[layer]) for y in range(fm_h): for x in range(fm_w): for _ in aspect: cx = (x + off) / fm_w cy = (y + off) / fm_h anchors.append((cx, cy)) layer = last return np.array(anchors, np.float32) # [N,2] def detect(det, img_rgb): h, w = img_rgb.shape[:2] scale = 224.0 / max(h, w) nh, nw = int(round(h * scale)), int(round(w * scale)) resized = cv2.resize(img_rgb, (nw, nh)) pad = np.zeros((224, 224, 3), np.uint8) pad[:nh, :nw] = resized x = (pad.astype(np.float32) / 255.0) * 2.0 - 1.0 # [-1,1] reg, score = run(det, x[None]) reg, score = reg[0], score[0, :, 0] anchors = gen_anchors() prob = 1.0 / (1.0 + np.exp(-np.clip(score, -100, 100))) # decode boxes/keypoints in 224 letterboxed space (normalized 0..1) cx = reg[:, 0] / 224.0 + anchors[:, 0] cy = reg[:, 1] / 224.0 + anchors[:, 1] bw = reg[:, 2] / 224.0 bh = reg[:, 3] / 224.0 # keypoints 0 (mid-hip) and 1 (scale/rotation point) kp0x = reg[:, 4] / 224.0 + anchors[:, 0] kp0y = reg[:, 5] / 224.0 + anchors[:, 1] kp1x = reg[:, 6] / 224.0 + anchors[:, 0] kp1y = reg[:, 7] / 224.0 + anchors[:, 1] best = int(np.argmax(prob)) det_out = dict( prob=float(prob[best]), cx=cx[best], cy=cy[best], bw=bw[best], bh=bh[best], kp0=(kp0x[best], kp0y[best]), kp1=(kp1x[best], kp1y[best]), letter_scale=scale, nw=nw, nh=nh, ) return det_out def roi_from_detection(d, img_w, img_h): # keypoints are in letterboxed-normalized [0,1] over 224; convert to image px def to_px(pt): return (pt[0] * 224.0 / d["letter_scale"], pt[1] * 224.0 / d["letter_scale"]) k0 = to_px(d["kp0"]) k1 = to_px(d["kp1"]) cx, cy = k0 dx, dy = k1[0] - k0[0], k1[1] - k0[1] box = 2.0 * math.hypot(dx, dy) # target angle 90deg: rotate so k0->k1 points up angle = math.pi * 0.5 - math.atan2(-dy, dx) # RectTransformation: scale 1.25, square_long box *= 1.25 return cx, cy, box, angle def crop_roi(img, cx, cy, size, angle, out=256): cos, sin = math.cos(angle), math.sin(angle) R = np.array([[cos, -sin], [sin, cos]], np.float32) half = size / 2.0 c = np.array([cx, cy], np.float32) tl = c + R @ np.array([-half, -half], np.float32) tr = c + R @ np.array([half, -half], np.float32) br = c + R @ np.array([half, half], np.float32) src = np.stack([tl, tr, br]).astype(np.float32) dst = np.array([[0, 0], [out, 0], [out, out]], np.float32) M = cv2.getAffineTransform(src, dst) crop = cv2.warpAffine(img, M, (out, out), flags=cv2.INTER_LINEAR) Minv = cv2.invertAffineTransform(M) return crop, Minv def landmarks(lmk, crop_rgb, Minv, out=256): x = crop_rgb.astype(np.float32) / 255.0 # [0,1] o = run(lmk, x[None]) raw = o[0][0].reshape(39, 5) # x,y,z,vis,presence in crop pixels presence = 1.0 / (1.0 + math.exp(-float(o[1][0, 0]))) mask = o[2][0, :, :, 0] pts = raw[:, :2] # [0,256] crop px ones = np.ones((39, 1), np.float32) img_pts = (np.hstack([pts, ones]) @ Minv.T) # back to image px vis = 1.0 / (1.0 + np.exp(-raw[:, 3])) return img_pts, vis, presence, mask, Minv def main(): img = cv2.imread("testdata/pose_sample.jpg") rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) H, W = img.shape[:2] det = load("pose_detector") lmk = load("pose_landmarks_detector") d = detect(det, rgb) print(f"detect prob={d['prob']:.3f} kp0={d['kp0']} kp1={d['kp1']}") cx, cy, size, angle = roi_from_detection(d, W, H) print(f"roi center=({cx:.0f},{cy:.0f}) size={size:.0f} angle={math.degrees(angle):.1f}deg") crop, Minv = crop_roi(rgb, cx, cy, size, angle) img_pts, vis, presence, mask, _ = landmarks(lmk, crop, Minv) print(f"presence={presence:.3f} landmarks in image px, first 5:") for i in range(5): print(f" lm{i}: ({img_pts[i,0]:.0f},{img_pts[i,1]:.0f}) vis={vis[i]:.2f}") ov = img.copy() for i in range(33): x, y = int(img_pts[i, 0]), int(img_pts[i, 1]) col = (0, 255, 0) if vis[i] > 0.5 else (0, 128, 255) cv2.circle(ov, (x, y), 4, col, -1) # mask overlay back to image maskimg = cv2.warpAffine((mask * 255).astype(np.uint8), Minv, (W, H)) red = np.zeros_like(ov) red[:, :, 2] = maskimg ov = cv2.addWeighted(ov, 1.0, red, 0.4, 0) cv2.imwrite("testdata/overlay.png", ov) print("wrote testdata/overlay.png") if __name__ == "__main__": sys.exit(main())