root
commited on
Commit
·
6879e29
1
Parent(s):
42adb07
changin g
Browse files- sampler.py +2 -2
- src/dwpose/__pycache__/wholebody.cpython-310.pyc +0 -0
- src/dwpose/wholebody.py +499 -6
sampler.py
CHANGED
|
@@ -10,8 +10,8 @@ handler = EndpointHandler()
|
|
| 10 |
# Define sample inputs
|
| 11 |
inputs = {
|
| 12 |
"inputs": {
|
| 13 |
-
"ref_image_url": "https://cdn.discordapp.com/attachments/1237667074210267217/
|
| 14 |
-
"video_url": "https://cdn.discordapp.com/attachments/1237667074210267217/
|
| 15 |
"length": 24,
|
| 16 |
"num_inference_steps": 25,
|
| 17 |
"cfg": 3.5,
|
|
|
|
| 10 |
# Define sample inputs
|
| 11 |
inputs = {
|
| 12 |
"inputs": {
|
| 13 |
+
"ref_image_url": "https://cdn.discordapp.com/attachments/1237667074210267217/1246572710679806003/image.jpg?ex=665ce0ce&is=665b8f4e&hm=b8a0caf3080336aac412746681efb7189d5cb4c3e2c0b8ea52696402bbb82a91&",
|
| 14 |
+
"video_url": "https://cdn.discordapp.com/attachments/1237667074210267217/1246572710964756593/pose.mp4?ex=665ce0ce&is=665b8f4e&hm=32748799cab55da4040143c5449f497c1440ecd13ba9886e6b12648e1d72e9fc&",
|
| 15 |
"length": 24,
|
| 16 |
"num_inference_steps": 25,
|
| 17 |
"cfg": 3.5,
|
src/dwpose/__pycache__/wholebody.cpython-310.pyc
CHANGED
|
Binary files a/src/dwpose/__pycache__/wholebody.cpython-310.pyc and b/src/dwpose/__pycache__/wholebody.cpython-310.pyc differ
|
|
|
src/dwpose/wholebody.py
CHANGED
|
@@ -8,15 +8,507 @@ import onnxruntime as ort
|
|
| 8 |
import os
|
| 9 |
import sys
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
from onnxdet import inference_detector
|
| 15 |
-
from onnxpose import inference_pose
|
| 16 |
|
| 17 |
ModelDataPathPrefix = Path("./pretrained_weights")
|
| 18 |
|
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|
|
| 32 |
)
|
| 33 |
|
| 34 |
def __call__(self, oriImg):
|
| 35 |
-
det_result = inference_detector(self.session_det, oriImg)
|
| 36 |
-
keypoints, scores = inference_pose(self.session_pose, det_result, oriImg)
|
| 37 |
|
| 38 |
keypoints_info = np.concatenate((keypoints, scores[..., None]), axis=-1)
|
| 39 |
# compute neck joint
|
|
@@ -51,3 +543,4 @@ class Wholebody:
|
|
| 51 |
keypoints, scores = keypoints_info[..., :2], keypoints_info[..., 2]
|
| 52 |
|
| 53 |
return keypoints, scores
|
|
|
|
|
|
| 8 |
import os
|
| 9 |
import sys
|
| 10 |
|
| 11 |
+
from typing import List, Tuple
|
| 12 |
+
|
| 13 |
+
import cv2
|
| 14 |
+
import numpy as np
|
| 15 |
+
import onnxruntime as ort
|
| 16 |
|
|
|
|
|
|
|
| 17 |
|
| 18 |
ModelDataPathPrefix = Path("./pretrained_weights")
|
| 19 |
|
| 20 |
class Wholebody:
|
| 21 |
+
# https://github.com/IDEA-Research/DWPose
|
| 22 |
+
def nms(self, boxes, scores, nms_thr):
|
| 23 |
+
"""Single class NMS implemented in Numpy."""
|
| 24 |
+
x1 = boxes[:, 0]
|
| 25 |
+
y1 = boxes[:, 1]
|
| 26 |
+
x2 = boxes[:, 2]
|
| 27 |
+
y2 = boxes[:, 3]
|
| 28 |
+
|
| 29 |
+
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
|
| 30 |
+
order = scores.argsort()[::-1]
|
| 31 |
+
|
| 32 |
+
keep = []
|
| 33 |
+
while order.size > 0:
|
| 34 |
+
i = order[0]
|
| 35 |
+
keep.append(i)
|
| 36 |
+
xx1 = np.maximum(x1[i], x1[order[1:]])
|
| 37 |
+
yy1 = np.maximum(y1[i], y1[order[1:]])
|
| 38 |
+
xx2 = np.minimum(x2[i], x2[order[1:]])
|
| 39 |
+
yy2 = np.minimum(y2[i], y2[order[1:]])
|
| 40 |
+
|
| 41 |
+
w = np.maximum(0.0, xx2 - xx1 + 1)
|
| 42 |
+
h = np.maximum(0.0, yy2 - yy1 + 1)
|
| 43 |
+
inter = w * h
|
| 44 |
+
ovr = inter / (areas[i] + areas[order[1:]] - inter)
|
| 45 |
+
|
| 46 |
+
inds = np.where(ovr <= nms_thr)[0]
|
| 47 |
+
order = order[inds + 1]
|
| 48 |
+
|
| 49 |
+
return keep
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def multiclass_nms(self, boxes, scores, nms_thr, score_thr):
|
| 53 |
+
"""Multiclass NMS implemented in Numpy. Class-aware version."""
|
| 54 |
+
final_dets = []
|
| 55 |
+
num_classes = scores.shape[1]
|
| 56 |
+
for cls_ind in range(num_classes):
|
| 57 |
+
cls_scores = scores[:, cls_ind]
|
| 58 |
+
valid_score_mask = cls_scores > score_thr
|
| 59 |
+
if valid_score_mask.sum() == 0:
|
| 60 |
+
continue
|
| 61 |
+
else:
|
| 62 |
+
valid_scores = cls_scores[valid_score_mask]
|
| 63 |
+
valid_boxes = boxes[valid_score_mask]
|
| 64 |
+
keep = self.nms(valid_boxes, valid_scores, nms_thr)
|
| 65 |
+
if len(keep) > 0:
|
| 66 |
+
cls_inds = np.ones((len(keep), 1)) * cls_ind
|
| 67 |
+
dets = np.concatenate(
|
| 68 |
+
[valid_boxes[keep], valid_scores[keep, None], cls_inds], 1
|
| 69 |
+
)
|
| 70 |
+
final_dets.append(dets)
|
| 71 |
+
if len(final_dets) == 0:
|
| 72 |
+
return None
|
| 73 |
+
return np.concatenate(final_dets, 0)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def demo_postprocess(self, outputs, img_size, p6=False):
|
| 77 |
+
grids = []
|
| 78 |
+
expanded_strides = []
|
| 79 |
+
strides = [8, 16, 32] if not p6 else [8, 16, 32, 64]
|
| 80 |
+
|
| 81 |
+
hsizes = [img_size[0] // stride for stride in strides]
|
| 82 |
+
wsizes = [img_size[1] // stride for stride in strides]
|
| 83 |
+
|
| 84 |
+
for hsize, wsize, stride in zip(hsizes, wsizes, strides):
|
| 85 |
+
xv, yv = np.meshgrid(np.arange(wsize), np.arange(hsize))
|
| 86 |
+
grid = np.stack((xv, yv), 2).reshape(1, -1, 2)
|
| 87 |
+
grids.append(grid)
|
| 88 |
+
shape = grid.shape[:2]
|
| 89 |
+
expanded_strides.append(np.full((*shape, 1), stride))
|
| 90 |
+
|
| 91 |
+
grids = np.concatenate(grids, 1)
|
| 92 |
+
expanded_strides = np.concatenate(expanded_strides, 1)
|
| 93 |
+
outputs[..., :2] = (outputs[..., :2] + grids) * expanded_strides
|
| 94 |
+
outputs[..., 2:4] = np.exp(outputs[..., 2:4]) * expanded_strides
|
| 95 |
+
|
| 96 |
+
return outputs
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def det_preprocess(self, img, input_size, swap=(2, 0, 1)):
|
| 100 |
+
if len(img.shape) == 3:
|
| 101 |
+
padded_img = np.ones((input_size[0], input_size[1], 3), dtype=np.uint8) * 114
|
| 102 |
+
else:
|
| 103 |
+
padded_img = np.ones(input_size, dtype=np.uint8) * 114
|
| 104 |
+
|
| 105 |
+
r = min(input_size[0] / img.shape[0], input_size[1] / img.shape[1])
|
| 106 |
+
resized_img = cv2.resize(
|
| 107 |
+
img,
|
| 108 |
+
(int(img.shape[1] * r), int(img.shape[0] * r)),
|
| 109 |
+
interpolation=cv2.INTER_LINEAR,
|
| 110 |
+
).astype(np.uint8)
|
| 111 |
+
padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img
|
| 112 |
+
|
| 113 |
+
padded_img = padded_img.transpose(swap)
|
| 114 |
+
padded_img = np.ascontiguousarray(padded_img, dtype=np.float32)
|
| 115 |
+
return padded_img, r
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def inference_detector(self, session, oriImg):
|
| 119 |
+
input_shape = (640, 640)
|
| 120 |
+
img, ratio = self.det_preprocess(oriImg, input_shape)
|
| 121 |
+
|
| 122 |
+
ort_inputs = {session.get_inputs()[0].name: img[None, :, :, :]}
|
| 123 |
+
output = session.run(None, ort_inputs)
|
| 124 |
+
predictions = self.demo_postprocess(output[0], input_shape)[0]
|
| 125 |
+
|
| 126 |
+
boxes = predictions[:, :4]
|
| 127 |
+
scores = predictions[:, 4:5] * predictions[:, 5:]
|
| 128 |
+
|
| 129 |
+
boxes_xyxy = np.ones_like(boxes)
|
| 130 |
+
boxes_xyxy[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0
|
| 131 |
+
boxes_xyxy[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0
|
| 132 |
+
boxes_xyxy[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0
|
| 133 |
+
boxes_xyxy[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0
|
| 134 |
+
boxes_xyxy /= ratio
|
| 135 |
+
dets = self.multiclass_nms(boxes_xyxy, scores, nms_thr=0.45, score_thr=0.1)
|
| 136 |
+
if dets is not None:
|
| 137 |
+
final_boxes, final_scores, final_cls_inds = dets[:, :4], dets[:, 4], dets[:, 5]
|
| 138 |
+
isscore = final_scores > 0.3
|
| 139 |
+
iscat = final_cls_inds == 0
|
| 140 |
+
isbbox = [i and j for (i, j) in zip(isscore, iscat)]
|
| 141 |
+
final_boxes = final_boxes[isbbox]
|
| 142 |
+
else:
|
| 143 |
+
return []
|
| 144 |
+
|
| 145 |
+
return final_boxes
|
| 146 |
+
|
| 147 |
+
def pose_preprocess(self, img: np.ndarray, out_bbox, input_size: Tuple[int, int] = (192, 256)) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 148 |
+
"""Do preprocessing for RTMPose model inference.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
img (np.ndarray): Input image in shape.
|
| 152 |
+
input_size (tuple): Input image size in shape (w, h).
|
| 153 |
+
|
| 154 |
+
Returns:
|
| 155 |
+
tuple:
|
| 156 |
+
- resized_img (np.ndarray): Preprocessed image.
|
| 157 |
+
- center (np.ndarray): Center of image.
|
| 158 |
+
- scale (np.ndarray): Scale of image.
|
| 159 |
+
"""
|
| 160 |
+
# get shape of image
|
| 161 |
+
img_shape = img.shape[:2]
|
| 162 |
+
out_img, out_center, out_scale = [], [], []
|
| 163 |
+
if len(out_bbox) == 0:
|
| 164 |
+
out_bbox = [[0, 0, img_shape[1], img_shape[0]]]
|
| 165 |
+
for i in range(len(out_bbox)):
|
| 166 |
+
x0 = out_bbox[i][0]
|
| 167 |
+
y0 = out_bbox[i][1]
|
| 168 |
+
x1 = out_bbox[i][2]
|
| 169 |
+
y1 = out_bbox[i][3]
|
| 170 |
+
bbox = np.array([x0, y0, x1, y1])
|
| 171 |
+
|
| 172 |
+
# get center and scale
|
| 173 |
+
center, scale = self.bbox_xyxy2cs(bbox, padding=1.25)
|
| 174 |
+
|
| 175 |
+
# do affine transformation
|
| 176 |
+
resized_img, scale = self.top_down_affine(input_size, scale, center, img)
|
| 177 |
+
|
| 178 |
+
# normalize image
|
| 179 |
+
mean = np.array([123.675, 116.28, 103.53])
|
| 180 |
+
std = np.array([58.395, 57.12, 57.375])
|
| 181 |
+
resized_img = (resized_img - mean) / std
|
| 182 |
+
|
| 183 |
+
out_img.append(resized_img)
|
| 184 |
+
out_center.append(center)
|
| 185 |
+
out_scale.append(scale)
|
| 186 |
+
|
| 187 |
+
return out_img, out_center, out_scale
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def inference(self, sess: ort.InferenceSession, img: np.ndarray) -> np.ndarray:
|
| 191 |
+
"""Inference RTMPose model.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
sess (ort.InferenceSession): ONNXRuntime session.
|
| 195 |
+
img (np.ndarray): Input image in shape.
|
| 196 |
+
|
| 197 |
+
Returns:
|
| 198 |
+
outputs (np.ndarray): Output of RTMPose model.
|
| 199 |
+
"""
|
| 200 |
+
all_out = []
|
| 201 |
+
# build input
|
| 202 |
+
for i in range(len(img)):
|
| 203 |
+
input = [img[i].transpose(2, 0, 1)]
|
| 204 |
+
|
| 205 |
+
# build output
|
| 206 |
+
sess_input = {sess.get_inputs()[0].name: input}
|
| 207 |
+
sess_output = []
|
| 208 |
+
for out in sess.get_outputs():
|
| 209 |
+
sess_output.append(out.name)
|
| 210 |
+
|
| 211 |
+
# run model
|
| 212 |
+
outputs = sess.run(sess_output, sess_input)
|
| 213 |
+
all_out.append(outputs)
|
| 214 |
+
|
| 215 |
+
return all_out
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def postprocess(
|
| 219 |
+
self,
|
| 220 |
+
outputs: List[np.ndarray],
|
| 221 |
+
model_input_size: Tuple[int, int],
|
| 222 |
+
center: Tuple[int, int],
|
| 223 |
+
scale: Tuple[int, int],
|
| 224 |
+
simcc_split_ratio: float = 2.0,
|
| 225 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 226 |
+
"""Postprocess for RTMPose model output.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
outputs (np.ndarray): Output of RTMPose model.
|
| 230 |
+
model_input_size (tuple): RTMPose model Input image size.
|
| 231 |
+
center (tuple): Center of bbox in shape (x, y).
|
| 232 |
+
scale (tuple): Scale of bbox in shape (w, h).
|
| 233 |
+
simcc_split_ratio (float): Split ratio of simcc.
|
| 234 |
+
|
| 235 |
+
Returns:
|
| 236 |
+
tuple:
|
| 237 |
+
- keypoints (np.ndarray): Rescaled keypoints.
|
| 238 |
+
- scores (np.ndarray): Model predict scores.
|
| 239 |
+
"""
|
| 240 |
+
all_key = []
|
| 241 |
+
all_score = []
|
| 242 |
+
for i in range(len(outputs)):
|
| 243 |
+
# use simcc to decode
|
| 244 |
+
simcc_x, simcc_y = outputs[i]
|
| 245 |
+
keypoints, scores = self.decode(simcc_x, simcc_y, simcc_split_ratio)
|
| 246 |
+
|
| 247 |
+
# rescale keypoints
|
| 248 |
+
keypoints = keypoints / model_input_size * scale[i] + center[i] - scale[i] / 2
|
| 249 |
+
all_key.append(keypoints[0])
|
| 250 |
+
all_score.append(scores[0])
|
| 251 |
+
|
| 252 |
+
return np.array(all_key), np.array(all_score)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def bbox_xyxy2cs(
|
| 256 |
+
self,
|
| 257 |
+
bbox: np.ndarray, padding: float = 1.0
|
| 258 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 259 |
+
"""Transform the bbox format from (x,y,w,h) into (center, scale)
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
bbox (ndarray): Bounding box(es) in shape (4,) or (n, 4), formatted
|
| 263 |
+
as (left, top, right, bottom)
|
| 264 |
+
padding (float): BBox padding factor that will be multilied to scale.
|
| 265 |
+
Default: 1.0
|
| 266 |
+
|
| 267 |
+
Returns:
|
| 268 |
+
tuple: A tuple containing center and scale.
|
| 269 |
+
- np.ndarray[float32]: Center (x, y) of the bbox in shape (2,) or
|
| 270 |
+
(n, 2)
|
| 271 |
+
- np.ndarray[float32]: Scale (w, h) of the bbox in shape (2,) or
|
| 272 |
+
(n, 2)
|
| 273 |
+
"""
|
| 274 |
+
# convert single bbox from (4, ) to (1, 4)
|
| 275 |
+
dim = bbox.ndim
|
| 276 |
+
if dim == 1:
|
| 277 |
+
bbox = bbox[None, :]
|
| 278 |
+
|
| 279 |
+
# get bbox center and scale
|
| 280 |
+
x1, y1, x2, y2 = np.hsplit(bbox, [1, 2, 3])
|
| 281 |
+
center = np.hstack([x1 + x2, y1 + y2]) * 0.5
|
| 282 |
+
scale = np.hstack([x2 - x1, y2 - y1]) * padding
|
| 283 |
+
|
| 284 |
+
if dim == 1:
|
| 285 |
+
center = center[0]
|
| 286 |
+
scale = scale[0]
|
| 287 |
+
|
| 288 |
+
return center, scale
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def _fix_aspect_ratio(self, bbox_scale: np.ndarray, aspect_ratio: float) -> np.ndarray:
|
| 292 |
+
"""Extend the scale to match the given aspect ratio.
|
| 293 |
+
|
| 294 |
+
Args:
|
| 295 |
+
scale (np.ndarray): The image scale (w, h) in shape (2, )
|
| 296 |
+
aspect_ratio (float): The ratio of ``w/h``
|
| 297 |
+
|
| 298 |
+
Returns:
|
| 299 |
+
np.ndarray: The reshaped image scale in (2, )
|
| 300 |
+
"""
|
| 301 |
+
w, h = np.hsplit(bbox_scale, [1])
|
| 302 |
+
bbox_scale = np.where(
|
| 303 |
+
w > h * aspect_ratio,
|
| 304 |
+
np.hstack([w, w / aspect_ratio]),
|
| 305 |
+
np.hstack([h * aspect_ratio, h]),
|
| 306 |
+
)
|
| 307 |
+
return bbox_scale
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _rotate_point(self, pt: np.ndarray, angle_rad: float) -> np.ndarray:
|
| 311 |
+
"""Rotate a point by an angle.
|
| 312 |
+
|
| 313 |
+
Args:
|
| 314 |
+
pt (np.ndarray): 2D point coordinates (x, y) in shape (2, )
|
| 315 |
+
angle_rad (float): rotation angle in radian
|
| 316 |
+
|
| 317 |
+
Returns:
|
| 318 |
+
np.ndarray: Rotated point in shape (2, )
|
| 319 |
+
"""
|
| 320 |
+
sn, cs = np.sin(angle_rad), np.cos(angle_rad)
|
| 321 |
+
rot_mat = np.array([[cs, -sn], [sn, cs]])
|
| 322 |
+
return rot_mat @ pt
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _get_3rd_point(self, a: np.ndarray, b: np.ndarray) -> np.ndarray:
|
| 326 |
+
"""To calculate the affine matrix, three pairs of points are required. This
|
| 327 |
+
function is used to get the 3rd point, given 2D points a & b.
|
| 328 |
+
|
| 329 |
+
The 3rd point is defined by rotating vector `a - b` by 90 degrees
|
| 330 |
+
anticlockwise, using b as the rotation center.
|
| 331 |
+
|
| 332 |
+
Args:
|
| 333 |
+
a (np.ndarray): The 1st point (x,y) in shape (2, )
|
| 334 |
+
b (np.ndarray): The 2nd point (x,y) in shape (2, )
|
| 335 |
+
|
| 336 |
+
Returns:
|
| 337 |
+
np.ndarray: The 3rd point.
|
| 338 |
+
"""
|
| 339 |
+
direction = a - b
|
| 340 |
+
c = b + np.r_[-direction[1], direction[0]]
|
| 341 |
+
return c
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def get_warp_matrix(
|
| 345 |
+
self,
|
| 346 |
+
center: np.ndarray,
|
| 347 |
+
scale: np.ndarray,
|
| 348 |
+
rot: float,
|
| 349 |
+
output_size: Tuple[int, int],
|
| 350 |
+
shift: Tuple[float, float] = (0.0, 0.0),
|
| 351 |
+
inv: bool = False,
|
| 352 |
+
) -> np.ndarray:
|
| 353 |
+
"""Calculate the affine transformation matrix that can warp the bbox area
|
| 354 |
+
in the input image to the output size.
|
| 355 |
+
|
| 356 |
+
Args:
|
| 357 |
+
center (np.ndarray[2, ]): Center of the bounding box (x, y).
|
| 358 |
+
scale (np.ndarray[2, ]): Scale of the bounding box
|
| 359 |
+
wrt [width, height].
|
| 360 |
+
rot (float): Rotation angle (degree).
|
| 361 |
+
output_size (np.ndarray[2, ] | list(2,)): Size of the
|
| 362 |
+
destination heatmaps.
|
| 363 |
+
shift (0-100%): Shift translation ratio wrt the width/height.
|
| 364 |
+
Default (0., 0.).
|
| 365 |
+
inv (bool): Option to inverse the affine transform direction.
|
| 366 |
+
(inv=False: src->dst or inv=True: dst->src)
|
| 367 |
+
|
| 368 |
+
Returns:
|
| 369 |
+
np.ndarray: A 2x3 transformation matrix
|
| 370 |
+
"""
|
| 371 |
+
shift = np.array(shift)
|
| 372 |
+
src_w = scale[0]
|
| 373 |
+
dst_w = output_size[0]
|
| 374 |
+
dst_h = output_size[1]
|
| 375 |
+
|
| 376 |
+
# compute transformation matrix
|
| 377 |
+
rot_rad = np.deg2rad(rot)
|
| 378 |
+
src_dir = self._rotate_point(np.array([0.0, src_w * -0.5]), rot_rad)
|
| 379 |
+
dst_dir = np.array([0.0, dst_w * -0.5])
|
| 380 |
+
|
| 381 |
+
# get four corners of the src rectangle in the original image
|
| 382 |
+
src = np.zeros((3, 2), dtype=np.float32)
|
| 383 |
+
src[0, :] = center + scale * shift
|
| 384 |
+
src[1, :] = center + src_dir + scale * shift
|
| 385 |
+
src[2, :] = self._get_3rd_point(src[0, :], src[1, :])
|
| 386 |
+
|
| 387 |
+
# get four corners of the dst rectangle in the input image
|
| 388 |
+
dst = np.zeros((3, 2), dtype=np.float32)
|
| 389 |
+
dst[0, :] = [dst_w * 0.5, dst_h * 0.5]
|
| 390 |
+
dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5]) + dst_dir
|
| 391 |
+
dst[2, :] = self._get_3rd_point(dst[0, :], dst[1, :])
|
| 392 |
+
|
| 393 |
+
if inv:
|
| 394 |
+
warp_mat = cv2.getAffineTransform(np.float32(dst), np.float32(src))
|
| 395 |
+
else:
|
| 396 |
+
warp_mat = cv2.getAffineTransform(np.float32(src), np.float32(dst))
|
| 397 |
+
|
| 398 |
+
return warp_mat
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def top_down_affine(
|
| 402 |
+
self, input_size: dict, bbox_scale: dict, bbox_center: dict, img: np.ndarray
|
| 403 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 404 |
+
"""Get the bbox image as the model input by affine transform.
|
| 405 |
+
|
| 406 |
+
Args:
|
| 407 |
+
input_size (dict): The input size of the model.
|
| 408 |
+
bbox_scale (dict): The bbox scale of the img.
|
| 409 |
+
bbox_center (dict): The bbox center of the img.
|
| 410 |
+
img (np.ndarray): The original image.
|
| 411 |
+
|
| 412 |
+
Returns:
|
| 413 |
+
tuple: A tuple containing center and scale.
|
| 414 |
+
- np.ndarray[float32]: img after affine transform.
|
| 415 |
+
- np.ndarray[float32]: bbox scale after affine transform.
|
| 416 |
+
"""
|
| 417 |
+
w, h = input_size
|
| 418 |
+
warp_size = (int(w), int(h))
|
| 419 |
+
|
| 420 |
+
# reshape bbox to fixed aspect ratio
|
| 421 |
+
bbox_scale = self._fix_aspect_ratio(bbox_scale, aspect_ratio=w / h)
|
| 422 |
+
|
| 423 |
+
# get the affine matrix
|
| 424 |
+
center = bbox_center
|
| 425 |
+
scale = bbox_scale
|
| 426 |
+
rot = 0
|
| 427 |
+
warp_mat = self.get_warp_matrix(center, scale, rot, output_size=(w, h))
|
| 428 |
+
|
| 429 |
+
# do affine transform
|
| 430 |
+
img = cv2.warpAffine(img, warp_mat, warp_size, flags=cv2.INTER_LINEAR)
|
| 431 |
+
|
| 432 |
+
return img, bbox_scale
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def get_simcc_maximum(
|
| 436 |
+
self, simcc_x: np.ndarray, simcc_y: np.ndarray
|
| 437 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 438 |
+
"""Get maximum response location and value from simcc representations.
|
| 439 |
+
|
| 440 |
+
Note:
|
| 441 |
+
instance number: N
|
| 442 |
+
num_keypoints: K
|
| 443 |
+
heatmap height: H
|
| 444 |
+
heatmap width: W
|
| 445 |
+
|
| 446 |
+
Args:
|
| 447 |
+
simcc_x (np.ndarray): x-axis SimCC in shape (K, Wx) or (N, K, Wx)
|
| 448 |
+
simcc_y (np.ndarray): y-axis SimCC in shape (K, Wy) or (N, K, Wy)
|
| 449 |
+
|
| 450 |
+
Returns:
|
| 451 |
+
tuple:
|
| 452 |
+
- locs (np.ndarray): locations of maximum heatmap responses in shape
|
| 453 |
+
(K, 2) or (N, K, 2)
|
| 454 |
+
- vals (np.ndarray): values of maximum heatmap responses in shape
|
| 455 |
+
(K,) or (N, K)
|
| 456 |
+
"""
|
| 457 |
+
N, K, Wx = simcc_x.shape
|
| 458 |
+
simcc_x = simcc_x.reshape(N * K, -1)
|
| 459 |
+
simcc_y = simcc_y.reshape(N * K, -1)
|
| 460 |
+
|
| 461 |
+
# get maximum value locations
|
| 462 |
+
x_locs = np.argmax(simcc_x, axis=1)
|
| 463 |
+
y_locs = np.argmax(simcc_y, axis=1)
|
| 464 |
+
locs = np.stack((x_locs, y_locs), axis=-1).astype(np.float32)
|
| 465 |
+
max_val_x = np.amax(simcc_x, axis=1)
|
| 466 |
+
max_val_y = np.amax(simcc_y, axis=1)
|
| 467 |
+
|
| 468 |
+
# get maximum value across x and y axis
|
| 469 |
+
mask = max_val_x > max_val_y
|
| 470 |
+
max_val_x[mask] = max_val_y[mask]
|
| 471 |
+
vals = max_val_x
|
| 472 |
+
locs[vals <= 0.0] = -1
|
| 473 |
+
|
| 474 |
+
# reshape
|
| 475 |
+
locs = locs.reshape(N, K, 2)
|
| 476 |
+
vals = vals.reshape(N, K)
|
| 477 |
+
|
| 478 |
+
return locs, vals
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def decode(
|
| 482 |
+
self, simcc_x: np.ndarray, simcc_y: np.ndarray, simcc_split_ratio
|
| 483 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 484 |
+
"""Modulate simcc distribution with Gaussian.
|
| 485 |
+
|
| 486 |
+
Args:
|
| 487 |
+
simcc_x (np.ndarray[K, Wx]): model predicted simcc in x.
|
| 488 |
+
simcc_y (np.ndarray[K, Wy]): model predicted simcc in y.
|
| 489 |
+
simcc_split_ratio (int): The split ratio of simcc.
|
| 490 |
+
|
| 491 |
+
Returns:
|
| 492 |
+
tuple: A tuple containing center and scale.
|
| 493 |
+
- np.ndarray[float32]: keypoints in shape (K, 2) or (n, K, 2)
|
| 494 |
+
- np.ndarray[float32]: scores in shape (K,) or (n, K)
|
| 495 |
+
"""
|
| 496 |
+
keypoints, scores = self.get_simcc_maximum(simcc_x, simcc_y)
|
| 497 |
+
keypoints /= simcc_split_ratio
|
| 498 |
+
|
| 499 |
+
return keypoints, scores
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def inference_pose(self, session, out_bbox, oriImg):
|
| 503 |
+
h, w = session.get_inputs()[0].shape[2:]
|
| 504 |
+
model_input_size = (w, h)
|
| 505 |
+
resized_img, center, scale = self.pose_preprocess(oriImg, out_bbox, model_input_size)
|
| 506 |
+
outputs = self.inference(session, resized_img)
|
| 507 |
+
keypoints, scores = self.postprocess(outputs, model_input_size, center, scale)
|
| 508 |
+
|
| 509 |
+
return keypoints, scores
|
| 510 |
+
|
| 511 |
+
|
| 512 |
def __init__(self, device="cuda:0"):
|
| 513 |
providers = (
|
| 514 |
["CPUExecutionProvider"] if device == "cpu" else ["CUDAExecutionProvider"]
|
|
|
|
| 524 |
)
|
| 525 |
|
| 526 |
def __call__(self, oriImg):
|
| 527 |
+
det_result = self.inference_detector(self.session_det, oriImg)
|
| 528 |
+
keypoints, scores = self.inference_pose(self.session_pose, det_result, oriImg)
|
| 529 |
|
| 530 |
keypoints_info = np.concatenate((keypoints, scores[..., None]), axis=-1)
|
| 531 |
# compute neck joint
|
|
|
|
| 543 |
keypoints, scores = keypoints_info[..., :2], keypoints_info[..., 2]
|
| 544 |
|
| 545 |
return keypoints, scores
|
| 546 |
+
|