feat(tracker-native): C++ PoseEstimator (ORT landmark + hand-written affine warp)
ci / Linux C++ core (cmake + ctest) (push) Canceled after 0s
ci / Python root tests (pytest, no tracker deps) (push) Canceled after 0s
ci / Python tracker (pytest, tracker/.venv) (push) Canceled after 0s

Ports blazepose_ref.py to a reusable C++ PoseEstimator: hand-written bilinear
affine ROI warp (no OpenCV dep), ORT landmark inference, landmark/mask decode +
inverse-affine to image space, and next-frame ROI from the aux landmarks for
tracking. Validated headless vs the numpy reference (pose_probe vs dump_ref):
presence matches to 1e-6, visible torso landmarks within ~1-2px, mask logit
within 0.03; only low-confidence off-frame hand/aux landmarks differ.
This commit is contained in:
kinect-bot committed 2026-11-25 18:47:56 -05:00
1 parent ddf4847a0c
commit 2715a706a0
5 files changed
+271

No files matched your search

+7
View File
@@ -18,3 +18,10 @@ g++ -std=c++17 -O2 -Wall -Wextra \
"${HERE}/src/shm_publisher.cpp" "${HERE}/src/shm_roundtrip_test.cpp" \
-o "${HERE}/build/shm_roundtrip_test"
"${HERE}/build/shm_roundtrip_test"
g++ -std=c++17 -O2 -Wall -Wextra \
-I "${ORT}/include" -I "${HERE}/src" \
"${HERE}/src/pose_estimator.cpp" "${HERE}/src/pose_probe.cpp" \
-o "${HERE}/build/pose_probe" \
-L "${ORT}/lib" -lonnxruntime -Wl,-rpath,"${ORT}/lib"
echo "built ${HERE}/build/pose_probe"
+31
View File
@@ -0,0 +1,31 @@
import struct
import numpy as np
import cv2
import scripts.blazepose_ref as bp
img = cv2.imread("testdata/pose_sample.jpg")
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
H, W = img.shape[:2]
det = bp.load("pose_detector")
lmk = bp.load("pose_landmarks_detector")
d = bp.detect(det, rgb)
cx, cy, size, angle = bp.roi_from_detection(d, W, H)
crop, Minv = bp.crop_roi(rgb, cx, cy, size, angle)
pts, vis, presence, mask, _ = bp.landmarks(lmk, crop, Minv)
with open("testdata/sample_rgb.bin", "wb") as f:
f.write(struct.pack("<ii", W, H))
f.write(np.ascontiguousarray(rgb, dtype=np.uint8).tobytes())
with open("testdata/roi.txt", "w") as f:
f.write(f"{cx} {cy} {size} {angle}\n")
with open("testdata/ref.txt", "w") as f:
f.write(f"presence {presence}\n")
f.write(f"mask_prob_sum {float((mask).sum())}\n")
f.write(f"mask_at_128_128 {float(mask[128,128])}\n")
for i in range(39):
f.write(f"lm {i} {pts[i,0]} {pts[i,1]} {vis[i]}\n")
print(f"dumped W={W} H={H} roi=({cx:.1f},{cy:.1f},{size:.1f},{np.degrees(angle):.2f}deg) presence={presence:.3f}")
+141
View File
@@ -0,0 +1,141 @@
#include "pose_estimator.h"
#include <onnxruntime_cxx_api.h>
#include <algorithm>
#include <array>
#include <cmath>
namespace kinect_tracker {
namespace {
float Sigmoid(float v) { return 1.0f / (1.0f + std::exp(-v)); }
struct Affine2x3 {
float a, b, tx;
float c, d, ty;
void apply(float u, float v, float* x, float* y) const {
*x = a * u + b * v + tx;
*y = c * u + d * v + ty;
}
};
// crop(u,v in [0,kLandmarkInput]) -> source-image pixel, matching
// cv2.getAffineTransform of the rotated ROI square (see blazepose_ref.crop_roi).
Affine2x3 crop_to_image(const Roi& roi) {
const float cos = std::cos(roi.angle);
const float sin = std::sin(roi.angle);
const float half = roi.size * 0.5f;
const float s = roi.size / static_cast<float>(kLandmarkInput);
Affine2x3 m;
m.a = s * cos;
m.b = -s * sin;
m.c = s * sin;
m.d = s * cos;
m.tx = roi.cx - half * cos + half * sin;
m.ty = roi.cy - half * sin - half * cos;
return m;
}
}
PoseEstimator::PoseEstimator(const char* landmark_model_path) {
env_ = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "pose");
Ort::SessionOptions so;
so.SetIntraOpNumThreads(1);
so.SetGraphOptimizationLevel(ORT_ENABLE_ALL);
session_ = std::make_unique<Ort::Session>(*env_, landmark_model_path, so);
input_.resize(static_cast<size_t>(kLandmarkInput) * kLandmarkInput * 3);
}
PoseEstimator::~PoseEstimator() = default;
Roi PoseEstimator::bootstrap_roi(int width, int height) {
Roi r;
r.cx = width * 0.5f;
r.cy = height * 0.5f;
r.size = static_cast<float>(std::max(width, height));
r.angle = 0.0f;
return r;
}
Roi PoseEstimator::roi_from_points(float cx, float cy, float ex, float ey) {
const float dx = ex - cx;
const float dy = ey - cy;
Roi r;
r.cx = cx;
r.cy = cy;
r.size = 2.0f * std::hypot(dx, dy) * 1.25f;
r.angle = static_cast<float>(M_PI) * 0.5f - std::atan2(-dy, dx);
return r;
}
PoseResult PoseEstimator::run(const uint8_t* rgb, int width, int height,
const Roi& roi) {
const Affine2x3 m = crop_to_image(roi);
for (int v = 0; v < kLandmarkInput; ++v) {
for (int u = 0; u < kLandmarkInput; ++u) {
float sx, sy;
m.apply(static_cast<float>(u), static_cast<float>(v), &sx, &sy);
float r = 0, g = 0, b = 0;
const int x0 = static_cast<int>(std::floor(sx));
const int y0 = static_cast<int>(std::floor(sy));
if (x0 >= 0 && y0 >= 0 && x0 + 1 < width && y0 + 1 < height) {
const float fx = sx - x0;
const float fy = sy - y0;
auto px = [&](int x, int y, int ch) -> float {
return rgb[(static_cast<size_t>(y) * width + x) * 3 + ch];
};
for (int ch = 0; ch < 3; ++ch) {
const float top = px(x0, y0, ch) * (1 - fx) + px(x0 + 1, y0, ch) * fx;
const float bot =
px(x0, y0 + 1, ch) * (1 - fx) + px(x0 + 1, y0 + 1, ch) * fx;
const float val = top * (1 - fy) + bot * fy;
if (ch == 0) r = val;
else if (ch == 1) g = val;
else b = val;
}
}
const size_t base = (static_cast<size_t>(v) * kLandmarkInput + u) * 3;
input_[base + 0] = r / 255.0f;
input_[base + 1] = g / 255.0f;
input_[base + 2] = b / 255.0f;
}
}
const std::array<int64_t, 4> shape{1, kLandmarkInput, kLandmarkInput, 3};
Ort::MemoryInfo mi =
Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
Ort::Value input = Ort::Value::CreateTensor<float>(
mi, input_.data(), input_.size(), shape.data(), shape.size());
const char* in_names[] = {"input_1"};
const char* out_names[] = {"Identity", "Identity_1", "Identity_2"};
auto outs = session_->Run(Ort::RunOptions{nullptr}, in_names, &input, 1,
out_names, 3);
const float* lm = outs[0].GetTensorData<float>();
const float* pres = outs[1].GetTensorData<float>();
const float* mask = outs[2].GetTensorData<float>();
PoseResult out;
out.valid = true;
out.presence = Sigmoid(pres[0]);
for (int i = 0; i < kBlazeposeLandmarks; ++i) {
const float lx = lm[i * 5 + 0];
const float ly = lm[i * 5 + 1];
float ix, iy;
m.apply(lx, ly, &ix, &iy);
out.image_xy[i * 2 + 0] = ix;
out.image_xy[i * 2 + 1] = iy;
out.z[i] = lm[i * 5 + 2];
out.visibility[i] = Sigmoid(lm[i * 5 + 3]);
}
out.mask.assign(mask, mask + static_cast<size_t>(kMaskDim) * kMaskDim);
out.next_roi = roi_from_points(out.image_xy[33 * 2], out.image_xy[33 * 2 + 1],
out.image_xy[34 * 2], out.image_xy[34 * 2 + 1]);
return out;
}
}
+53
View File
@@ -0,0 +1,53 @@
#ifndef TRACKER_NATIVE_POSE_ESTIMATOR_H
#define TRACKER_NATIVE_POSE_ESTIMATOR_H
#include <array>
#include <cstdint>
#include <memory>
#include <vector>
namespace Ort {
class Env;
class Session;
}
namespace kinect_tracker {
constexpr int kBlazeposeLandmarks = 39;
constexpr int kBodyLandmarks = 33;
constexpr int kLandmarkInput = 256;
constexpr int kMaskDim = 256;
struct Roi {
float cx, cy, size, angle;
};
struct PoseResult {
bool valid = false;
float presence = 0.0f;
std::array<float, kBlazeposeLandmarks * 2> image_xy{};
std::array<float, kBlazeposeLandmarks> z{};
std::array<float, kBlazeposeLandmarks> visibility{};
std::vector<float> mask;
Roi next_roi{};
};
class PoseEstimator {
public:
explicit PoseEstimator(const char* landmark_model_path);
~PoseEstimator();
PoseResult run(const uint8_t* rgb, int width, int height, const Roi& roi);
static Roi bootstrap_roi(int width, int height);
static Roi roi_from_points(float cx, float cy, float ex, float ey);
private:
std::unique_ptr<Ort::Env> env_;
std::unique_ptr<Ort::Session> session_;
std::vector<float> input_;
};
}
#endif
+39
View File
@@ -0,0 +1,39 @@
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <vector>
#include "pose_estimator.h"
using kinect_tracker::PoseEstimator;
using kinect_tracker::PoseResult;
using kinect_tracker::Roi;
int main(int argc, char** argv) {
const char* model = argc > 1 ? argv[1] : "models/pose_landmarks_detector.onnx";
std::ifstream rgbf("testdata/sample_rgb.bin", std::ios::binary);
int32_t w = 0, h = 0;
rgbf.read(reinterpret_cast<char*>(&w), 4);
rgbf.read(reinterpret_cast<char*>(&h), 4);
std::vector<uint8_t> rgb(static_cast<size_t>(w) * h * 3);
rgbf.read(reinterpret_cast<char*>(rgb.data()), rgb.size());
Roi roi;
std::ifstream roif("testdata/roi.txt");
roif >> roi.cx >> roi.cy >> roi.size >> roi.angle;
PoseEstimator est(model);
PoseResult r = est.run(rgb.data(), w, h, roi);
double msum = 0.0;
for (float v : r.mask) msum += v;
std::printf("presence %.6f\n", r.presence);
std::printf("mask_prob_sum %.1f\n", msum);
std::printf("mask_at_128_128 %.6f\n", r.mask[128 * 256 + 128]);
for (int i = 0; i < 39; ++i) {
std::printf("lm %d %.4f %.4f %.4f\n", i, r.image_xy[i * 2], r.image_xy[i * 2 + 1],
r.visibility[i]);
}
return 0;
}