forked from dsutanto/nuclio-handler
252 lines
8.3 KiB
Python
252 lines
8.3 KiB
Python
"""Nuclio handler for CVAT automatic pose annotation using OpenVINO IR model.
|
||
|
||
Loads a single-person pose estimation model (e.g. Human Pose Estimation,
|
||
HRNet, OpenPose) exported to OpenVINO IR (.xml / .bin). The handler
|
||
returns keypoint annotations in CVAT-compatible format.
|
||
|
||
Environment variables
|
||
---------------------
|
||
MODEL_XML : path to the .xml file (default: /models/pose_model.xml)
|
||
MODEL_BIN : path to the .bin file (default: /models/pose_model.bin)
|
||
CONF_THRESHOLD : minimum keypoint confidence (default: 0.3)
|
||
KEYPOINTS_FILE : path to JSON file with keypoint labels (default: keypoints.json)
|
||
SKELETON_FILE : path to JSON file with skeleton edges (default: skeleton.json)
|
||
OUTPUT_TYPE : "skeleton" or "points" – how to return shapes (default: "skeleton")
|
||
"""
|
||
|
||
import base64
|
||
import json
|
||
import os
|
||
from pathlib import Path
|
||
|
||
import cv2
|
||
import numpy as np
|
||
import openvino as ov
|
||
from openvino.preprocess import PrePostProcessor
|
||
from openvino.preprocess import ColorFormat
|
||
from openvino import Layout, Type
|
||
|
||
MODEL_XML = os.getenv("MODEL_XML", "/models/best.xml")
|
||
MODEL_BIN = os.getenv("MODEL_BIN", "/models/best.bin")
|
||
CONF_THRESHOLD = float(os.getenv("CONF_THRESHOLD", "0.3"))
|
||
OUTPUT_TYPE = os.getenv("OUTPUT_TYPE", "skeleton")
|
||
|
||
_COCO_KEYPOINTS = [
|
||
"nose", "left_eye", "right_eye", "left_ear", "right_ear",
|
||
"left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
|
||
"left_wrist", "right_wrist", "left_hip", "right_hip",
|
||
"left_knee", "right_knee", "left_ankle", "right_ankle",
|
||
]
|
||
|
||
_COCO_SKELETON = [
|
||
[15, 13], [13, 11], [16, 14], [14, 12], [11, 12],
|
||
[5, 11], [6, 12], [5, 6], [5, 7], [6, 8],
|
||
[7, 9], [8, 10], [1, 2], [0, 1], [0, 2],
|
||
[1, 3], [2, 4], [3, 5], [4, 6],
|
||
]
|
||
|
||
|
||
def _load_json_list(env_var, fallback):
|
||
path = os.getenv(env_var, "")
|
||
if path and os.path.isfile(path):
|
||
with open(path, "r") as fh:
|
||
return json.load(fh)
|
||
return fallback
|
||
|
||
|
||
KEYPOINT_LABELS = _load_json_list("KEYPOINTS_FILE", _COCO_KEYPOINTS)
|
||
SKELETON_EDGES = _load_json_list("SKELETON_FILE", _COCO_SKELETON)
|
||
|
||
|
||
class PoseEstimator:
|
||
def __init__(self, xml_path=MODEL_XML, bin_path=MODEL_BIN, conf=CONF_THRESHOLD):
|
||
core = ov.Core()
|
||
if os.path.isfile(bin_path):
|
||
model = core.read_model(str(Path(xml_path)), str(Path(bin_path)))
|
||
else:
|
||
model = core.read_model(str(Path(xml_path)))
|
||
|
||
ppp = PrePostProcessor(model)
|
||
ppp.input().tensor().set_element_type(Type.u8).set_layout(
|
||
Layout("NHWC")
|
||
).set_color_format(ColorFormat.BGR)
|
||
ppp.input().preprocess().convert_element_type(Type.f32).convert_color(
|
||
ColorFormat.RGB
|
||
).scale([255.0, 255.0, 255.0])
|
||
ppp.input().model().set_layout(Layout("NCHW"))
|
||
ppp.output().tensor().set_element_type(Type.f32)
|
||
model = ppp.build()
|
||
|
||
self.compiled_model = core.compile_model(model, "CPU")
|
||
input_shape = self.compiled_model.input(0).shape
|
||
self.input_height = input_shape[2]
|
||
self.input_width = input_shape[3]
|
||
self.conf = conf
|
||
|
||
def resize_and_pad(self, image):
|
||
old_h, old_w = image.shape[:2]
|
||
ratio = min(self.input_width / old_w, self.input_height / old_h)
|
||
new_w = int(old_w * ratio)
|
||
new_h = int(old_h * ratio)
|
||
|
||
image = cv2.resize(image, (new_w, new_h))
|
||
|
||
delta_w = self.input_width - new_w
|
||
delta_h = self.input_height - new_h
|
||
|
||
padded = cv2.copyMakeBorder(
|
||
image, 0, delta_h, 0, delta_w, cv2.BORDER_CONSTANT, value=(100, 100, 100)
|
||
)
|
||
return padded, delta_w, delta_h
|
||
|
||
def predict(self, img, delta_w, delta_h, orig_shape):
|
||
input_tensor = np.expand_dims(img, 0)
|
||
|
||
infer_request = self.compiled_model.create_infer_request()
|
||
infer_request.infer({0: input_tensor})
|
||
output = infer_request.get_output_tensor().data
|
||
|
||
return self._postprocess(output, delta_w, delta_h, orig_shape)
|
||
|
||
def _postprocess(self, output, delta_w, delta_h, orig_shape):
|
||
"""Extract keypoints depending on output tensor shape.
|
||
|
||
- 4‑D [1, K, H, W] → heatmap‑based; argmax per channel.
|
||
- 3‑D [1, K, 3] / [1, K, 2] → direct coordinate regression.
|
||
"""
|
||
orig_h, orig_w = orig_shape[:2]
|
||
rx = orig_w / (self.input_width - delta_w)
|
||
ry = orig_h / (self.input_height - delta_h)
|
||
|
||
if output.ndim == 4:
|
||
return self._heatmap_keypoints(output, rx, ry)
|
||
return self._direct_keypoints(output, rx, ry)
|
||
|
||
def _heatmap_keypoints(self, heatmaps, rx, ry):
|
||
keypoints = []
|
||
for i in range(heatmaps.shape[1]):
|
||
hmap = heatmaps[0, i]
|
||
_, conf, _, loc = cv2.minMaxLoc(hmap)
|
||
label = KEYPOINT_LABELS[i] if i < len(KEYPOINT_LABELS) else f"kp_{i}"
|
||
keypoints.append({
|
||
"label": label,
|
||
"x": float(loc[0] * rx),
|
||
"y": float(loc[1] * ry),
|
||
"conf": float(conf),
|
||
})
|
||
return keypoints
|
||
|
||
def _direct_keypoints(self, output, rx, ry):
|
||
keypoints = []
|
||
has_conf = output.shape[2] >= 3
|
||
for i in range(output.shape[1]):
|
||
label = KEYPOINT_LABELS[i] if i < len(KEYPOINT_LABELS) else f"kp_{i}"
|
||
x = output[0, i, 0] * rx
|
||
y = output[0, i, 1] * ry
|
||
conf = float(output[0, i, 2]) if has_conf else 1.0
|
||
keypoints.append({
|
||
"label": label,
|
||
"x": float(x),
|
||
"y": float(y),
|
||
"conf": conf,
|
||
})
|
||
return keypoints
|
||
|
||
|
||
def _build_shapes_skeleton(keypoints):
|
||
"""Return a single skeleton shape containing all visible keypoints."""
|
||
filtered = [kp for kp in keypoints if kp["conf"] >= CONF_THRESHOLD]
|
||
if not filtered:
|
||
return []
|
||
|
||
elements = []
|
||
for kp in keypoints:
|
||
visible = kp["conf"] >= CONF_THRESHOLD
|
||
elements.append({
|
||
"label": kp["label"],
|
||
"type": "points",
|
||
"points": [kp["x"], kp["y"]],
|
||
"occluded": not visible,
|
||
"outside": not visible,
|
||
})
|
||
|
||
return [{
|
||
"label": "person",
|
||
"type": "skeleton",
|
||
"elements": elements,
|
||
}]
|
||
|
||
|
||
def _build_shapes_points(keypoints):
|
||
"""Return one ``points`` shape per visible keypoint."""
|
||
shapes = []
|
||
for kp in keypoints:
|
||
if kp["conf"] >= CONF_THRESHOLD:
|
||
shapes.append({
|
||
"label": kp["label"],
|
||
"type": "points",
|
||
"points": [kp["x"], kp["y"]],
|
||
"confidence": str(kp["conf"]),
|
||
})
|
||
return shapes
|
||
|
||
|
||
def init_context(context):
|
||
context.logger.info("Init context ----> 0%")
|
||
model = PoseEstimator(MODEL_XML, MODEL_BIN, conf=CONF_THRESHOLD)
|
||
context.user_data.model = model
|
||
context.logger.info(
|
||
"Init context ----> 100%% (input: %dx%d, labels: %d, output: %s)",
|
||
model.input_width,
|
||
model.input_height,
|
||
len(KEYPOINT_LABELS),
|
||
OUTPUT_TYPE,
|
||
)
|
||
|
||
|
||
def handler(context, event):
|
||
context.logger.info("Run OpenVINO Pose Estimation model")
|
||
|
||
try:
|
||
data = event.body
|
||
image_b64 = data["image"]
|
||
except Exception:
|
||
context.logger.error("Invalid request body – missing 'image' key")
|
||
return context.Response(
|
||
body=json.dumps({"error": "Invalid request body"}),
|
||
status_code=400,
|
||
content_type="application/json",
|
||
)
|
||
|
||
image_bytes = base64.b64decode(image_b64)
|
||
image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||
if image is None:
|
||
context.logger.error("Failed to decode image")
|
||
return context.Response(
|
||
body=json.dumps({"error": "Failed to decode image"}),
|
||
status_code=400,
|
||
content_type="application/json",
|
||
)
|
||
|
||
model = context.user_data.model
|
||
|
||
img_resized, dw, dh = model.resize_and_pad(image)
|
||
keypoints = model.predict(img_resized, dw, dh, image.shape)
|
||
|
||
if OUTPUT_TYPE == "points":
|
||
shapes = _build_shapes_points(keypoints)
|
||
else:
|
||
shapes = _build_shapes_skeleton(keypoints)
|
||
|
||
visible = sum(1 for kp in keypoints if kp["conf"] >= CONF_THRESHOLD)
|
||
context.logger.info(
|
||
"Detected %d / %d keypoints", visible, len(keypoints)
|
||
)
|
||
|
||
return context.Response(
|
||
body=json.dumps(shapes),
|
||
headers={},
|
||
content_type="application/json",
|
||
status_code=200,
|
||
)
|