File size: 2,582 Bytes
326d3cc
 
 
 
f771d3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f771d3b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from pathlib import Path
import numpy as np
from .detection import ort_session, verify_cuda_nodes


def filter_implausible_feet(points, scores):
    """Reject detached toe/heel predictions; never move them onto an ankle."""
    points, scores = points.copy(), scores.copy()
    for knee, ankle, feet in ((13, 15, range(17, 20)), (14, 16, range(20, 23))):
        if not np.isfinite(points[[knee, ankle]]).all():
            points[list(feet)], scores[list(feet)] = np.nan, 0.
            continue
        limit = max(30., .75 * np.linalg.norm(points[knee]-points[ankle]))
        for joint in feet:
            if not np.isfinite(points[joint]).all() or np.linalg.norm(points[joint]-points[ankle]) > limit:
                points[joint], scores[joint] = np.nan, 0.
    return points, scores


class RTMWPose:
    def __init__(self, path, device="cpu"):
        if not Path(path).is_file() or Path(path).suffix != ".onnx":
            raise ValueError("Explicit local .onnx pose artifact required")
        self.session = ort_session(path, device)
        self.device, self.cuda_verified = device, False
        shape = self.session.get_inputs()[0].shape
        if shape[1:] != [3, 384, 288]:
            raise ValueError(f"Unexpected RTMW input {shape}")
        # Reuse the pinned RTMLib transforms/decoder with our scored/profilable session.
        from rtmlib.tools.pose_estimation.pre_processings import bbox_xyxy2cs, top_down_affine
        from rtmlib.tools.pose_estimation.post_processings import get_simcc_maximum
        self.bbox_transform, self.affine, self.decode = bbox_xyxy2cs, top_down_affine, get_simcc_maximum

    def __call__(self, image, box):
        center, scale = self.bbox_transform(np.asarray(box), padding=1.25)
        crop, scale = self.affine((288,384), scale, center, image)
        normalized = (crop-np.array([123.675,116.28,103.53]))/np.array([58.395,57.12,57.375])
        tensor = np.ascontiguousarray(normalized.transpose(2,0,1)[None],dtype=np.float32)
        x, y = self.session.run(None,{self.session.get_inputs()[0].name:tensor})
        locations, scores = self.decode(x,y)
        points = locations / 2 / np.array([288,384]) * scale + center - scale/2
        points, scores = points[0], scores[0]
        if self.device == "cuda" and not self.cuda_verified:
            verify_cuda_nodes(self.session)
            self.cuda_verified = True
        if points.shape != (133, 2) or scores.shape != (133,):
            raise ValueError("RTMW must preserve 133-point native topology")
        return filter_implausible_feet(points, scores)