Fangming Guo commited on
Commit
dd9450f
·
verified ·
1 Parent(s): 2b0ddce

Upload 47 files

Browse files
Files changed (48) hide show
  1. .gitattributes +2 -0
  2. AX615/yolov8l-pose_640x640_npu1.axmodel +3 -0
  3. AX615/yolov8l-pose_640x640_npu2.axmodel +3 -0
  4. AX615/yolov8m-pose_640x640_npu1.axmodel +3 -0
  5. AX615/yolov8m-pose_640x640_npu2.axmodel +3 -0
  6. AX615/yolov8n-pose_640x640_npu1.axmodel +3 -0
  7. AX615/yolov8n-pose_640x640_npu2.axmodel +3 -0
  8. AX615/yolov8s-pose_640x640_npu1.axmodel +3 -0
  9. AX615/yolov8s-pose_640x640_npu2.axmodel +3 -0
  10. AX615/yolov8x-pose_640x640_npu1.axmodel +3 -0
  11. AX615/yolov8x-pose_640x640_npu2.axmodel +3 -0
  12. AX620E/yolov8l-pose_640x640_npu1.axmodel +3 -0
  13. AX620E/yolov8l-pose_640x640_npu2.axmodel +3 -0
  14. AX620E/yolov8m-pose_640x640_npu1.axmodel +3 -0
  15. AX620E/yolov8m-pose_640x640_npu2.axmodel +3 -0
  16. AX620E/yolov8n-pose_640x640_npu1.axmodel +3 -0
  17. AX620E/yolov8n-pose_640x640_npu2.axmodel +3 -0
  18. AX620E/yolov8s-pose_640x640_npu1.axmodel +3 -0
  19. AX620E/yolov8s-pose_640x640_npu2.axmodel +3 -0
  20. AX620E/yolov8x-pose_640x640_npu1.axmodel +3 -0
  21. AX620E/yolov8x-pose_640x640_npu2.axmodel +3 -0
  22. AX637/yolov8l-pose_640x640_npu1.axmodel +3 -0
  23. AX637/yolov8m-pose_640x640_npu1.axmodel +3 -0
  24. AX637/yolov8n-pose_640x640_npu1.axmodel +3 -0
  25. AX637/yolov8s-pose_640x640_npu1.axmodel +3 -0
  26. AX637/yolov8x-pose_640x640_npu1.axmodel +3 -0
  27. AX650/yolov8l-pose_640x640_npu1.axmodel +3 -0
  28. AX650/yolov8l-pose_640x640_npu3.axmodel +3 -0
  29. AX650/yolov8m-pose_640x640_npu1.axmodel +3 -0
  30. AX650/yolov8m-pose_640x640_npu3.axmodel +3 -0
  31. AX650/yolov8n-pose_640x640_npu1.axmodel +3 -0
  32. AX650/yolov8n-pose_640x640_npu3.axmodel +3 -0
  33. AX650/yolov8s-pose_640x640_npu1.axmodel +3 -0
  34. AX650/yolov8s-pose_640x640_npu3.axmodel +3 -0
  35. AX650/yolov8x-pose_640x640_npu1.axmodel +3 -0
  36. AX650/yolov8x-pose_640x640_npu3.axmodel +3 -0
  37. ax_infer.py +304 -0
  38. bus.jpg +3 -0
  39. coco_1000.tar +3 -0
  40. config.json +32 -0
  41. export_onnx.py +98 -0
  42. onnx_infer.py +356 -0
  43. result_yolov8_pose.jpg +3 -0
  44. yolov8l-pose_640x640.onnx +3 -0
  45. yolov8m-pose_640x640.onnx +3 -0
  46. yolov8n-pose_640x640.onnx +3 -0
  47. yolov8s-pose_640x640.onnx +3 -0
  48. yolov8x-pose_640x640.onnx +3 -0
.gitattributes CHANGED
@@ -38,3 +38,5 @@ ax_yolov8_pose filter=lfs diff=lfs merge=lfs -text
38
  football.jpg filter=lfs diff=lfs merge=lfs -text
39
  yolov8_pose_out.jpg filter=lfs diff=lfs merge=lfs -text
40
  ax_aarch64/ax_yolov8_pose filter=lfs diff=lfs merge=lfs -text
 
 
 
38
  football.jpg filter=lfs diff=lfs merge=lfs -text
39
  yolov8_pose_out.jpg filter=lfs diff=lfs merge=lfs -text
40
  ax_aarch64/ax_yolov8_pose filter=lfs diff=lfs merge=lfs -text
41
+ bus.jpg filter=lfs diff=lfs merge=lfs -text
42
+ result_yolov8_pose.jpg filter=lfs diff=lfs merge=lfs -text
AX615/yolov8l-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2dad83d34bac9974ac6170ee2d0cb6b1081892134f09e868b3cfe4b9225d9d5
3
+ size 51019915
AX615/yolov8l-pose_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e975a669baf70ac52003b5d6d8ecad444a7fcf3f12b565511870e0ec9a879b13
3
+ size 45754431
AX615/yolov8m-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ea0f94270866f906fec43be51be98ec0c3c292d177e0c145c29e824471cecd1
3
+ size 29491937
AX615/yolov8m-pose_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58411bc72b167477869a02f3cd834ecd6a860f5f3a95a51d7d25a47ab1128e6b
3
+ size 27389045
AX615/yolov8n-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9db4874199a4c9f6e6b547d5f00006922fed3c7d972aeea68e7c0d0e33068174
3
+ size 3849505
AX615/yolov8n-pose_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8369442dd40ce79de2f3bb99e43d1e6e3edd84d2bbfc1031bc63c7feebae2c22
3
+ size 3586585
AX615/yolov8s-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c322a8b1e72a2f66d95eb45243f253e8bfe877af11c9a0a70a3254fe42208c9c
3
+ size 13088257
AX615/yolov8s-pose_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a6fb39dfcb793bb13139a54ce7fefb32ca22eab9d0f10f425e17f8066621e46d
3
+ size 12122457
AX615/yolov8x-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f247acfb2471aa96326f2691ff47f2f09a6f2a47676951315650ad8336c7eac
3
+ size 81376619
AX615/yolov8x-pose_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f46da3c070f2a66d42700c75d53e82f08733745d70664debf27d4809b9d4de9c
3
+ size 71624575
AX620E/yolov8l-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c7d38c6c156f6cd953168d589690d0b4f1be4f107808478366d2d6e07fbd263
3
+ size 51226853
AX620E/yolov8l-pose_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e5dd70ee3dcf2440a5aae369645693554f3ecef7032932dc3914e524c59cb09
3
+ size 45763597
AX620E/yolov8m-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1215bbccd1f54135f0527ba1f3deee5af6e65755bd9f8b8e07d4c407179ed4ae
3
+ size 30692125
AX620E/yolov8m-pose_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06894c8d1b2190d6f5602ed0fbd011a594dfef842d8d028adda30257871101d4
3
+ size 27499901
AX620E/yolov8n-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea91b465cae540f53b76e7fddc81335d8f3ce6c784992640444c8c1fe1208147
3
+ size 4014305
AX620E/yolov8n-pose_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe0d7628cc220c96fd9aaba2eb1946fa80e0d28fd3e38cdbd0dc132f025b0781
3
+ size 3612093
AX620E/yolov8s-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9acdad70261155b42f1a7b0df802309e8a3d67f50acf44420bca33074f77924f
3
+ size 13317169
AX620E/yolov8s-pose_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4571a535934c933fd7bd4f1f38cc27962fcff6626ca957f260dcd0157004f250
3
+ size 12157821
AX620E/yolov8x-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2bd6d785d4c109aa2a5efa2a29e00e77420c58e764ff9bb086042117504610a9
3
+ size 82118973
AX620E/yolov8x-pose_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:519237baf385f82d75aabe4916387431078303acbf396d8b294168fccfdfe9e9
3
+ size 71981085
AX637/yolov8l-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:814344afeeed5828c8a7669fa3c76aff8051ae0178fa12c9b9993363403068c7
3
+ size 45236543
AX637/yolov8m-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6f4cd0e5b9d0ef7ae6541ce46b2a4c90fa71acfb205e9171531a34ff1319d26c
3
+ size 27436669
AX637/yolov8n-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eeb4e68f6f0568452c9c8bde7ba32435f62d98f0c192bf229a4f168d23849d4c
3
+ size 3761897
AX637/yolov8s-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7db8655e2bd7c6bc7dc9b5b71f1d886bbc8e1fc4a62b15503d97af91f9ee27b3
3
+ size 12350441
AX637/yolov8x-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa8d89b93a0a5014ffc1cb9941c737400d368ffc83af4bcf1204e1a7ea82ca5c
3
+ size 71784855
AX650/yolov8l-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dad2ae4f1fe24345c0e5306c8d97efd1a4fda5093270e769ed4754e2be7d0b3e
3
+ size 45934971
AX650/yolov8l-pose_640x640_npu3.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a78396d07489774fc91aec81404af7075a46cc47132d615e87257347318802b8
3
+ size 46400859
AX650/yolov8m-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76b3396e674f31f5bc13a574b245d23096e6be533f352ebf1d2aeb61d8a9e114
3
+ size 27511381
AX650/yolov8m-pose_640x640_npu3.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:81d0a74fa362b06c7f4ed031053edfb926af6a5f82fcbaf80253f6281bd529b3
3
+ size 27890357
AX650/yolov8n-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25d3e4ad07d5ce05cd2c7de2ad1b8d80eabd021d45afc4a7f353d91f0324e40d
3
+ size 3660657
AX650/yolov8n-pose_640x640_npu3.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6deff323b0091b1aaa684694876c36a482437408f0916c8a9259e44beae6948f
3
+ size 3943725
AX650/yolov8s-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:11b2c1824d2ce60afca96607d6a2444378bb8607c88ac4ebc134ff0c44449363
3
+ size 12255761
AX650/yolov8s-pose_640x640_npu3.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7594b542c89c71081d3535e82118904290ef38f63defe607430986ffac66e9aa
3
+ size 12547117
AX650/yolov8x-pose_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a99c95ef13cdd87cf2caccc7928b44d8d5b8ce718b58fe8614ed4eada2169175
3
+ size 72003197
AX650/yolov8x-pose_640x640_npu3.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d729ac50f6e88dcfd914aa40ea0d544b3e169d5db8fb5a7fa3067aceb5750fcd
3
+ size 72549821
ax_infer.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Usage: python ax_infer.py --model-path yolov8n-pose_640x640.axmodel --test-img bus.jpg --img-save-path result_yolov8_pose.jpg --score-thres 0.25 --nms-thres 0.7 --providers AxEngineExecutionProvider
3
+ import os
4
+ import cv2
5
+ import numpy as np
6
+ from time import time
7
+ import argparse
8
+ import logging
9
+ import axengine as ort
10
+
11
+ logging.basicConfig(
12
+ level=logging.DEBUG,
13
+ format='[%(name)s] [%(asctime)s.%(msecs)03d] [%(levelname)s] %(message)s',
14
+ datefmt='%H:%M:%S'
15
+ )
16
+ logger = logging.getLogger("YOLOv8-Pose")
17
+
18
+
19
+ def infer_hw_layout(shape):
20
+ """Infer input height, width and layout from model input shape."""
21
+ shape = list(shape)
22
+ if len(shape) == 4 and shape[-1] == 3:
23
+ h = int(shape[1] or 640)
24
+ w = int(shape[2] or 640)
25
+ return h, w, "NHWC"
26
+ if len(shape) == 4 and shape[1] == 3:
27
+ h = int(shape[2] or 640)
28
+ w = int(shape[3] or 640)
29
+ return h, w, "NCHW"
30
+ return 640, 640, "NCHW"
31
+
32
+
33
+ def softmax(x, axis=-1):
34
+ """Compute softmax along axis."""
35
+ e_x = np.exp(x - np.max(x, axis=axis, keepdims=True))
36
+ return e_x / np.sum(e_x, axis=axis, keepdims=True)
37
+
38
+
39
+ def dfl_decode(box_pred, reg_max=16):
40
+ """Decode DFL (Distribution Focal Loss) box predictions to ltrb distances."""
41
+ N = box_pred.shape[0]
42
+ box_pred = box_pred.reshape(N, 4, reg_max)
43
+ box_pred = softmax(box_pred, axis=-1)
44
+ proj = np.arange(reg_max, dtype=np.float32)
45
+ return np.sum(box_pred * proj, axis=-1) # (N, 4)
46
+
47
+
48
+ def decode_keypoints(kpt_preds, anchors, stride, kpt_shape=(17, 3)):
49
+ """
50
+ Decode keypoints from predictions (standard YOLOv8-Pose formula, export mode):
51
+ a = (y[:, :, :2] * 2.0 + (self.anchors - 0.5)) * self.strides
52
+ if ndim == 3:
53
+ a = torch.cat((a, y[:, :, 2:3].sigmoid()), 2)
54
+
55
+ Here anchors are grid indices + 0.5, so (anchors - 0.5) == grid indices.
56
+
57
+ Args:
58
+ kpt_preds: (N, nk) raw keypoint predictions, nk = 17 * 3 = 51
59
+ anchors: (N, 2) - anchor points (x, y) with offset 0.5
60
+ stride: scalar - stride value
61
+ kpt_shape: (num_keypoints, num_dims) = (17, 3)
62
+
63
+ Returns:
64
+ keypoints: (N, 17, 3) decoded keypoints [x, y, conf]
65
+ """
66
+ N = kpt_preds.shape[0]
67
+ nk = kpt_shape[0] * kpt_shape[1] # 51
68
+
69
+ kpt_preds = kpt_preds[:, :nk]
70
+ kpts = kpt_preds.reshape(N, kpt_shape[0], kpt_shape[1])
71
+
72
+ anchor_x = anchors[:, 0:1] # (N, 1)
73
+ anchor_y = anchors[:, 1:2] # (N, 1)
74
+
75
+ kpts_decoded = np.zeros_like(kpts)
76
+ kpts_decoded[:, :, 0] = (kpts[:, :, 0] * 2.0 + (anchor_x - 0.5)) * stride
77
+ kpts_decoded[:, :, 1] = (kpts[:, :, 1] * 2.0 + (anchor_y - 0.5)) * stride
78
+
79
+ if kpt_shape[1] == 3:
80
+ kpts_decoded[:, :, 2] = 1 / (1 + np.exp(-kpts[:, :, 2]))
81
+
82
+ return kpts_decoded
83
+
84
+
85
+ def scale_keypoints_lefttop(keypoints, scale, orig_shape):
86
+ """Scale keypoints from model output to original image coordinates."""
87
+ keypoints = keypoints.copy()
88
+ keypoints[..., 0] /= scale
89
+ keypoints[..., 1] /= scale
90
+ keypoints[..., 0] = np.clip(keypoints[..., 0], 0, orig_shape[1])
91
+ keypoints[..., 1] = np.clip(keypoints[..., 1], 0, orig_shape[0])
92
+ return keypoints
93
+
94
+
95
+ def main():
96
+ ap = argparse.ArgumentParser(description='YOLOv8-Pose Inference (AXERARuntime)')
97
+ ap.add_argument('--model-path', type=str, default='yolov8n-pose_640x640.axmodel')
98
+ ap.add_argument('--test-img', type=str, default='bus.jpg')
99
+ ap.add_argument('--img-save-path', type=str, default='result_yolov8_pose.jpg')
100
+ ap.add_argument('--score-thres', type=float, default=0.25)
101
+ ap.add_argument('--nms-thres', type=float, default=0.7)
102
+ ap.add_argument('--providers', type=str, default='AxEngineExecutionProvider')
103
+ opt = ap.parse_args()
104
+
105
+ if not os.path.exists(opt.model_path):
106
+ logger.error(f"Model not found: {opt.model_path}")
107
+ return
108
+
109
+ t0 = time()
110
+ providers = [p.strip() for p in opt.providers.split(",") if p.strip()] or None
111
+ sess = ort.InferenceSession(opt.model_path, providers=providers)
112
+ logger.debug(f"\033[1;31mLoad model time = {(time() - t0) * 1000:.2f} ms\033[0m")
113
+
114
+ inp = sess.get_inputs()[0]
115
+ input_name = inp.name
116
+ m_h, m_w, layout = infer_hw_layout(inp.shape)
117
+
118
+ img = cv2.imread(opt.test_img)
119
+ if img is None:
120
+ logger.error(f"Image not found or unreadable: {opt.test_img}")
121
+ return
122
+
123
+ # Preprocess
124
+ t0 = time()
125
+ orig_h, orig_w = img.shape[:2]
126
+ scale = min(m_h / orig_h, m_w / orig_w)
127
+ new_w, new_h = int(orig_w * scale), int(orig_h * scale)
128
+
129
+ resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
130
+ padded = cv2.copyMakeBorder(
131
+ resized, 0, m_h - new_h, 0, m_w - new_w,
132
+ cv2.BORDER_CONSTANT, value=(127, 127, 127)
133
+ )
134
+ rgb = cv2.cvtColor(padded, cv2.COLOR_BGR2RGB)
135
+ input_tensor = rgb[None, ...].astype(np.uint8) if layout == "NHWC" else np.transpose(rgb, (2, 0, 1))[None, ...].astype(np.uint8)
136
+ logger.debug(f"\033[1;31mPre-process time = {(time() - t0) * 1000:.2f} ms\033[0m")
137
+
138
+ # Inference
139
+ t0 = time()
140
+ ort_outputs = sess.run(None, {input_name: input_tensor})
141
+ out_metas = sess.get_outputs()
142
+ logger.debug(f"\033[1;31mForward time = {(time() - t0) * 1000:.2f} ms\033[0m")
143
+
144
+ # Post-process
145
+ t0 = time()
146
+ strides = (8, 16, 32)
147
+ conf_raw = -np.log(1 / opt.score_thres - 1)
148
+ detections = []
149
+ all_keypoints = []
150
+ kpt_shape = (17, 3)
151
+
152
+ output_items = []
153
+ for meta, data in zip(out_metas, ort_outputs):
154
+ shape = list(meta.shape)
155
+ if any(s is None or isinstance(s, str) for s in shape):
156
+ shape = list(data.shape)
157
+ output_items.append((data, shape))
158
+
159
+ # Process each scale (9 outputs: 3 scales * 3 outputs per scale)
160
+ for scale_idx, stride in enumerate(strides):
161
+ box_idx = scale_idx * 3
162
+ cls_idx = scale_idx * 3 + 1
163
+ kpt_idx = scale_idx * 3 + 2
164
+
165
+ if box_idx >= len(output_items) or cls_idx >= len(output_items) or kpt_idx >= len(output_items):
166
+ continue
167
+
168
+ box_data, box_shape = output_items[box_idx]
169
+ cls_data, cls_shape = output_items[cls_idx]
170
+ kpt_data, kpt_shape_raw = output_items[kpt_idx]
171
+
172
+ H, W = box_shape[1], box_shape[2]
173
+ box_channels = box_shape[-1]
174
+
175
+ # Determine if DFL is used (YOLOv8: 4*reg_max = 64)
176
+ reg_max = None
177
+ if box_channels > 4 and box_channels % 4 == 0:
178
+ reg_max = box_channels // 4
179
+
180
+ box_data = box_data[0].reshape(-1, box_channels)
181
+ cls_data = cls_data[0].reshape(-1, cls_shape[-1])
182
+ kpt_data = kpt_data[0].reshape(-1, kpt_shape_raw[-1])
183
+
184
+ # Get max class scores (for pose, usually nc=1)
185
+ if cls_data.shape[-1] == 1:
186
+ cls_scores = cls_data[:, 0]
187
+ cls_ids = np.zeros(len(cls_scores), dtype=np.int32)
188
+ else:
189
+ cls_scores = np.max(cls_data, axis=1)
190
+ cls_ids = np.argmax(cls_data, axis=1)
191
+
192
+ valid_mask = cls_scores >= conf_raw
193
+ if not np.any(valid_mask):
194
+ continue
195
+
196
+ v_box = box_data[valid_mask]
197
+ v_score = 1 / (1 + np.exp(-cls_scores[valid_mask]))
198
+ v_id = cls_ids[valid_mask]
199
+ v_kpt = kpt_data[valid_mask]
200
+
201
+ gy, gx = np.indices((H, W))
202
+ anchors = np.stack((gx.ravel(), gy.ravel()), axis=-1).astype(np.float32) + 0.5
203
+ anchors = anchors[valid_mask]
204
+
205
+ # Decode boxes (DFL -> ltrb -> xyxy)
206
+ if reg_max is not None:
207
+ v_box = dfl_decode(v_box, reg_max)
208
+ lt = v_box[:, :2]
209
+ rb = v_box[:, 2:]
210
+ x1y1 = anchors - lt
211
+ x2y2 = anchors + rb
212
+ boxes = np.hstack([x1y1, x2y2]) * stride
213
+
214
+ kpts = decode_keypoints(v_kpt, anchors, stride, kpt_shape)
215
+
216
+ for i in range(len(boxes)):
217
+ detections.append([*boxes[i], v_score[i], v_id[i]])
218
+ all_keypoints.append(kpts[i])
219
+
220
+ logger.debug(f"\033[1;31mPost-process time = {(time() - t0) * 1000:.2f} ms\033[0m")
221
+
222
+ if len(detections) == 0:
223
+ logger.info("No detections found.")
224
+ cv2.imwrite(opt.img_save_path, img)
225
+ return
226
+
227
+ detections = np.array(detections)
228
+ all_keypoints = np.array(all_keypoints)
229
+
230
+ # NMS
231
+ xywh = detections[:, :4].copy()
232
+ xywh[:, 2] = xywh[:, 2] - xywh[:, 0] # w
233
+ xywh[:, 3] = xywh[:, 3] - xywh[:, 1] # h
234
+
235
+ indices = cv2.dnn.NMSBoxes(xywh.tolist(), detections[:, 4].tolist(), opt.score_thres, opt.nms_thres)
236
+
237
+ if len(indices) == 0:
238
+ logger.info("No detections after NMS.")
239
+ cv2.imwrite(opt.img_save_path, img)
240
+ return
241
+
242
+ indices = indices.flatten()
243
+ final_dets = detections[indices]
244
+ final_kpts = all_keypoints[indices]
245
+
246
+ # Scale to original image coordinates
247
+ final_dets[:, :4] = final_dets[:, :4] / scale
248
+ final_dets[:, [0, 2]] = np.clip(final_dets[:, [0, 2]], 0, orig_w)
249
+ final_dets[:, [1, 3]] = np.clip(final_dets[:, [1, 3]], 0, orig_h)
250
+ final_kpts = scale_keypoints_lefttop(final_kpts, scale, (orig_h, orig_w))
251
+
252
+ kpt_color = [
253
+ (0, 255, 0), (0, 255, 0), (0, 255, 0), (0, 255, 0), (0, 255, 0), # face
254
+ (255, 128, 0), (255, 128, 0), (255, 128, 0), (255, 128, 0), (255, 128, 0), (255, 128, 0), # arms
255
+ (51, 153, 255), (51, 153, 255), (51, 153, 255), (51, 153, 255), (51, 153, 255), (51, 153, 255) # legs
256
+ ]
257
+ limb_color = [
258
+ (51, 153, 255), (0, 255, 0), (255, 128, 0), (255, 153, 255), (102, 178, 255),
259
+ (255, 51, 51), (51, 255, 153), (255, 178, 102), (230, 230, 0), (255, 153, 204),
260
+ (255, 102, 255), (153, 255, 153), (255, 255, 128), (0, 255, 255), (255, 255, 0),
261
+ (255, 204, 153), (153, 204, 255), (255, 153, 153), (204, 153, 255)
262
+ ]
263
+ skeleton = [
264
+ [16, 14], [14, 12], [17, 15], [15, 13], [12, 13],
265
+ [6, 12], [7, 13], [6, 7],
266
+ [6, 8], [7, 9], [8, 10], [9, 11],
267
+ [2, 3], [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7]
268
+ ]
269
+
270
+ logger.info(f"\033[1;32mDraw Results ({len(final_dets)} persons): \033[0m")
271
+
272
+ for i, det in enumerate(final_dets):
273
+ box = det[:4].astype(int)
274
+ conf = det[4]
275
+
276
+ logger.info(f"({box[0]}, {box[1]}, {box[2]}, {box[3]}) -> person: {conf:.2f}")
277
+
278
+ cv2.rectangle(img, (box[0], box[1]), (box[2], box[3]), (255, 42, 4), 2)
279
+ cv2.putText(img, f"person {conf:.2f}", (box[0], box[1] - 10),
280
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 42, 4), 2)
281
+
282
+ kpt = final_kpts[i]
283
+
284
+ for sk_idx, sk in enumerate(skeleton):
285
+ idx1, idx2 = sk[0] - 1, sk[1] - 1
286
+ if idx1 < 0 or idx1 >= 17 or idx2 < 0 or idx2 >= 17:
287
+ continue
288
+ if kpt[idx1, 2] > 0.5 and kpt[idx2, 2] > 0.5:
289
+ pt1 = (int(kpt[idx1, 0]), int(kpt[idx1, 1]))
290
+ pt2 = (int(kpt[idx2, 0]), int(kpt[idx2, 1]))
291
+ color = limb_color[sk_idx % len(limb_color)]
292
+ cv2.line(img, pt1, pt2, color, 2)
293
+
294
+ for j, (x, y, conf_kpt) in enumerate(kpt):
295
+ if conf_kpt > 0.5:
296
+ color = kpt_color[j] if j < len(kpt_color) else (0, 255, 0)
297
+ cv2.circle(img, (int(x), int(y)), 5, color, -1)
298
+
299
+ cv2.imwrite(opt.img_save_path, img)
300
+ logger.info(f"Saved to {opt.img_save_path}")
301
+
302
+
303
+ if __name__ == "__main__":
304
+ main()
bus.jpg ADDED

Git LFS Details

  • SHA256: 33b198a1d2839bb9ac4c65d61f9e852196793cae9a0781360859425f6022b69c
  • Pointer size: 131 Bytes
  • Size of remote file: 487 kB
coco_1000.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3e18a198658270e19ced079de7a404e3478e69c2ef94fb47c87ddf056e6a541
3
+ size 163112960
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "ONNX",
3
+ "npu_mode": "NPU3",
4
+ "quant": {
5
+ "input_configs": [
6
+ {
7
+ "tensor_name": "images",
8
+ "calibration_dataset": "./coco_1000.tar",
9
+ "calibration_size": 32,
10
+ "calibration_mean": [0, 0, 0],
11
+ "calibration_std": [255.0, 255.0, 255.0]
12
+ }
13
+ ],
14
+ "calibration_method": "MinMax",
15
+ "precision_analysis": true,
16
+ "precision_analysis_method":"EndToEnd"
17
+ },
18
+ "input_processors": [
19
+ {
20
+ "tensor_name": "images",
21
+ "tensor_format": "BGR",
22
+ "src_format": "BGR",
23
+ "src_dtype": "U8",
24
+ "src_layout": "NHWC"
25
+ }
26
+ ],
27
+ "output_processors": [
28
+ ],
29
+ "compiler": {
30
+ "check": 0
31
+ }
32
+ }
export_onnx.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import torch
3
+ from ultralytics import YOLO
4
+ from ultralytics.nn.modules.head import Pose
5
+ import os
6
+ import shutil
7
+
8
+
9
+ def npu_pose_forward(self, x):
10
+ """
11
+ YOLOv8 Pose Head Modified for NPU.
12
+
13
+ YOLOv8 Pose structure (NOT end2end):
14
+ - cv2: box regression layers (DFL, out channels = 4 * reg_max = 64)
15
+ - cv3: classification layers (out channels = nc, nc=1 for pose)
16
+ - cv4: keypoint output layers (out channels = nk = 17 * 3 = 51)
17
+
18
+ Output:
19
+ List of Tensors (9 items for 3 scales), Layout: NHWC.
20
+ For each scale:
21
+ - Box_Raw (B, H, W, 4*reg_max), <-- raw DFL box logits (decode in post-process)
22
+ - Cls_Raw (B, H, W, nc), <-- class scores (raw logits), nc=1 for pose
23
+ - Kpt_Raw (B, H, W, nk), <-- raw keypoints (nk = 17*3 = 51)
24
+ """
25
+ if not isinstance(x, (list, tuple)):
26
+ x = [x]
27
+
28
+ res = []
29
+
30
+ box_layers = self.cv2
31
+ cls_layers = self.cv3
32
+ kpt_layers = self.cv4
33
+
34
+ for i in range(self.nl):
35
+ # 1. Box branch (raw DFL logits) - NHWC
36
+ bboxes = box_layers[i](x[i]).permute(0, 2, 3, 1)
37
+
38
+ # 2. Cls branch (raw logits) - NHWC
39
+ scores = cls_layers[i](x[i]).permute(0, 2, 3, 1)
40
+
41
+ # 3. Keypoints branch (raw) - NHWC
42
+ kpts = kpt_layers[i](x[i]).permute(0, 2, 3, 1)
43
+
44
+ res.append(bboxes)
45
+ res.append(scores)
46
+ res.append(kpts)
47
+
48
+ return res
49
+
50
+
51
+ def batch_export_yolov8_pose():
52
+ variants = ['n', 's', 'm', 'l', 'x']
53
+ imgsz = 640
54
+
55
+ # Execute Monkey Patch
56
+ Pose.forward = npu_pose_forward
57
+ print("Monkey patch applied for Pose: Output Layout forced to NHWC (Box, Cls, Kpt for each scale).")
58
+
59
+ for v in variants:
60
+ model_name = f"yolov8{v}-pose"
61
+ pt_path = f"{model_name}.pt"
62
+ onnx_final_name = f"{model_name}_640x640.onnx"
63
+ print(f"\n--- Processing {model_name} ---")
64
+ try:
65
+ # Load model
66
+ model = YOLO(pt_path)
67
+
68
+ # Reapply monkey patch
69
+ Pose.forward = npu_pose_forward
70
+
71
+ # Ensure the model's head also uses the new forward
72
+ if hasattr(model.model, 'model') and len(model.model.model) > 0:
73
+ head = model.model.model[-1]
74
+ if isinstance(head, Pose):
75
+ head.forward = lambda x: npu_pose_forward(head, x)
76
+
77
+ # Execute export
78
+ exported_path = model.export(
79
+ format="onnx",
80
+ imgsz=imgsz,
81
+ dynamic=False,
82
+ opset=11,
83
+ simplify=True,
84
+ nms=False
85
+ )
86
+
87
+ # Move and rename
88
+ if exported_path:
89
+ shutil.move(exported_path, onnx_final_name)
90
+ print(f"Success: {onnx_final_name}")
91
+ except Exception as e:
92
+ print(f"Failed to export {model_name}: {e}")
93
+ import traceback
94
+ traceback.print_exc()
95
+
96
+
97
+ if __name__ == "__main__":
98
+ batch_export_yolov8_pose()
onnx_infer.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import onnxruntime as ort
3
+ import cv2
4
+ import numpy as np
5
+ import argparse
6
+ import os
7
+
8
+
9
+ def preprocess_image(image, input_size=(640, 640)):
10
+ """
11
+ Preprocess image with left-top aligned letterbox (same as official YOLO).
12
+
13
+ Args:
14
+ image: BGR image (H, W, C)
15
+ input_size: (height, width) target size
16
+
17
+ Returns:
18
+ input_tensor: (1, 3, H, W) float32 tensor normalized to [0, 1]
19
+ scale: scale ratio used for resizing
20
+ original_shape: (orig_h, orig_w) original image shape
21
+ """
22
+ orig_h, orig_w = image.shape[:2]
23
+ m_h, m_w = input_size
24
+
25
+ # Calculate scale (keep aspect ratio)
26
+ scale = min(m_h / orig_h, m_w / orig_w)
27
+
28
+ # Resize
29
+ new_w, new_h = int(orig_w * scale), int(orig_h * scale)
30
+ img_resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
31
+
32
+ # Pad to target size (left-top aligned)
33
+ input_bgr = cv2.copyMakeBorder(
34
+ img_resized, 0, m_h - new_h, 0, m_w - new_w,
35
+ cv2.BORDER_CONSTANT, value=(114, 114, 114)
36
+ )
37
+
38
+ # BGR -> RGB, normalize to [0, 1]
39
+ input_rgb = cv2.cvtColor(input_bgr, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
40
+
41
+ # HWC -> CHW, add batch dimension
42
+ input_tensor = np.transpose(input_rgb, (2, 0, 1))[None, ...]
43
+
44
+ return input_tensor, scale, (orig_h, orig_w)
45
+
46
+
47
+ def softmax(x, axis=-1):
48
+ """Compute softmax along axis."""
49
+ e_x = np.exp(x - np.max(x, axis=axis, keepdims=True))
50
+ return e_x / np.sum(e_x, axis=axis, keepdims=True)
51
+
52
+
53
+ def dfl_decode(box_pred, reg_max=16):
54
+ """
55
+ Decode DFL (Distribution Focal Loss) box predictions.
56
+
57
+ Args:
58
+ box_pred: (N, 4 * reg_max) raw box predictions
59
+ reg_max: number of DFL bins
60
+
61
+ Returns:
62
+ (N, 4) decoded ltrb distances
63
+ """
64
+ N = box_pred.shape[0]
65
+ box_pred = box_pred.reshape(N, 4, reg_max)
66
+ box_pred = softmax(box_pred, axis=-1)
67
+ proj = np.arange(reg_max, dtype=np.float32)
68
+ return np.sum(box_pred * proj, axis=-1) # (N, 4)
69
+
70
+
71
+ def decode_bboxes(bbox_preds, anchors, stride, reg_max=None):
72
+ """
73
+ Decode bounding boxes from predictions.
74
+
75
+ Args:
76
+ bbox_preds: (N, 4) or (N, 4*reg_max) - distance predictions in ltrb format
77
+ anchors: (N, 2) - anchor points (x, y) with offset 0.5
78
+ stride: scalar - stride value
79
+ reg_max: if not None, apply DFL decoding first
80
+
81
+ Returns:
82
+ boxes: (N, 4) in xyxy format
83
+ """
84
+ if reg_max is not None and bbox_preds.shape[-1] == 4 * reg_max:
85
+ bbox_preds = dfl_decode(bbox_preds, reg_max)
86
+
87
+ # dist2bbox: ltrb to xyxy
88
+ lt = bbox_preds[:, :2] # left, top
89
+ rb = bbox_preds[:, 2:] # right, bottom
90
+
91
+ x1y1 = anchors - lt
92
+ x2y2 = anchors + rb
93
+
94
+ boxes = np.hstack([x1y1, x2y2]) * stride
95
+ return boxes
96
+
97
+
98
+ def decode_keypoints(kpt_preds, anchors, stride, kpt_shape=(17, 3)):
99
+ """
100
+ Decode keypoints from predictions.
101
+
102
+ IMPORTANT: This is the standard YOLOv8-Pose formula (export mode):
103
+ a = (y[:, :, :2] * 2.0 + (self.anchors - 0.5)) * self.strides
104
+ if ndim == 3:
105
+ a = torch.cat((a, y[:, :, 2:3].sigmoid()), 2)
106
+
107
+ Note: YOLOv8 multiplies keypoint offsets by 2.0 and uses (anchors - 0.5).
108
+ Here anchors are grid indices + 0.5, so (anchors - 0.5) == grid indices.
109
+
110
+ Args:
111
+ kpt_preds: (N, nk) raw keypoint predictions, nk = 17 * 3 = 51
112
+ anchors: (N, 2) - anchor points (x, y) with offset 0.5
113
+ stride: scalar - stride value
114
+ kpt_shape: (num_keypoints, num_dims) = (17, 3)
115
+
116
+ Returns:
117
+ keypoints: (N, 17, 3) decoded keypoints [x, y, conf]
118
+ """
119
+ N = kpt_preds.shape[0]
120
+ nk = kpt_shape[0] * kpt_shape[1] # 51
121
+
122
+ kpt_preds = kpt_preds[:, :nk]
123
+ kpts = kpt_preds.reshape(N, kpt_shape[0], kpt_shape[1])
124
+
125
+ anchor_x = anchors[:, 0:1] # (N, 1)
126
+ anchor_y = anchors[:, 1:2] # (N, 1)
127
+
128
+ kpts_decoded = np.zeros_like(kpts)
129
+ kpts_decoded[:, :, 0] = (kpts[:, :, 0] * 2.0 + (anchor_x - 0.5)) * stride
130
+ kpts_decoded[:, :, 1] = (kpts[:, :, 1] * 2.0 + (anchor_y - 0.5)) * stride
131
+
132
+ # Apply sigmoid to confidence
133
+ if kpt_shape[1] == 3:
134
+ kpts_decoded[:, :, 2] = 1 / (1 + np.exp(-kpts[:, :, 2]))
135
+
136
+ return kpts_decoded
137
+
138
+
139
+ def scale_boxes_lefttop(boxes, scale, orig_shape):
140
+ """Scale boxes from model output to original image coordinates."""
141
+ boxes = boxes.copy()
142
+ boxes[..., :4] /= scale
143
+ boxes[..., [0, 2]] = np.clip(boxes[..., [0, 2]], 0, orig_shape[1])
144
+ boxes[..., [1, 3]] = np.clip(boxes[..., [1, 3]], 0, orig_shape[0])
145
+ return boxes
146
+
147
+
148
+ def scale_keypoints_lefttop(keypoints, scale, orig_shape):
149
+ """Scale keypoints from model output to original image coordinates."""
150
+ keypoints = keypoints.copy()
151
+ keypoints[..., 0] /= scale
152
+ keypoints[..., 1] /= scale
153
+ keypoints[..., 0] = np.clip(keypoints[..., 0], 0, orig_shape[1])
154
+ keypoints[..., 1] = np.clip(keypoints[..., 1], 0, orig_shape[0])
155
+ return keypoints
156
+
157
+
158
+ def main():
159
+ parser = argparse.ArgumentParser(description='YOLOv8-Pose ONNX Inference')
160
+ parser.add_argument('-m', '--model', type=str, default='yolov8n-pose_640x640.onnx',
161
+ dest='model_path', help='Path to YOLOv8-Pose *.onnx Model.')
162
+ parser.add_argument('-i', '--img', type=str, default='bus.jpg',
163
+ dest='test_img', help='Path to Test Image.')
164
+ parser.add_argument('-o', '--output', type=str, default='result_yolov8_pose.jpg',
165
+ dest='img_save_path', help='Path to Save Result Image.')
166
+ parser.add_argument('--score-thres', type=float, default=0.25,
167
+ help='Confidence threshold.')
168
+ parser.add_argument('--nms-thres', type=float, default=0.7,
169
+ help='IoU threshold for NMS.')
170
+ opt = parser.parse_args()
171
+
172
+ if not os.path.exists(opt.model_path):
173
+ print(f"Error: Model not found: {opt.model_path}")
174
+ return
175
+
176
+ if not os.path.exists(opt.test_img):
177
+ print(f"Error: Image not found: {opt.test_img}")
178
+ return
179
+
180
+ # Load ONNX model
181
+ providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
182
+ try:
183
+ session = ort.InferenceSession(opt.model_path, providers=providers)
184
+ except:
185
+ session = ort.InferenceSession(opt.model_path, providers=['CPUExecutionProvider'])
186
+
187
+ input_name = session.get_inputs()[0].name
188
+ output_names = [o.name for o in session.get_outputs()]
189
+ input_shape = session.get_inputs()[0].shape
190
+ imgsz = (input_shape[2], input_shape[3])
191
+
192
+ # Get metadata
193
+ metadata = session.get_modelmeta().custom_metadata_map
194
+ kpt_shape = eval(metadata.get('kpt_shape', '[17, 3]')) if metadata else [17, 3]
195
+
196
+ # Load image
197
+ img0 = cv2.imread(opt.test_img)
198
+ if img0 is None:
199
+ print(f"Error: Cannot read image: {opt.test_img}")
200
+ return
201
+
202
+ # Preprocess
203
+ img, scale, orig_shape = preprocess_image(img0.copy(), imgsz)
204
+
205
+ # Inference
206
+ outputs = session.run(output_names, {input_name: img})
207
+
208
+ # Post-process
209
+ strides = [8, 16, 32]
210
+ conf_raw = -np.log(1 / opt.score_thres - 1)
211
+ detections = []
212
+ all_keypoints = []
213
+
214
+ # Process each scale
215
+ for scale_idx, stride in enumerate(strides):
216
+ grid_size = imgsz[0] // stride
217
+
218
+ box_idx = scale_idx * 3
219
+ cls_idx = scale_idx * 3 + 1
220
+ kpt_idx = scale_idx * 3 + 2
221
+
222
+ if box_idx >= len(outputs) or cls_idx >= len(outputs) or kpt_idx >= len(outputs):
223
+ continue
224
+
225
+ box_data = outputs[box_idx] # (1, H, W, C) where C = 4 or 4*reg_max
226
+ cls_data = outputs[cls_idx] # (1, H, W, nc)
227
+ kpt_data = outputs[kpt_idx] # (1, H, W, nk)
228
+
229
+ H, W = box_data.shape[1:3]
230
+ box_channels = box_data.shape[-1]
231
+
232
+ # Determine if DFL is used (YOLOv8: 4*reg_max = 64)
233
+ reg_max = None
234
+ if box_channels > 4 and box_channels % 4 == 0:
235
+ reg_max = box_channels // 4
236
+
237
+ # Reshape to (H*W, ...)
238
+ box_data = box_data[0].reshape(-1, box_channels)
239
+ cls_data = cls_data[0].reshape(-1, cls_data.shape[-1])
240
+ kpt_data = kpt_data[0].reshape(-1, kpt_data.shape[-1])
241
+
242
+ # Get max class scores
243
+ if cls_data.shape[-1] == 1:
244
+ cls_scores = cls_data[:, 0]
245
+ cls_ids = np.zeros(len(cls_scores), dtype=np.int32)
246
+ else:
247
+ cls_scores = np.max(cls_data, axis=1)
248
+ cls_ids = np.argmax(cls_data, axis=1)
249
+
250
+ # Filter by confidence (on raw logits)
251
+ valid_mask = cls_scores >= conf_raw
252
+ if not np.any(valid_mask):
253
+ continue
254
+
255
+ v_box = box_data[valid_mask]
256
+ v_score = 1 / (1 + np.exp(-cls_scores[valid_mask]))
257
+ v_id = cls_ids[valid_mask]
258
+ v_kpt = kpt_data[valid_mask]
259
+
260
+ # Generate anchors for this scale (grid indices + 0.5)
261
+ gy, gx = np.indices((H, W))
262
+ anchors = np.stack((gx.ravel(), gy.ravel()), axis=-1).astype(np.float32) + 0.5
263
+ anchors = anchors[valid_mask]
264
+
265
+ # Decode boxes
266
+ boxes = decode_bboxes(v_box, anchors, stride, reg_max)
267
+
268
+ # Decode keypoints
269
+ kpts = decode_keypoints(v_kpt, anchors, stride, tuple(kpt_shape))
270
+
271
+ # Store detections
272
+ for i in range(len(boxes)):
273
+ detections.append([*boxes[i], v_score[i], v_id[i]])
274
+ all_keypoints.append(kpts[i])
275
+
276
+ if len(detections) == 0:
277
+ print("No detections found.")
278
+ cv2.imwrite(opt.img_save_path, img0)
279
+ return
280
+
281
+ detections = np.array(detections)
282
+ all_keypoints = np.array(all_keypoints)
283
+
284
+ # NMS
285
+ xywh = detections[:, :4].copy()
286
+ xywh[:, 2] = xywh[:, 2] - xywh[:, 0] # w
287
+ xywh[:, 3] = xywh[:, 3] - xywh[:, 1] # h
288
+
289
+ indices = cv2.dnn.NMSBoxes(xywh.tolist(), detections[:, 4].tolist(), opt.score_thres, opt.nms_thres)
290
+
291
+ if len(indices) == 0:
292
+ print("No detections after NMS.")
293
+ cv2.imwrite(opt.img_save_path, img0)
294
+ return
295
+
296
+ indices = indices.flatten()
297
+ detections = detections[indices]
298
+ all_keypoints = all_keypoints[indices]
299
+
300
+ # Scale to original image
301
+ detections[:, :4] = scale_boxes_lefttop(detections[:, :4], scale, orig_shape)
302
+ all_keypoints = scale_keypoints_lefttop(all_keypoints, scale, orig_shape)
303
+
304
+ # Keypoint colors: green for face, orange for arms, blue for legs
305
+ kpt_color = [
306
+ (0, 255, 0), (0, 255, 0), (0, 255, 0), (0, 255, 0), (0, 255, 0), # face
307
+ (255, 128, 0), (255, 128, 0), (255, 128, 0), (255, 128, 0), (255, 128, 0), (255, 128, 0), # arms
308
+ (51, 153, 255), (51, 153, 255), (51, 153, 255), (51, 153, 255), (51, 153, 255), (51, 153, 255) # legs
309
+ ]
310
+ limb_color = [
311
+ (51, 153, 255), (0, 255, 0), (255, 128, 0), (255, 153, 255), (102, 178, 255),
312
+ (255, 51, 51), (51, 255, 153), (255, 178, 102), (230, 230, 0), (255, 153, 204),
313
+ (255, 102, 255), (153, 255, 153), (255, 255, 128), (0, 255, 255), (255, 255, 0),
314
+ (255, 204, 153), (153, 204, 255), (255, 153, 153), (204, 153, 255)
315
+ ]
316
+
317
+ # Draw results
318
+ for i, det in enumerate(detections):
319
+ box = det[:4].astype(int)
320
+ conf = det[4]
321
+
322
+ cv2.rectangle(img0, (box[0], box[1]), (box[2], box[3]), (255, 42, 4), 2)
323
+ cv2.putText(img0, f"person {conf:.2f}", (box[0], box[1] - 10),
324
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 42, 4), 2)
325
+
326
+ # COCO skeleton (1-based indices)
327
+ skeleton = [
328
+ [16, 14], [14, 12], [17, 15], [15, 13], [12, 13], # legs
329
+ [6, 12], [7, 13], [6, 7], # torso
330
+ [6, 8], [7, 9], [8, 10], [9, 11], # arms
331
+ [2, 3], [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7] # face
332
+ ]
333
+
334
+ kpt = all_keypoints[i]
335
+
336
+ for sk_idx, sk in enumerate(skeleton):
337
+ idx1, idx2 = sk[0] - 1, sk[1] - 1
338
+ if idx1 < 0 or idx1 >= 17 or idx2 < 0 or idx2 >= 17:
339
+ continue
340
+ if kpt[idx1, 2] > 0.5 and kpt[idx2, 2] > 0.5:
341
+ pt1 = (int(kpt[idx1, 0]), int(kpt[idx1, 1]))
342
+ pt2 = (int(kpt[idx2, 0]), int(kpt[idx2, 1]))
343
+ color = limb_color[sk_idx % len(limb_color)]
344
+ cv2.line(img0, pt1, pt2, color, 2)
345
+
346
+ for j, (x, y, conf_kpt) in enumerate(kpt):
347
+ if conf_kpt > 0.5:
348
+ color = kpt_color[j] if j < len(kpt_color) else (0, 255, 0)
349
+ cv2.circle(img0, (int(x), int(y)), 5, color, -1)
350
+
351
+ cv2.imwrite(opt.img_save_path, img0)
352
+ print(f"Done! Found {len(detections)} persons. Result saved to {opt.img_save_path}")
353
+
354
+
355
+ if __name__ == "__main__":
356
+ main()
result_yolov8_pose.jpg ADDED

Git LFS Details

  • SHA256: 5cc19989c96364183ed8486557570d1cc735221469b321f64456a588451fc0cd
  • Pointer size: 131 Bytes
  • Size of remote file: 500 kB
yolov8l-pose_640x640.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:47070ae5e07264c852ec1140d3ca051fae86a866b6eed3bcdae32a1c6df1cc01
3
+ size 177977300
yolov8m-pose_640x640.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9153dd5d5a9c42340a03233fbc10663d6e026330d50841e50155918f78e7acde
3
+ size 105883538
yolov8n-pose_640x640.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c28854a5e4139f90d9e527bf762e674976347ecc6841f9956246f443a5feda23
3
+ size 13231214
yolov8s-pose_640x640.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50582ba675ec2e1deec4a4b46884bb07e225ba81fc16380a73c440bc61432834
3
+ size 46534489
yolov8x-pose_640x640.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25c64b8f7d382509628fd6e5ce040b43c5794cfbf1501addfae5289b32d6ef70
3
+ size 277963799