mwangi-clinton's picture
deploy 2d pose models with rtmcc head
e7bf352
Raw History Blame Contribute Delete
28.9 kB
"""Standalone Pure-PyTorch CustomCNN + RTMCCHead 2D Human Pose Estimator.
Zero-MMPose inference implementation for the DeKUT-DSAIL/cakd-coco-2d-pose
Hugging Face model family (small, medium, large RTMCC variants trained on COCO 256x192).
"""
from __future__ import annotations
import json
import math
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from PIL import Image, ImageOps
from safetensors.torch import load_file as load_safetensors
from torch import Tensor
DEFAULT_REPO_ID = "DeKUT-DSAIL/cakd-coco-2d-pose"
KEYPOINT_NAMES: List[str] = [
"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",
]
# Symmetric left/right swap indices for horizontal flip test-time augmentation.
FLIP_INDICES: List[int] = [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15]
SKELETON: List[Tuple[int, int]] = [
(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),
]
# Official COCO 17 keypoint colors (RGB): blue face/head, green left, orange right.
KEYPOINT_COLORS: List[Tuple[int, int, int]] = [
(51, 153, 255), # 0: nose
(51, 153, 255), # 1: left_eye
(51, 153, 255), # 2: right_eye
(51, 153, 255), # 3: left_ear
(51, 153, 255), # 4: right_ear
(0, 255, 0), # 5: left_shoulder
(255, 128, 0), # 6: right_shoulder
(0, 255, 0), # 7: left_elbow
(255, 128, 0), # 8: right_elbow
(0, 255, 0), # 9: left_wrist
(255, 128, 0), # 10: right_wrist
(0, 255, 0), # 11: left_hip
(255, 128, 0), # 12: right_hip
(0, 255, 0), # 13: left_knee
(255, 128, 0), # 14: right_knee
(0, 255, 0), # 15: left_ankle
(255, 128, 0), # 16: right_ankle
]
# Official COCO 19 skeleton link colors (RGB), aligned 1:1 with SKELETON edges.
SKELETON_LINK_COLORS: List[Tuple[int, int, int]] = [
(0, 255, 0), # (15, 13) left_ankle - left_knee
(0, 255, 0), # (13, 11) left_knee - left_hip
(255, 128, 0), # (16, 14) right_ankle - right_knee
(255, 128, 0), # (14, 12) right_knee - right_hip
(51, 153, 255), # (11, 12) left_hip - right_hip
(51, 153, 255), # (5, 11) left_shoulder - left_hip
(51, 153, 255), # (6, 12) right_shoulder - right_hip
(51, 153, 255), # (5, 6) left_shoulder - right_shoulder
(0, 255, 0), # (5, 7) left_shoulder - left_elbow
(255, 128, 0), # (6, 8) right_shoulder - right_elbow
(0, 255, 0), # (7, 9) left_elbow - left_wrist
(255, 128, 0), # (8, 10) right_elbow - right_wrist
(51, 153, 255), # (1, 2) left_eye - right_eye
(51, 153, 255), # (0, 1) nose - left_eye
(51, 153, 255), # (0, 2) nose - right_eye
(51, 153, 255), # (1, 3) left_eye - left_ear
(51, 153, 255), # (2, 4) right_eye - right_ear
(51, 153, 255), # (3, 5) left_ear - left_shoulder
(51, 153, 255), # (4, 6) right_ear - right_shoulder
]
VARIANT_ALIASES: Dict[str, str] = {
"small": "small",
"small_rtmcc": "small",
"small-rtmcc": "small",
"s": "small",
"medium": "medium",
"medium_rtmcc": "medium",
"medium-rtmcc": "medium",
"m": "medium",
"large": "large",
"large_rtmcc": "large",
"large-rtmcc": "large",
"l": "large",
}
class SqueezeExcitation(nn.Module):
"""Squeeze-and-Excitation (SE) channel attention block."""
def __init__(self, channels: int, reduction: int = 4) -> None:
super().__init__()
reduced_ch = max(8, channels // reduction)
self.fc = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(channels, reduced_ch, kernel_size=1, bias=True),
nn.SiLU(inplace=True),
nn.Conv2d(reduced_ch, channels, kernel_size=1, bias=True),
nn.Sigmoid(),
)
def forward(self, x: Tensor) -> Tensor:
return x * self.fc(x)
class DropPath(nn.Module):
"""Stochastic Depth per sample."""
def __init__(self, drop_prob: float = 0.0) -> None:
super().__init__()
self.drop_prob = drop_prob
def forward(self, x: Tensor) -> Tensor:
if self.drop_prob == 0.0 or not self.training:
return x
keep_prob = 1.0 - self.drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1)
random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
random_tensor.floor_()
return x.div(keep_prob) * random_tensor
class InvertedResidual(nn.Module):
"""Inverted residual block with depthwise separable conv and SE attention."""
def __init__(
self,
in_channels: int,
out_channels: int,
stride: int = 1,
expand_ratio: float = 3.0,
se_reduction: int = 4,
drop_path_rate: float = 0.0,
) -> None:
super().__init__()
self.use_residual = stride == 1 and in_channels == out_channels
hidden_dim = int(round(in_channels * expand_ratio))
layers: List[nn.Module] = []
if expand_ratio != 1.0:
layers.extend([
nn.Conv2d(in_channels, hidden_dim, kernel_size=1, bias=False),
nn.BatchNorm2d(hidden_dim),
nn.SiLU(inplace=True),
])
layers.extend([
nn.Conv2d(
hidden_dim,
hidden_dim,
kernel_size=3,
stride=stride,
padding=1,
groups=hidden_dim,
bias=False,
),
nn.BatchNorm2d(hidden_dim),
nn.SiLU(inplace=True),
SqueezeExcitation(hidden_dim, reduction=se_reduction),
nn.Conv2d(hidden_dim, out_channels, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channels),
])
self.conv = nn.Sequential(*layers)
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
def forward(self, x: Tensor) -> Tensor:
if self.use_residual:
return x + self.drop_path(self.conv(x))
return self.conv(x)
class CustomSmallCNN(nn.Module):
"""4-stage inverted-residual CNN backbone with SE attention."""
def __init__(
self,
in_channels: int = 3,
stage_channels: Sequence[int] = (48, 96, 192, 384),
depths: Sequence[int] = (2, 2, 3, 2),
expand_ratio: float = 3.0,
se_reduction: int = 4,
drop_path_rate: float = 0.0,
out_indices: Sequence[int] = (3,),
) -> None:
super().__init__()
if len(stage_channels) != 4 or len(depths) != 4:
raise ValueError("stage_channels and depths must both have length 4.")
self.stage_channels = list(stage_channels)
self.depths = tuple(depths)
self.out_indices = tuple(out_indices)
stem_ch = max(16, stage_channels[0] * 3 // 4)
self.stem = nn.Sequential(
nn.Conv2d(in_channels, stem_ch, kernel_size=3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(stem_ch),
nn.SiLU(inplace=True),
InvertedResidual(
in_channels=stem_ch,
out_channels=stage_channels[0],
stride=2,
expand_ratio=2.0,
se_reduction=se_reduction,
drop_path_rate=0.0,
),
)
self.stage1 = self._make_stage(
stage_channels[0], stage_channels[0], depths[0] - 1,
downsample=False, expand_ratio=expand_ratio, se_reduction=se_reduction,
drop_path_rate=drop_path_rate,
)
self.stage2 = self._make_stage(
stage_channels[0], stage_channels[1], depths[1],
downsample=True, expand_ratio=expand_ratio, se_reduction=se_reduction,
drop_path_rate=drop_path_rate,
)
self.stage3 = self._make_stage(
stage_channels[1], stage_channels[2], depths[2],
downsample=True, expand_ratio=expand_ratio, se_reduction=se_reduction,
drop_path_rate=drop_path_rate,
)
self.stage4 = self._make_stage(
stage_channels[2], stage_channels[3], depths[3],
downsample=True, expand_ratio=expand_ratio, se_reduction=se_reduction,
drop_path_rate=drop_path_rate,
)
@staticmethod
def _make_stage(
in_ch: int,
out_ch: int,
num_blocks: int,
downsample: bool,
expand_ratio: float,
se_reduction: int,
drop_path_rate: float,
) -> nn.Sequential:
blocks: List[nn.Module] = []
if downsample:
blocks.append(
InvertedResidual(
in_channels=in_ch,
out_channels=out_ch,
stride=2,
expand_ratio=expand_ratio,
se_reduction=se_reduction,
drop_path_rate=drop_path_rate,
)
)
remaining = num_blocks - 1
else:
remaining = num_blocks
for _ in range(remaining):
blocks.append(
InvertedResidual(
in_channels=out_ch,
out_channels=out_ch,
stride=1,
expand_ratio=expand_ratio,
se_reduction=se_reduction,
drop_path_rate=drop_path_rate,
)
)
return nn.Sequential(*blocks)
def forward(self, x: Tensor) -> List[Tensor]:
x1 = self.stage1(self.stem(x))
x2 = self.stage2(x1)
x3 = self.stage3(x2)
x4 = self.stage4(x3)
outs = [x1, x2, x3, x4]
return [outs[i] for i in self.out_indices]
class Scale(nn.Module):
"""Learnable per-channel scale vector."""
def __init__(self, dim: int, init_value: float = 1.0) -> None:
super().__init__()
self.scale = nn.Parameter(init_value * torch.ones(dim))
def forward(self, x: Tensor) -> Tensor:
return x * self.scale
class ScaleNorm(nn.Module):
"""Scale normalization over the last dimension."""
def __init__(self, dim: int, eps: float = 1e-5) -> None:
super().__init__()
self.scale = dim ** -0.5
self.eps = eps
self.g = nn.Parameter(torch.ones(1))
def forward(self, x: Tensor) -> Tensor:
norm = torch.norm(x, dim=-1, keepdim=True) * self.scale
return x / norm.clamp(min=self.eps) * self.g
class RTMCCBlock(nn.Module):
"""Gated Attention Unit (GAU) block used in RTMCCHead."""
def __init__(
self,
num_token: int,
in_token_dims: int,
out_token_dims: int,
expansion_factor: int = 2,
s: int = 128,
eps: float = 1e-5,
dropout_rate: float = 0.0,
drop_path: float = 0.0,
act_fn: str = "SiLU",
) -> None:
super().__init__()
self.s = s
self.e = int(in_token_dims * expansion_factor)
self.o = nn.Linear(self.e, out_token_dims, bias=False)
self.uv = nn.Linear(in_token_dims, 2 * self.e + self.s, bias=False)
self.gamma = nn.Parameter(torch.rand((2, self.s)))
self.beta = nn.Parameter(torch.rand((2, self.s)))
self.ln = ScaleNorm(in_token_dims, eps=eps)
self.act_fn = nn.SiLU(inplace=True) if act_fn == "SiLU" else nn.ReLU(inplace=True)
self.shortcut = in_token_dims == out_token_dims
if self.shortcut:
self.res_scale = Scale(in_token_dims)
self.sqrt_s = math.sqrt(s)
self.dropout_rate = dropout_rate
self.dropout = nn.Dropout(dropout_rate) if dropout_rate > 0.0 else nn.Identity()
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
def _forward_gau(self, x: Tensor) -> Tensor:
x = self.ln(x)
u, v, base = torch.split(self.act_fn(self.uv(x)), [self.e, self.e, self.s], dim=-1)
base = base.unsqueeze(2) * self.gamma[None, None, :] + self.beta
q, k = torch.unbind(base, dim=-2)
qk = torch.bmm(q, k.permute(0, 2, 1))
kernel = torch.square(F.relu(qk / self.sqrt_s))
if self.dropout_rate > 0.0:
kernel = self.dropout(kernel)
return self.o(u * torch.bmm(kernel, v))
def forward(self, x: Tensor) -> Tensor:
out = self.drop_path(self._forward_gau(x))
if self.shortcut:
return self.res_scale(x) + out
return out
class RTMCCHead(nn.Module):
"""1D SimCC coordinate classification head."""
def __init__(
self,
in_channels: int,
out_channels: int = 17,
input_size: Tuple[int, int] = (192, 256),
in_featuremap_size: Tuple[int, int] = (6, 8),
simcc_split_ratio: float = 2.0,
final_layer_kernel_size: int = 7,
hidden_dims: int = 256,
s: int = 128,
expansion_factor: int = 2,
act_fn: str = "SiLU",
) -> None:
super().__init__()
flatten_dims = in_featuremap_size[0] * in_featuremap_size[1]
self.final_layer = nn.Conv2d(
in_channels,
out_channels,
kernel_size=final_layer_kernel_size,
stride=1,
padding=final_layer_kernel_size // 2,
)
self.mlp = nn.Sequential(
ScaleNorm(flatten_dims),
nn.Linear(flatten_dims, hidden_dims, bias=False),
)
self.gau = RTMCCBlock(
num_token=out_channels,
in_token_dims=hidden_dims,
out_token_dims=hidden_dims,
expansion_factor=expansion_factor,
s=s,
act_fn=act_fn,
)
w_bins = int(input_size[0] * simcc_split_ratio)
h_bins = int(input_size[1] * simcc_split_ratio)
self.cls_x = nn.Linear(hidden_dims, w_bins, bias=False)
self.cls_y = nn.Linear(hidden_dims, h_bins, bias=False)
def forward(self, feats: Sequence[Tensor]) -> Tuple[Tensor, Tensor]:
x = self.final_layer(feats[-1])
x = torch.flatten(x, 2)
x = self.mlp(x)
x = self.gau(x)
return self.cls_x(x), self.cls_y(x)
class TopdownRTMCCModel(nn.Module):
"""Combined backbone + RTMCCHead matching checkpoint state_dict keys."""
def __init__(
self,
stage_channels: Sequence[int],
depths: Sequence[int] = (2, 2, 3, 2),
expand_ratio: float = 3.0,
se_reduction: int = 4,
out_channels: int = 17,
input_size: Tuple[int, int] = (192, 256),
in_featuremap_size: Tuple[int, int] = (6, 8),
simcc_split_ratio: float = 2.0,
final_layer_kernel_size: int = 7,
hidden_dims: int = 256,
s: int = 128,
expansion_factor: int = 2,
act_fn: str = "SiLU",
) -> None:
super().__init__()
self.backbone = CustomSmallCNN(
stage_channels=stage_channels,
depths=depths,
expand_ratio=expand_ratio,
se_reduction=se_reduction,
out_indices=(3,),
)
self.head = RTMCCHead(
in_channels=stage_channels[-1],
out_channels=out_channels,
input_size=input_size,
in_featuremap_size=in_featuremap_size,
simcc_split_ratio=simcc_split_ratio,
final_layer_kernel_size=final_layer_kernel_size,
hidden_dims=hidden_dims,
s=s,
expansion_factor=expansion_factor,
act_fn=act_fn,
)
def forward(self, x: Tensor) -> Tuple[Tensor, Tensor]:
return self.head(self.backbone(x))
def _rotate_point(pt: np.ndarray, angle_rad: float) -> np.ndarray:
sn, cs = np.sin(angle_rad), np.cos(angle_rad)
return np.array([pt[0] * cs - pt[1] * sn, pt[0] * sn + pt[1] * cs], dtype=np.float32)
def _get_3rd_point(a: np.ndarray, b: np.ndarray) -> np.ndarray:
direction = a - b
return b + np.array([-direction[1], direction[0]], dtype=np.float32)
def _get_warp_matrix(
center: np.ndarray,
scale: np.ndarray,
output_size: Tuple[int, int],
rot: float = 0.0,
) -> np.ndarray:
"""Compute top-down affine warp matrix matching MMPose's get_warp_matrix."""
src_w = float(scale[0])
dst_w, dst_h = float(output_size[0]), float(output_size[1])
rot_rad = np.deg2rad(rot)
src_dir = _rotate_point(np.array([0.0, src_w * -0.5], dtype=np.float32), rot_rad)
dst_dir = np.array([0.0, dst_w * -0.5], dtype=np.float32)
src = np.zeros((3, 2), dtype=np.float32)
src[0, :] = center
src[1, :] = center + src_dir
src[2, :] = _get_3rd_point(src[0, :], src[1, :])
dst = np.zeros((3, 2), dtype=np.float32)
dst[0, :] = [dst_w * 0.5, dst_h * 0.5]
dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5], dtype=np.float32) + dst_dir
dst[2, :] = _get_3rd_point(dst[0, :], dst[1, :])
return cv2.getAffineTransform(src, dst)
def _fix_aspect_ratio(scale: np.ndarray, aspect_ratio: float) -> np.ndarray:
w, h = float(scale[0]), float(scale[1])
if w > h * aspect_ratio:
return np.array([w, w / aspect_ratio], dtype=np.float32)
return np.array([h * aspect_ratio, h], dtype=np.float32)
def _decode_simcc(
simcc_x: np.ndarray,
simcc_y: np.ndarray,
simcc_split_ratio: float = 2.0,
) -> Tuple[np.ndarray, np.ndarray]:
"""Decode 1D SimCC distributions to (N, K, 2) coordinates and (N, K) scores."""
x_locs = np.argmax(simcc_x, axis=-1)
y_locs = np.argmax(simcc_y, axis=-1)
locs = np.stack([x_locs, y_locs], axis=-1).astype(np.float32)
scores = np.minimum(np.amax(simcc_x, axis=-1), np.amax(simcc_y, axis=-1))
locs[scores <= 0.0] = -1.0
return locs / simcc_split_ratio, scores
def draw_pose(
image: Union[str, Path, Image.Image, np.ndarray],
keypoints: np.ndarray,
scores: np.ndarray,
kpt_thr: float = 0.3,
radius: int = 4,
thickness: int = 2,
input_format: str = "rgb",
out_file: Optional[Union[str, Path]] = None,
) -> np.ndarray:
"""Draw COCO-17 skeleton edges and keypoints using the official COCO color palette."""
img_rgb = _load_image_rgb(image, input_format=input_format).copy()
num_kpts = len(keypoints)
for edge_idx, (u, v) in enumerate(SKELETON):
if u < num_kpts and v < num_kpts and scores[u] > kpt_thr and scores[v] > kpt_thr:
pt1 = (int(round(keypoints[u][0])), int(round(keypoints[u][1])))
pt2 = (int(round(keypoints[v][0])), int(round(keypoints[v][1])))
color = SKELETON_LINK_COLORS[edge_idx % len(SKELETON_LINK_COLORS)]
cv2.line(img_rgb, pt1, pt2, color, thickness, cv2.LINE_AA)
for idx, (kpt, score) in enumerate(zip(keypoints, scores)):
if score > kpt_thr:
center = (int(round(kpt[0])), int(round(kpt[1])))
color = KEYPOINT_COLORS[idx % len(KEYPOINT_COLORS)]
cv2.circle(img_rgb, center, radius, color, -1, cv2.LINE_AA)
cv2.circle(img_rgb, center, radius + 1, (255, 255, 255), 1, cv2.LINE_AA)
if out_file is not None:
out_path = Path(out_file)
out_path.parent.mkdir(parents=True, exist_ok=True)
cv2.imwrite(str(out_path), cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR))
return img_rgb
def _load_image_rgb(image: Union[str, Path, Image.Image, np.ndarray], input_format: str = "rgb") -> np.ndarray:
if isinstance(image, (str, Path)):
with Image.open(image) as pil_img:
return np.asarray(ImageOps.exif_transpose(pil_img).convert("RGB"))
if isinstance(image, Image.Image):
return np.asarray(ImageOps.exif_transpose(image).convert("RGB"))
if isinstance(image, np.ndarray):
if image.ndim != 3 or image.shape[2] != 3:
raise ValueError(f"Expected HxWx3 image array, got shape {image.shape}.")
if input_format.lower() == "bgr":
return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
if input_format.lower() == "rgb":
return image
raise ValueError(f"Unsupported input_format='{input_format}' (expected 'rgb' or 'bgr').")
raise TypeError(f"Unsupported image type: {type(image)}")
class PoseEstimator:
"""User-facing Hugging Face inference wrapper for CustomCNN + RTMCCHead models."""
def __init__(
self,
model: TopdownRTMCCModel,
config: Dict[str, Any],
variant: str,
device: Union[str, torch.device],
) -> None:
self.model = model
self.config = config
self.variant = variant
self.device = torch.device(device)
self.input_size: Tuple[int, int] = tuple(config["input_size"])
self.simcc_split_ratio: float = float(config["variants"][variant]["head"]["simcc_split_ratio"])
self.mean = torch.tensor(config["mean"], dtype=torch.float32, device=self.device).view(1, 3, 1, 1)
self.std = torch.tensor(config["std"], dtype=torch.float32, device=self.device).view(1, 3, 1, 1)
self.model.to(self.device).eval()
@classmethod
def resolve_variant(cls, variant: Optional[str], config: Dict[str, Any]) -> str:
"""Resolve user-supplied variant name or default to config['default_variant']."""
if variant is None:
resolved = config["default_variant"]
else:
key = variant.strip().lower()
resolved = VARIANT_ALIASES.get(key, key)
available = list(config["variants"].keys())
if resolved not in config["variants"]:
raise ValueError(f"Unknown variant '{variant}'. Available variants: {available}")
return resolved
@classmethod
def from_pretrained(
cls,
pretrained_model_name_or_path: Union[str, Path] = DEFAULT_REPO_ID,
variant: Optional[str] = None,
device: Optional[Union[str, torch.device]] = None,
cache_dir: Optional[Union[str, Path]] = None,
token: Optional[Union[bool, str]] = None,
force_download: bool = False,
) -> "PoseEstimator":
"""Load a CustomCNN + RTMCCHead pose model from a local folder or Hugging Face Hub."""
repo_path = Path(pretrained_model_name_or_path)
if repo_path.is_dir():
config_path = repo_path / "config.json"
if not config_path.is_file():
raise FileNotFoundError(f"config.json not found in {repo_path}")
else:
config_path = Path(
hf_hub_download(
repo_id=str(pretrained_model_name_or_path),
filename="config.json",
cache_dir=cache_dir,
token=token,
force_download=force_download,
)
)
with open(config_path, "r", encoding="utf-8") as f:
config = json.load(f)
resolved_variant = cls.resolve_variant(variant, config)
v_cfg = config["variants"][resolved_variant]
weights_rel = v_cfg["weights_file"]
if repo_path.is_dir():
weights_path = repo_path / weights_rel
if not weights_path.is_file():
raise FileNotFoundError(f"Weights file not found: {weights_path}")
else:
weights_path = Path(
hf_hub_download(
repo_id=str(pretrained_model_name_or_path),
filename=weights_rel,
cache_dir=cache_dir,
token=token,
force_download=force_download,
)
)
bb_cfg = v_cfg["backbone"]
hd_cfg = v_cfg["head"]
model = TopdownRTMCCModel(
stage_channels=bb_cfg["stage_channels"],
depths=bb_cfg["depths"],
expand_ratio=bb_cfg["expand_ratio"],
se_reduction=bb_cfg["se_reduction"],
out_channels=hd_cfg["out_channels"],
input_size=tuple(config["input_size"]),
in_featuremap_size=tuple(hd_cfg["in_featuremap_size"]),
simcc_split_ratio=hd_cfg["simcc_split_ratio"],
final_layer_kernel_size=hd_cfg["final_layer_kernel_size"],
hidden_dims=hd_cfg["hidden_dims"],
s=hd_cfg["s"],
expansion_factor=hd_cfg["expansion_factor"],
act_fn=hd_cfg["act_fn"],
)
state_dict = load_safetensors(str(weights_path), device="cpu")
model.load_state_dict(state_dict, strict=True)
target_device = device or ("cuda" if torch.cuda.is_available() else "cpu")
return cls(model=model, config=config, variant=resolved_variant, device=target_device)
def _preprocess_crop(
self,
img_rgb: np.ndarray,
bbox: Sequence[float],
padding: float,
) -> Tuple[Tensor, np.ndarray, np.ndarray]:
w_in, h_in = self.input_size
x1, y1, x2, y2 = [float(v) for v in bbox]
center = np.array([(x1 + x2) * 0.5, (y1 + y2) * 0.5], dtype=np.float32)
scale = np.array([(x2 - x1) * padding, (y2 - y1) * padding], dtype=np.float32)
scale = _fix_aspect_ratio(scale, aspect_ratio=w_in / h_in)
warp_mat = _get_warp_matrix(center, scale, output_size=(w_in, h_in))
warped = cv2.warpAffine(img_rgb, warp_mat, (w_in, h_in), flags=cv2.INTER_LINEAR)
tensor = torch.from_numpy(warped).permute(2, 0, 1).contiguous().float().unsqueeze(0).to(self.device)
tensor = (tensor - self.mean) / self.std
return tensor, center, scale
@torch.inference_mode()
def forward_tensors(self, x: Tensor) -> Tuple[Tensor, Tensor]:
"""Run raw forward pass on normalized NCHW RGB tensor."""
return self.model(x)
@torch.inference_mode()
def predict(
self,
image: Union[str, Path, Image.Image, np.ndarray],
bbox: Optional[Sequence[float]] = None,
padding: float = 1.25,
flip_test: bool = True,
input_format: str = "rgb",
return_vis: bool = False,
kpt_thr: float = 0.3,
) -> Union[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray, np.ndarray]]:
"""Predict 17 COCO keypoints for a person crop or full image.
Args:
image: File path, PIL Image, or HxWx3 numpy array.
bbox: Optional ``[x1, y1, x2, y2]`` bounding box. Defaults to full image.
padding: BBox padding multiplier (defaults to 1.25, matching MMPose GetBBoxCenterScale).
flip_test: Whether to average predictions with horizontal-flip TTA.
input_format: ``'rgb'`` (default) or ``'bgr'`` when passing a numpy array.
return_vis: If True, also return an RGB image with skeleton overlay.
kpt_thr: Confidence threshold used when ``return_vis=True``.
Returns:
``(keypoints, scores)`` with shapes ``(17, 2)`` and ``(17,)``,
or ``(keypoints, scores, vis_rgb)`` if ``return_vis=True``.
"""
img_rgb = _load_image_rgb(image, input_format=input_format)
img_h, img_w = img_rgb.shape[:2]
active_bbox = [0.0, 0.0, float(img_w), float(img_h)] if bbox is None else list(bbox)
x, center, scale = self._preprocess_crop(img_rgb, active_bbox, float(padding))
pred_x, pred_y = self.model(x)
if flip_test:
pred_x_f, pred_y_f = self.model(x.flip(-1))
pred_x = 0.5 * (pred_x + pred_x_f[:, FLIP_INDICES].flip(-1))
pred_y = 0.5 * (pred_y + pred_y_f[:, FLIP_INDICES])
kpts_in, scores = _decode_simcc(
pred_x.cpu().numpy(),
pred_y.cpu().numpy(),
simcc_split_ratio=self.simcc_split_ratio,
)
in_size = np.array(self.input_size, dtype=np.float32)
keypoints = (kpts_in[0] / in_size) * scale + center - 0.5 * scale
scores_1d = scores[0]
if return_vis:
vis = draw_pose(img_rgb, keypoints, scores_1d, kpt_thr=kpt_thr)
return keypoints, scores_1d, vis
return keypoints, scores_1d
def render(
self,
image: Union[str, Path, Image.Image, np.ndarray],
keypoints: np.ndarray,
scores: np.ndarray,
kpt_thr: float = 0.3,
out_file: Optional[Union[str, Path]] = None,
input_format: str = "rgb",
) -> np.ndarray:
"""Render COCO-17 keypoints and skeleton onto an image using the COCO color palette."""
return draw_pose(
image=image,
keypoints=keypoints,
scores=scores,
kpt_thr=kpt_thr,
input_format=input_format,
out_file=out_file,
)