AlexSinHF commited on
Commit
b490a5e
·
verified ·
1 Parent(s): 83a4ffc

Pose: drop off-frame / border-parked joints (no squeezed-in feet on cropped references)

Browse files
Files changed (1) hide show
  1. anima_pose/detect.py +297 -249
anima_pose/detect.py CHANGED
@@ -1,249 +1,297 @@
1
- """DWPose (COCO-WholeBody 133) detection and skeleton rendering for Anima-Control-Pose.
2
-
3
- Detection: rtmlib ``Wholebody`` in ``balanced`` mode (YOLOX-m HumanArt + RTMW-DW-x-L 256x192)
4
- -- the exact models the adapter author uses, mirrored in the ``detector/`` folder of
5
- Claquasse/Anima-Control-Pose. CPU / onnxruntime, ~0.5 s per image.
6
-
7
- Rendering styles:
8
-
9
- * ``R0_thin`` (default), ``R1_thick``, ``R2_puppet``, ``heatmap`` -- ported from the
10
- author's ComfyUI node ``ComfyUI-anima-pose-control/pose_render.py`` (same palette, widths
11
- and keypoint threshold). The author's workflows render at 768 px and ``ImageScale``
12
- (nearest-exact) to the generation size; we do the same (long side 768, then nearest
13
- upscale), so line weight relative to the canvas matches the published results. The
14
- README calls R0_thin "the only one the model trained on".
15
- * ``dwpose_rtmlib`` -- rtmlib ``draw_skeleton(openpose_skeleton=False)`` drawn into a BGR
16
- canvas and flipped, i.e. exactly ``scripts/render_skeletons.py`` from the adapter repo.
17
-
18
- Keypoint JSON (``POSE_FORMAT``) -- coordinates normalised to the *source image*:
19
- {"format": "anima-pose-v1", "width": W, "height": H,
20
- "people": [{"keypoints": [[x, y, score], ... 133 items]}]}
21
- """
22
- from __future__ import annotations
23
-
24
- import json
25
- import threading
26
- from typing import Callable, Optional
27
-
28
- import numpy as np
29
- from PIL import Image
30
-
31
- POSE_FORMAT = "anima-pose-v1"
32
- NUM_KPTS = 133
33
- KPT_THR = 0.3
34
-
35
- BODY = list(range(17))
36
- FEET = list(range(17, 23))
37
- FACE = list(range(23, 91))
38
- HAND = list(range(91, 133))
39
-
40
- DETECTOR_FILES = {
41
- "det": "detector/yolox_m_8xb8-300e_humanart-c2c7a14a.onnx",
42
- "pose": "detector/rtmw-dw-x-l_simcc-cocktail14_270e-256x192_20231122.onnx",
43
- }
44
- DET_INPUT_SIZE = (640, 640)
45
- POSE_INPUT_SIZE = (192, 256)
46
-
47
- FIT_MODES = ("contain", "cover", "stretch")
48
- STYLES = ("R0_thin", "R1_thick", "R2_puppet", "heatmap", "dwpose_rtmlib")
49
- DEFAULT_STYLE = "R0_thin"
50
- NODE_RENDER_LONG_SIDE = 768
51
-
52
- # ── Palette / widths: verbatim from the author's pose_render.py ─────────────────────────────
53
- COCO_LIMBS = [(5, 7), (7, 9), (6, 8), (8, 10), (11, 13), (13, 15), (12, 14), (14, 16),
54
- (5, 6), (11, 12), (5, 11), (6, 12), (0, 5), (0, 6)]
55
- _PAL = [(255, 0, 0), (255, 128, 0), (255, 255, 0), (128, 255, 0), (0, 255, 0), (0, 255, 128), (0, 255, 255),
56
- (0, 128, 255), (0, 0, 255), (128, 0, 255), (255, 0, 255), (255, 0, 128), (180, 180, 180), (220, 220, 220)]
57
- LIMB_COLOR = {l: _PAL[i % len(_PAL)] for i, l in enumerate(COCO_LIMBS)}
58
- JOINT_COLOR = [_PAL[i % len(_PAL)] for i in range(17)]
59
- _W = {"R0_thin": {"stick": 2, "joint": 3}, "R1_thick": {"stick": 8, "joint": 6},
60
- "R2_puppet": {"stick": 22, "joint": 11}, "heatmap": {"stick": 2, "joint": 3}}
61
-
62
-
63
- class NoPersonError(RuntimeError):
64
- pass
65
-
66
-
67
- _ESTIMATOR = None
68
- _ESTIMATOR_LOCK = threading.Lock()
69
-
70
-
71
- def get_estimator(resolve_file: Callable[[str], str]):
72
- """Build (once) the rtmlib Wholebody estimator. ``resolve_file(repo_path) -> local path``."""
73
- global _ESTIMATOR
74
- with _ESTIMATOR_LOCK:
75
- if _ESTIMATOR is None:
76
- from rtmlib import Wholebody
77
- _ESTIMATOR = Wholebody(
78
- det=resolve_file(DETECTOR_FILES["det"]),
79
- det_input_size=DET_INPUT_SIZE,
80
- pose=resolve_file(DETECTOR_FILES["pose"]),
81
- pose_input_size=POSE_INPUT_SIZE,
82
- to_openpose=False,
83
- backend="onnxruntime",
84
- device="cpu",
85
- )
86
- return _ESTIMATOR
87
-
88
-
89
- def detect(image: Image.Image, estimator) -> dict:
90
- """Detect every person in ``image``. Returns a pose dict (see module docstring)."""
91
- rgb = np.asarray(image.convert("RGB"))
92
- bgr = np.ascontiguousarray(rgb[..., ::-1])
93
- keypoints, scores = estimator(bgr)
94
- if keypoints is None or len(keypoints) == 0:
95
- raise NoPersonError("No person detected in the reference image.")
96
- keypoints = np.asarray(keypoints, dtype=np.float64).reshape(-1, NUM_KPTS, 2)
97
- scores = np.asarray(scores, dtype=np.float64).reshape(-1, NUM_KPTS)
98
-
99
- keep = (scores[:, BODY] >= KPT_THR).sum(axis=1) >= 4
100
- if not keep.any():
101
- raise NoPersonError("No person detected with enough confident body joints.")
102
- keypoints, scores = keypoints[keep], scores[keep]
103
- # Largest person first (the author's node only ever uses person 0).
104
- areas = [np.ptp(k[s >= KPT_THR], axis=0).prod() if (s >= KPT_THR).sum() > 1 else 0.0
105
- for k, s in zip(keypoints, scores)]
106
- order = np.argsort(areas)[::-1]
107
-
108
- h, w = rgb.shape[:2]
109
- people = []
110
- for i in order:
111
- pts = [[float(x) / w, float(y) / h, float(s)] for (x, y), s in zip(keypoints[i], scores[i])]
112
- people.append({"keypoints": pts})
113
- return {"format": POSE_FORMAT, "width": int(w), "height": int(h), "people": people}
114
-
115
-
116
- def parse_pose(pose) -> dict:
117
- """Accept a pose dict or its JSON string; validate the shape."""
118
- if isinstance(pose, str):
119
- pose = json.loads(pose)
120
- if not isinstance(pose, dict) or pose.get("format") != POSE_FORMAT:
121
- raise ValueError(f"Pose JSON must have format={POSE_FORMAT!r}.")
122
- if not pose.get("people"):
123
- raise ValueError("Pose JSON has no people.")
124
- for person in pose["people"]:
125
- if len(person.get("keypoints", [])) != NUM_KPTS:
126
- raise ValueError(f"Each person needs exactly {NUM_KPTS} keypoints.")
127
- return pose
128
-
129
-
130
- def _fit_transform(src_w: int, src_h: int, dst_w: int, dst_h: int, fit: str):
131
- """Return (sx, sy, ox, oy) mapping source pixels to destination pixels."""
132
- if fit == "stretch":
133
- return dst_w / src_w, dst_h / src_h, 0.0, 0.0
134
- s = max(dst_w / src_w, dst_h / src_h) if fit == "cover" else min(dst_w / src_w, dst_h / src_h)
135
- return s, s, (dst_w - src_w * s) / 2.0, (dst_h - src_h * s) / 2.0
136
-
137
-
138
- def _to_canvas(pose: dict, width: int, height: int, fit: str, hands: bool, face: bool, feet: bool,
139
- max_people: int):
140
- src_w, src_h = int(pose["width"]), int(pose["height"])
141
- sx, sy, ox, oy = _fit_transform(src_w, src_h, width, height, fit if fit in FIT_MODES else "contain")
142
- arr = np.asarray([p["keypoints"] for p in pose["people"][:max_people]], dtype=np.float64)
143
- kp = np.empty((arr.shape[0], NUM_KPTS, 2), dtype=np.float64)
144
- kp[..., 0] = arr[..., 0] * src_w * sx + ox
145
- kp[..., 1] = arr[..., 1] * src_h * sy + oy
146
- sc = arr[..., 2].copy()
147
- if not hands:
148
- sc[:, HAND] = 0.0
149
- if not face:
150
- sc[:, FACE] = 0.0
151
- if not feet:
152
- sc[:, FEET] = 0.0
153
- return kp, sc
154
-
155
-
156
- def _draw_node_style(cv, kp, sc, style, feet):
157
- """One person, author's node renderer (pose_render.render), on an arbitrary HxW canvas."""
158
- import cv2
159
- if style == "heatmap":
160
- H, W = cv.shape[:2]
161
- acc = np.zeros((H, W, 3), np.float32)
162
- for i in BODY + (FEET if feet else []):
163
- if sc[i] >= KPT_THR:
164
- x, y = int(round(kp[i][0])), int(round(kp[i][1]))
165
- if 0 <= x < W and 0 <= y < H:
166
- b = np.zeros((H, W), np.float32)
167
- b[y, x] = 1.0
168
- b = cv2.GaussianBlur(b, (0, 0), 11)
169
- b /= (b.max() + 1e-9)
170
- acc += b[..., None] * np.array(JOINT_COLOR[i % 17], np.float32)
171
- return np.maximum(cv, np.clip(acc, 0, 255).astype(np.uint8))
172
- cfg = _W[style]
173
- for a, b in COCO_LIMBS:
174
- if sc[a] >= KPT_THR and sc[b] >= KPT_THR:
175
- cv2.line(cv, (int(kp[a][0]), int(kp[a][1])), (int(kp[b][0]), int(kp[b][1])), LIMB_COLOR[(a, b)], cfg["stick"])
176
- for i in BODY:
177
- if sc[i] >= KPT_THR:
178
- cv2.circle(cv, (int(kp[i][0]), int(kp[i][1])), cfg["joint"], (255, 255, 255), -1)
179
- for i in FEET:
180
- if sc[i] >= KPT_THR:
181
- cv2.circle(cv, (int(kp[i][0]), int(kp[i][1])), max(1, cfg["joint"] // 2), (255, 255, 255), -1)
182
- if style == "R0_thin":
183
- for i in HAND:
184
- if sc[i] >= KPT_THR:
185
- cv2.circle(cv, (int(kp[i][0]), int(kp[i][1])), 2, (0, 255, 255), -1)
186
- for i in FACE:
187
- if sc[i] >= KPT_THR:
188
- cv2.circle(cv, (int(kp[i][0]), int(kp[i][1])), 2, (255, 255, 255), -1)
189
- return cv
190
-
191
-
192
- def render(
193
- pose,
194
- width: int,
195
- height: int,
196
- *,
197
- style: str = DEFAULT_STYLE,
198
- fit: str = "contain",
199
- hands: bool = True,
200
- face: bool = True,
201
- feet: bool = True,
202
- max_people: int = 1,
203
- ) -> Image.Image:
204
- """Render the pose as a control skeleton on a black ``width``x``height`` canvas."""
205
- pose = parse_pose(pose)
206
- style = style if style in STYLES else DEFAULT_STYLE
207
- max_people = max(1, int(max_people))
208
-
209
- if style == "dwpose_rtmlib":
210
- from rtmlib import draw_skeleton
211
- kp, sc = _to_canvas(pose, width, height, fit, hands, face, feet, max_people)
212
- canvas_bgr = np.zeros((height, width, 3), dtype=np.uint8)
213
- canvas_bgr = draw_skeleton(canvas_bgr, kp, sc, openpose_skeleton=False, kpt_thr=KPT_THR)
214
- return Image.fromarray(np.ascontiguousarray(canvas_bgr[..., ::-1]))
215
-
216
- # Author's node path: draw at long side 768, then nearest-upscale (= their ImageScale).
217
- scale = NODE_RENDER_LONG_SIDE / max(width, height)
218
- rw, rh = max(1, round(width * scale)), max(1, round(height * scale))
219
- kp, sc = _to_canvas(pose, rw, rh, fit, hands, face, feet, max_people)
220
- cv = np.zeros((rh, rw, 3), dtype=np.uint8)
221
- for k, s in zip(kp, sc):
222
- cv = _draw_node_style(cv, k, s, style, feet)
223
- img = Image.fromarray(cv)
224
- return img if img.size == (width, height) else img.resize((width, height), Image.NEAREST)
225
-
226
-
227
- def fit_image(image: Image.Image, width: int, height: int, fit: str = "contain") -> Image.Image:
228
- """Fit a user-supplied, already-drawn skeleton image onto a black target canvas."""
229
- image = image.convert("RGB")
230
- src_w, src_h = image.size
231
- sx, sy, ox, oy = _fit_transform(src_w, src_h, width, height, fit if fit in FIT_MODES else "contain")
232
- new_w, new_h = max(1, round(src_w * sx)), max(1, round(src_h * sy))
233
- resized = image.resize((new_w, new_h), Image.NEAREST)
234
- canvas = Image.new("RGB", (width, height), (0, 0, 0))
235
- canvas.paste(resized, (round(ox), round(oy)))
236
- return canvas
237
-
238
-
239
- def mock_pose(image: Optional[Image.Image]) -> dict:
240
- """DEV_MODE stand-in when rtmlib is not installed: a centred standing figure."""
241
- w, h = image.size if image is not None else (768, 1024)
242
- body = {
243
- 0: (0.50, 0.14), 1: (0.48, 0.12), 2: (0.52, 0.12), 3: (0.46, 0.13), 4: (0.54, 0.13),
244
- 5: (0.42, 0.24), 6: (0.58, 0.24), 7: (0.38, 0.38), 8: (0.62, 0.38), 9: (0.36, 0.50),
245
- 10: (0.64, 0.50), 11: (0.45, 0.52), 12: (0.55, 0.52), 13: (0.44, 0.70), 14: (0.56, 0.70),
246
- 15: (0.44, 0.88), 16: (0.56, 0.88),
247
- }
248
- pts = [[body[i][0], body[i][1], 0.9] if i in body else [0.0, 0.0, 0.0] for i in range(NUM_KPTS)]
249
- return {"format": POSE_FORMAT, "width": int(w), "height": int(h), "people": [{"keypoints": pts}]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DWPose (COCO-WholeBody 133) detection and skeleton rendering for Anima-Control-Pose.
2
+
3
+ Detection: rtmlib ``Wholebody`` in ``balanced`` mode (YOLOX-m HumanArt + RTMW-DW-x-L 256x192)
4
+ -- the exact models the adapter author uses, mirrored in the ``detector/`` folder of
5
+ Claquasse/Anima-Control-Pose. CPU / onnxruntime, ~0.5 s per image.
6
+
7
+ Rendering styles:
8
+
9
+ * ``R0_thin`` (default), ``R1_thick``, ``R2_puppet``, ``heatmap`` -- ported from the
10
+ author's ComfyUI node ``ComfyUI-anima-pose-control/pose_render.py`` (same palette, widths
11
+ and keypoint threshold). The author's workflows render at 768 px and ``ImageScale``
12
+ (nearest-exact) to the generation size; we do the same (long side 768, then nearest
13
+ upscale), so line weight relative to the canvas matches the published results. The
14
+ README calls R0_thin "the only one the model trained on".
15
+ * ``dwpose_rtmlib`` -- rtmlib ``draw_skeleton(openpose_skeleton=False)`` drawn into a BGR
16
+ canvas and flipped, i.e. exactly ``scripts/render_skeletons.py`` from the adapter repo.
17
+
18
+ Keypoint JSON (``POSE_FORMAT``) -- coordinates normalised to the *source image*:
19
+ {"format": "anima-pose-v1", "width": W, "height": H,
20
+ "people": [{"keypoints": [[x, y, score], ... 133 items]}]}
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import threading
26
+ from typing import Callable, Optional
27
+
28
+ import numpy as np
29
+ from PIL import Image
30
+
31
+ POSE_FORMAT = "anima-pose-v1"
32
+ NUM_KPTS = 133
33
+ KPT_THR = 0.3
34
+
35
+ BODY = list(range(17))
36
+ FEET = list(range(17, 23))
37
+ FACE = list(range(23, 91))
38
+ HAND = list(range(91, 133))
39
+
40
+ DETECTOR_FILES = {
41
+ "det": "detector/yolox_m_8xb8-300e_humanart-c2c7a14a.onnx",
42
+ "pose": "detector/rtmw-dw-x-l_simcc-cocktail14_270e-256x192_20231122.onnx",
43
+ }
44
+ DET_INPUT_SIZE = (640, 640)
45
+ POSE_INPUT_SIZE = (192, 256)
46
+
47
+ FIT_MODES = ("contain", "cover", "stretch")
48
+ STYLES = ("R0_thin", "R1_thick", "R2_puppet", "heatmap", "dwpose_rtmlib")
49
+ DEFAULT_STYLE = "R0_thin"
50
+ NODE_RENDER_LONG_SIDE = 768
51
+
52
+ # ── Palette / widths: verbatim from the author's pose_render.py ─────────────────────────────
53
+ COCO_LIMBS = [(5, 7), (7, 9), (6, 8), (8, 10), (11, 13), (13, 15), (12, 14), (14, 16),
54
+ (5, 6), (11, 12), (5, 11), (6, 12), (0, 5), (0, 6)]
55
+ _PAL = [(255, 0, 0), (255, 128, 0), (255, 255, 0), (128, 255, 0), (0, 255, 0), (0, 255, 128), (0, 255, 255),
56
+ (0, 128, 255), (0, 0, 255), (128, 0, 255), (255, 0, 255), (255, 0, 128), (180, 180, 180), (220, 220, 220)]
57
+ LIMB_COLOR = {l: _PAL[i % len(_PAL)] for i, l in enumerate(COCO_LIMBS)}
58
+ JOINT_COLOR = [_PAL[i % len(_PAL)] for i in range(17)]
59
+ _W = {"R0_thin": {"stick": 2, "joint": 3}, "R1_thick": {"stick": 8, "joint": 6},
60
+ "R2_puppet": {"stick": 22, "joint": 11}, "heatmap": {"stick": 2, "joint": 3}}
61
+
62
+
63
+ class NoPersonError(RuntimeError):
64
+ pass
65
+
66
+
67
+ # ── Cleaning of off-frame / collapsed joints ─────────────────────────────────────────────────
68
+ # RTMW always predicts all 133 joints. When a limb is outside the frame (e.g. legs cropped off),
69
+ # it parks those joints on the image border with ~0.3 confidence -- just above KPT_THR -- so the
70
+ # skeleton gets feet squashed in at the bottom edge and the adapter dutifully draws them.
71
+ EDGE_BAND = 0.02 # fraction of the image size treated as "on the border"
72
+ EDGE_MIN_SCORE = 0.5 # joints inside the band need at least this confidence
73
+ MIN_SHIN_RATIO = 0.25 # knee->ankle shorter than this x hip->knee = collapsed lower leg
74
+ _PARENT = {7: 5, 8: 6, 9: 7, 10: 8, 13: 11, 14: 12, 15: 13, 16: 14}
75
+ _PARENT.update({i: 15 for i in (17, 18, 19)})
76
+ _PARENT.update({i: 16 for i in (20, 21, 22)})
77
+ _PARENT.update({i: 9 for i in range(91, 112)}) # left hand <- left wrist
78
+ _PARENT.update({i: 10 for i in range(112, 133)}) # right hand <- right wrist
79
+
80
+
81
+ def clean_keypoints(kp: np.ndarray, sc: np.ndarray, w: int, h: int) -> np.ndarray:
82
+ """Return a copy of ``sc`` with off-frame, border-parked and orphaned joints zeroed."""
83
+ sc = np.asarray(sc, dtype=np.float64).copy()
84
+ x, y = kp[:, 0], kp[:, 1]
85
+ outside = (x < 0) | (x > w - 1) | (y < 0) | (y > h - 1)
86
+ bx, by = EDGE_BAND * w, EDGE_BAND * h
87
+ on_edge = (x < bx) | (x > w - 1 - bx) | (y < by) | (y > h - 1 - by)
88
+ sc[outside] = 0.0
89
+ # Torso joints (shoulders/hips) sitting on the frame edge are usually real -- e.g. the
90
+ # waist at the bottom of a waist-up crop -- so the edge rule only applies to limbs,
91
+ # feet and hands, which is where the border-parking happens.
92
+ limb = np.zeros(len(sc), dtype=bool)
93
+ limb[[7, 8, 9, 10, 13, 14, 15, 16]] = True
94
+ limb[17:23] = True
95
+ limb[91:133] = True
96
+ sc[limb & on_edge & (sc < EDGE_MIN_SCORE)] = 0.0
97
+
98
+ def seen(i):
99
+ return sc[i] >= KPT_THR
100
+
101
+ for hip, knee, ankle in ((11, 13, 15), (12, 14, 16)):
102
+ if seen(hip) and seen(knee) and seen(ankle):
103
+ thigh = np.linalg.norm(kp[knee] - kp[hip])
104
+ shin = np.linalg.norm(kp[ankle] - kp[knee])
105
+ if thigh > 0 and shin < MIN_SHIN_RATIO * thigh:
106
+ sc[ankle] = 0.0
107
+ # Parents always have lower indices than their children, so one ordered pass suffices.
108
+ for child in sorted(_PARENT):
109
+ if not seen(_PARENT[child]):
110
+ sc[child] = 0.0
111
+ return sc
112
+
113
+
114
+ _ESTIMATOR = None
115
+ _ESTIMATOR_LOCK = threading.Lock()
116
+
117
+
118
+ def get_estimator(resolve_file: Callable[[str], str]):
119
+ """Build (once) the rtmlib Wholebody estimator. ``resolve_file(repo_path) -> local path``."""
120
+ global _ESTIMATOR
121
+ with _ESTIMATOR_LOCK:
122
+ if _ESTIMATOR is None:
123
+ from rtmlib import Wholebody
124
+ _ESTIMATOR = Wholebody(
125
+ det=resolve_file(DETECTOR_FILES["det"]),
126
+ det_input_size=DET_INPUT_SIZE,
127
+ pose=resolve_file(DETECTOR_FILES["pose"]),
128
+ pose_input_size=POSE_INPUT_SIZE,
129
+ to_openpose=False,
130
+ backend="onnxruntime",
131
+ device="cpu",
132
+ )
133
+ return _ESTIMATOR
134
+
135
+
136
+ def detect(image: Image.Image, estimator) -> dict:
137
+ """Detect every person in ``image``. Returns a pose dict (see module docstring)."""
138
+ rgb = np.asarray(image.convert("RGB"))
139
+ bgr = np.ascontiguousarray(rgb[..., ::-1])
140
+ keypoints, scores = estimator(bgr)
141
+ if keypoints is None or len(keypoints) == 0:
142
+ raise NoPersonError("No person detected in the reference image.")
143
+ keypoints = np.asarray(keypoints, dtype=np.float64).reshape(-1, NUM_KPTS, 2)
144
+ scores = np.asarray(scores, dtype=np.float64).reshape(-1, NUM_KPTS)
145
+ h, w = rgb.shape[:2]
146
+ scores = np.stack([clean_keypoints(k, s, w, h) for k, s in zip(keypoints, scores)])
147
+
148
+ keep = (scores[:, BODY] >= KPT_THR).sum(axis=1) >= 4
149
+ if not keep.any():
150
+ raise NoPersonError("No person detected with enough confident body joints.")
151
+ keypoints, scores = keypoints[keep], scores[keep]
152
+ # Largest person first (the author's node only ever uses person 0).
153
+ areas = [np.ptp(k[s >= KPT_THR], axis=0).prod() if (s >= KPT_THR).sum() > 1 else 0.0
154
+ for k, s in zip(keypoints, scores)]
155
+ order = np.argsort(areas)[::-1]
156
+
157
+ people = []
158
+ for i in order:
159
+ pts = [[float(x) / w, float(y) / h, float(s)] for (x, y), s in zip(keypoints[i], scores[i])]
160
+ people.append({"keypoints": pts})
161
+ return {"format": POSE_FORMAT, "width": int(w), "height": int(h), "people": people}
162
+
163
+
164
+ def parse_pose(pose) -> dict:
165
+ """Accept a pose dict or its JSON string; validate the shape."""
166
+ if isinstance(pose, str):
167
+ pose = json.loads(pose)
168
+ if not isinstance(pose, dict) or pose.get("format") != POSE_FORMAT:
169
+ raise ValueError(f"Pose JSON must have format={POSE_FORMAT!r}.")
170
+ if not pose.get("people"):
171
+ raise ValueError("Pose JSON has no people.")
172
+ for person in pose["people"]:
173
+ if len(person.get("keypoints", [])) != NUM_KPTS:
174
+ raise ValueError(f"Each person needs exactly {NUM_KPTS} keypoints.")
175
+ return pose
176
+
177
+
178
+ def _fit_transform(src_w: int, src_h: int, dst_w: int, dst_h: int, fit: str):
179
+ """Return (sx, sy, ox, oy) mapping source pixels to destination pixels."""
180
+ if fit == "stretch":
181
+ return dst_w / src_w, dst_h / src_h, 0.0, 0.0
182
+ s = max(dst_w / src_w, dst_h / src_h) if fit == "cover" else min(dst_w / src_w, dst_h / src_h)
183
+ return s, s, (dst_w - src_w * s) / 2.0, (dst_h - src_h * s) / 2.0
184
+
185
+
186
+ def _to_canvas(pose: dict, width: int, height: int, fit: str, hands: bool, face: bool, feet: bool,
187
+ max_people: int):
188
+ src_w, src_h = int(pose["width"]), int(pose["height"])
189
+ sx, sy, ox, oy = _fit_transform(src_w, src_h, width, height, fit if fit in FIT_MODES else "contain")
190
+ arr = np.asarray([p["keypoints"] for p in pose["people"][:max_people]], dtype=np.float64)
191
+ kp = np.empty((arr.shape[0], NUM_KPTS, 2), dtype=np.float64)
192
+ kp[..., 0] = arr[..., 0] * src_w * sx + ox
193
+ kp[..., 1] = arr[..., 1] * src_h * sy + oy
194
+ sc = arr[..., 2].copy()
195
+ if not hands:
196
+ sc[:, HAND] = 0.0
197
+ if not face:
198
+ sc[:, FACE] = 0.0
199
+ if not feet:
200
+ sc[:, FEET] = 0.0
201
+ return kp, sc
202
+
203
+
204
+ def _draw_node_style(cv, kp, sc, style, feet):
205
+ """One person, author's node renderer (pose_render.render), on an arbitrary HxW canvas."""
206
+ import cv2
207
+ if style == "heatmap":
208
+ H, W = cv.shape[:2]
209
+ acc = np.zeros((H, W, 3), np.float32)
210
+ for i in BODY + (FEET if feet else []):
211
+ if sc[i] >= KPT_THR:
212
+ x, y = int(round(kp[i][0])), int(round(kp[i][1]))
213
+ if 0 <= x < W and 0 <= y < H:
214
+ b = np.zeros((H, W), np.float32)
215
+ b[y, x] = 1.0
216
+ b = cv2.GaussianBlur(b, (0, 0), 11)
217
+ b /= (b.max() + 1e-9)
218
+ acc += b[..., None] * np.array(JOINT_COLOR[i % 17], np.float32)
219
+ return np.maximum(cv, np.clip(acc, 0, 255).astype(np.uint8))
220
+ cfg = _W[style]
221
+ for a, b in COCO_LIMBS:
222
+ if sc[a] >= KPT_THR and sc[b] >= KPT_THR:
223
+ cv2.line(cv, (int(kp[a][0]), int(kp[a][1])), (int(kp[b][0]), int(kp[b][1])), LIMB_COLOR[(a, b)], cfg["stick"])
224
+ for i in BODY:
225
+ if sc[i] >= KPT_THR:
226
+ cv2.circle(cv, (int(kp[i][0]), int(kp[i][1])), cfg["joint"], (255, 255, 255), -1)
227
+ for i in FEET:
228
+ if sc[i] >= KPT_THR:
229
+ cv2.circle(cv, (int(kp[i][0]), int(kp[i][1])), max(1, cfg["joint"] // 2), (255, 255, 255), -1)
230
+ if style == "R0_thin":
231
+ for i in HAND:
232
+ if sc[i] >= KPT_THR:
233
+ cv2.circle(cv, (int(kp[i][0]), int(kp[i][1])), 2, (0, 255, 255), -1)
234
+ for i in FACE:
235
+ if sc[i] >= KPT_THR:
236
+ cv2.circle(cv, (int(kp[i][0]), int(kp[i][1])), 2, (255, 255, 255), -1)
237
+ return cv
238
+
239
+
240
+ def render(
241
+ pose,
242
+ width: int,
243
+ height: int,
244
+ *,
245
+ style: str = DEFAULT_STYLE,
246
+ fit: str = "contain",
247
+ hands: bool = True,
248
+ face: bool = True,
249
+ feet: bool = True,
250
+ max_people: int = 1,
251
+ ) -> Image.Image:
252
+ """Render the pose as a control skeleton on a black ``width``x``height`` canvas."""
253
+ pose = parse_pose(pose)
254
+ style = style if style in STYLES else DEFAULT_STYLE
255
+ max_people = max(1, int(max_people))
256
+
257
+ if style == "dwpose_rtmlib":
258
+ from rtmlib import draw_skeleton
259
+ kp, sc = _to_canvas(pose, width, height, fit, hands, face, feet, max_people)
260
+ canvas_bgr = np.zeros((height, width, 3), dtype=np.uint8)
261
+ canvas_bgr = draw_skeleton(canvas_bgr, kp, sc, openpose_skeleton=False, kpt_thr=KPT_THR)
262
+ return Image.fromarray(np.ascontiguousarray(canvas_bgr[..., ::-1]))
263
+
264
+ # Author's node path: draw at long side 768, then nearest-upscale (= their ImageScale).
265
+ scale = NODE_RENDER_LONG_SIDE / max(width, height)
266
+ rw, rh = max(1, round(width * scale)), max(1, round(height * scale))
267
+ kp, sc = _to_canvas(pose, rw, rh, fit, hands, face, feet, max_people)
268
+ cv = np.zeros((rh, rw, 3), dtype=np.uint8)
269
+ for k, s in zip(kp, sc):
270
+ cv = _draw_node_style(cv, k, s, style, feet)
271
+ img = Image.fromarray(cv)
272
+ return img if img.size == (width, height) else img.resize((width, height), Image.NEAREST)
273
+
274
+
275
+ def fit_image(image: Image.Image, width: int, height: int, fit: str = "contain") -> Image.Image:
276
+ """Fit a user-supplied, already-drawn skeleton image onto a black target canvas."""
277
+ image = image.convert("RGB")
278
+ src_w, src_h = image.size
279
+ sx, sy, ox, oy = _fit_transform(src_w, src_h, width, height, fit if fit in FIT_MODES else "contain")
280
+ new_w, new_h = max(1, round(src_w * sx)), max(1, round(src_h * sy))
281
+ resized = image.resize((new_w, new_h), Image.NEAREST)
282
+ canvas = Image.new("RGB", (width, height), (0, 0, 0))
283
+ canvas.paste(resized, (round(ox), round(oy)))
284
+ return canvas
285
+
286
+
287
+ def mock_pose(image: Optional[Image.Image]) -> dict:
288
+ """DEV_MODE stand-in when rtmlib is not installed: a centred standing figure."""
289
+ w, h = image.size if image is not None else (768, 1024)
290
+ body = {
291
+ 0: (0.50, 0.14), 1: (0.48, 0.12), 2: (0.52, 0.12), 3: (0.46, 0.13), 4: (0.54, 0.13),
292
+ 5: (0.42, 0.24), 6: (0.58, 0.24), 7: (0.38, 0.38), 8: (0.62, 0.38), 9: (0.36, 0.50),
293
+ 10: (0.64, 0.50), 11: (0.45, 0.52), 12: (0.55, 0.52), 13: (0.44, 0.70), 14: (0.56, 0.70),
294
+ 15: (0.44, 0.88), 16: (0.56, 0.88),
295
+ }
296
+ pts = [[body[i][0], body[i][1], 0.9] if i in body else [0.0, 0.0, 0.0] for i in range(NUM_KPTS)]
297
+ return {"format": POSE_FORMAT, "width": int(w), "height": int(h), "people": [{"keypoints": pts}]}