Fangming Guo commited on
Commit
f3370c1
·
verified ·
1 Parent(s): b8c8f04

Upload 47 files

Browse files
Files changed (48) hide show
  1. .gitattributes +2 -0
  2. AX615/yolov8l-seg_640x640_npu1.axmodel +3 -0
  3. AX615/yolov8l-seg_640x640_npu2.axmodel +3 -0
  4. AX615/yolov8m-seg_640x640_npu1.axmodel +3 -0
  5. AX615/yolov8m-seg_640x640_npu2.axmodel +3 -0
  6. AX615/yolov8n-seg_640x640_npu1.axmodel +3 -0
  7. AX615/yolov8n-seg_640x640_npu2.axmodel +3 -0
  8. AX615/yolov8s-seg_640x640_npu1.axmodel +3 -0
  9. AX615/yolov8s-seg_640x640_npu2.axmodel +3 -0
  10. AX615/yolov8x-seg_640x640_npu1.axmodel +3 -0
  11. AX615/yolov8x-seg_640x640_npu2.axmodel +3 -0
  12. AX620E/yolov8l-seg_640x640_npu1.axmodel +3 -0
  13. AX620E/yolov8l-seg_640x640_npu2.axmodel +3 -0
  14. AX620E/yolov8m-seg_640x640_npu1.axmodel +3 -0
  15. AX620E/yolov8m-seg_640x640_npu2.axmodel +3 -0
  16. AX620E/yolov8n-seg_640x640_npu1.axmodel +3 -0
  17. AX620E/yolov8n-seg_640x640_npu2.axmodel +3 -0
  18. AX620E/yolov8s-seg_640x640_npu1.axmodel +3 -0
  19. AX620E/yolov8s-seg_640x640_npu2.axmodel +3 -0
  20. AX620E/yolov8x-seg_640x640_npu1.axmodel +3 -0
  21. AX620E/yolov8x-seg_640x640_npu2.axmodel +3 -0
  22. AX637/yolov8l-seg_640x640_npu1.axmodel +3 -0
  23. AX637/yolov8m-seg_640x640_npu1.axmodel +3 -0
  24. AX637/yolov8n-seg_640x640_npu1.axmodel +3 -0
  25. AX637/yolov8s-seg_640x640_npu1.axmodel +3 -0
  26. AX637/yolov8x-seg_640x640_npu1.axmodel +3 -0
  27. AX650/yolov8l-seg_640x640_npu1.axmodel +3 -0
  28. AX650/yolov8l-seg_640x640_npu3.axmodel +3 -0
  29. AX650/yolov8m-seg_640x640_npu1.axmodel +3 -0
  30. AX650/yolov8m-seg_640x640_npu3.axmodel +3 -0
  31. AX650/yolov8n-seg_640x640_npu1.axmodel +3 -0
  32. AX650/yolov8n-seg_640x640_npu3.axmodel +3 -0
  33. AX650/yolov8s-seg_640x640_npu1.axmodel +3 -0
  34. AX650/yolov8s-seg_640x640_npu3.axmodel +3 -0
  35. AX650/yolov8x-seg_640x640_npu1.axmodel +3 -0
  36. AX650/yolov8x-seg_640x640_npu3.axmodel +3 -0
  37. ax_infer.py +306 -0
  38. bus.jpg +3 -0
  39. coco_1000.tar +3 -0
  40. config.json +32 -0
  41. export_onnx.py +111 -0
  42. onnx_infer.py +313 -0
  43. result_yolov8_seg.jpg +3 -0
  44. yolov8l-seg_640x640.onnx +3 -0
  45. yolov8m-seg_640x640.onnx +3 -0
  46. yolov8n-seg_640x640.onnx +3 -0
  47. yolov8s-seg_640x640.onnx +3 -0
  48. yolov8x-seg_640x640.onnx +3 -0
.gitattributes CHANGED
@@ -42,3 +42,5 @@ axcl_aarch64/axcl_yolov8_seg filter=lfs diff=lfs merge=lfs -text
42
  yolov8_seg_axcl_out.jpg filter=lfs diff=lfs merge=lfs -text
43
  axcl_x86_64/axcl_yolov8_seg filter=lfs diff=lfs merge=lfs -text
44
  *.axmodel filter=lfs diff=lfs merge=lfs -text
 
 
 
42
  yolov8_seg_axcl_out.jpg filter=lfs diff=lfs merge=lfs -text
43
  axcl_x86_64/axcl_yolov8_seg filter=lfs diff=lfs merge=lfs -text
44
  *.axmodel filter=lfs diff=lfs merge=lfs -text
45
+ bus.jpg filter=lfs diff=lfs merge=lfs -text
46
+ result_yolov8_seg.jpg filter=lfs diff=lfs merge=lfs -text
AX615/yolov8l-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ee1ebd0cb03cbdee40c8f60d1b87e9eb80e337e2a08bf2b70983a929146953e2
3
+ size 53559043
AX615/yolov8l-seg_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4949e952eb6651aad74eb2a5e662f01855b765716b83aef07d2d05df211eefcf
3
+ size 47419871
AX615/yolov8m-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d21ec986e5ac8e6fc70cbc4bcf77b653d4b438eeba2ba4afdbbb0b7001c616a7
3
+ size 30596311
AX615/yolov8m-seg_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e46b26307d73f18d71d6aad4b792844c000ca81bbbb02f65b7f03a4939cd32e
3
+ size 28145395
AX615/yolov8n-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:16daecc36fca990d67b7d71aaba03e85289513bc9365b8a4df2d0201dacecacb
3
+ size 4023223
AX615/yolov8n-seg_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e95b15919671ea10c4c775cec3ca9b417bb2bd9b00a8059ad17f6977d5e17967
3
+ size 3687511
AX615/yolov8s-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c36ca12edd6aa6119bed02b4c3789a2213447d5acc191a9a208c36d6bf262b9b
3
+ size 13531735
AX615/yolov8s-seg_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2531fbbc75fe18bf0aa71e7d08d0c90a86a597b0c2853a17ac2f22bc6d6b86d
3
+ size 12233399
AX615/yolov8x-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe6ba94e2ccc05f683a227c2752ccdbdd24d120591a9c889047382646d317cd8
3
+ size 85531167
AX615/yolov8x-seg_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f48d954b73ef9bd049a923182be5ffe40d368d3be9836894c89f664ffda424a
3
+ size 74173243
AX620E/yolov8l-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e28abd85f7f6db93d5be49891148c4e3e8f4a7ae8d967eab8edab5a0bc0522d7
3
+ size 55088997
AX620E/yolov8l-seg_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b892996eb0ee905b23965a9b39ca2b6854cbc9611145a1cbe4deab4562a5e983
3
+ size 47443329
AX620E/yolov8m-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1e2a5754feb46e69a10fb1914beab7c8744905d94b2006d91db59be7204d282b
3
+ size 32397229
AX620E/yolov8m-seg_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a05191a36bd82a1076ab4a3d4db25a042e915023a8c8b169f01cd9ebdbbd905d
3
+ size 28376617
AX620E/yolov8n-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f2362408e14daec19cfcafb7d81eb9b963d1da046b6357ca3e3a018ed30e404d
3
+ size 4231465
AX620E/yolov8n-seg_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f1f49e9d0b87938a0882d4e4e5eb22b7175d5c6e1ceb8288b703544960053c2
3
+ size 3748729
AX620E/yolov8s-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbcc582ef71fc0053c9f27693fb4636f0e7aa654878f6fbc36e202f04db26fe4
3
+ size 13829785
AX620E/yolov8s-seg_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b22fba1cd7414a82f7dc059fbd77793aaae143a083297d4216fe3ae930756757
3
+ size 12270657
AX620E/yolov8x-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ec9986cb62bb8aaa2474b80fb79f697c0054356da7b8d879d9517a6ac4b3483
3
+ size 86048261
AX620E/yolov8x-seg_640x640_npu2.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4bdc08166c299d993ccd1c98c43fe63491ab27a2a7d54924c90d85175af6d888
3
+ size 74638485
AX637/yolov8l-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a452ee94ee0d82231cd251c07488bdc562a6244b7d1c79132be5a71029f12fac
3
+ size 46840623
AX637/yolov8m-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c232393417209e9eff412e673054bef81dc45e0bfb06e28fd6b9888c3b143a37
3
+ size 28046915
AX637/yolov8n-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:44f97db66aac0f525ee968aa87747641ae3123238bb4fd85c5a6a4e3febcf0a3
3
+ size 3969871
AX637/yolov8s-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3850a38d95039c287e98c842f66f6e6f7af742d262d4dc93195e572213db86af
3
+ size 12242959
AX637/yolov8x-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc1364c3d1f8b5f08681523b9f7814860f6bec2a2159d8a5e3484981483841e0
3
+ size 74247723
AX650/yolov8l-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:05706482b3ed405510dd6b69e96987470f1d2806d37dd3fb892ffad92066860f
3
+ size 47669199
AX650/yolov8l-seg_640x640_npu3.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50417fc2fd1ba22f0ae0712f82b7f0a3628a7ac738f2f9e36262d47044b3cadb
3
+ size 48161411
AX650/yolov8m-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:828173a9d6ed8a2baf43d7cf159ca6e93eb2046fc1f06f4f90a50042089c0889
3
+ size 28345411
AX650/yolov8m-seg_640x640_npu3.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5156fc8d8fa9e162c5170dc8733b4242e7575bc69533bf8abc732665c413ee18
3
+ size 28728887
AX650/yolov8n-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e37a41ab341d08093318353fbd437008e461110ca13aa2ffb53ef0ff80e24ff
3
+ size 3759715
AX650/yolov8n-seg_640x640_npu3.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0864456874aa78739eb270ac05ee5a91d8e50c9ab55faf324e9758ec590d3382
3
+ size 4031599
AX650/yolov8s-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb836ddbb151993f20790ff7237650d2636476c96e93a22af9fc218265b9b3b5
3
+ size 12353539
AX650/yolov8s-seg_640x640_npu3.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:138499d90eba16e6709a75d7ea667fe99bbdd3526a45a707f4a8905c63614604
3
+ size 12623215
AX650/yolov8x-seg_640x640_npu1.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cdad607330d0d0416e9498e881fdabc722cd860ccd51a5f9c36a1027bd0dc8b1
3
+ size 74608263
AX650/yolov8x-seg_640x640_npu3.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b8df655512c825300845ebe0e28ca99faa78372b4ba475ef68041eebb314a3c
3
+ size 75565791
ax_infer.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import cv2
4
+ import numpy as np
5
+ from time import time
6
+ import argparse
7
+ import logging
8
+ import axengine as ort
9
+
10
+ logging.basicConfig(
11
+ level=logging.DEBUG,
12
+ format='[%(name)s] [%(asctime)s.%(msecs)03d] [%(levelname)s] %(message)s',
13
+ datefmt='%H:%M:%S'
14
+ )
15
+ logger = logging.getLogger("YOLOv8-Seg")
16
+
17
+
18
+ def infer_hw_layout(shape):
19
+ """Infer input height, width and layout from model input shape."""
20
+ shape = list(shape)
21
+ if len(shape) == 4 and shape[-1] == 3:
22
+ h = int(shape[1] or 640)
23
+ w = int(shape[2] or 640)
24
+ return h, w, "NHWC"
25
+ if len(shape) == 4 and shape[1] == 3:
26
+ h = int(shape[2] or 640)
27
+ w = int(shape[3] or 640)
28
+ return h, w, "NCHW"
29
+ return 640, 640, "NCHW"
30
+
31
+
32
+ def softmax(x, axis=-1):
33
+ """Compute softmax along axis."""
34
+ e_x = np.exp(x - np.max(x, axis=axis, keepdims=True))
35
+ return e_x / np.sum(e_x, axis=axis, keepdims=True)
36
+
37
+
38
+ def dfl_decode(box_pred, reg_max=16):
39
+ """Decode DFL (Distribution Focal Loss) box predictions to ltrb distances."""
40
+ N = box_pred.shape[0]
41
+ box_pred = box_pred.reshape(N, 4, reg_max)
42
+ box_pred = softmax(box_pred, axis=-1)
43
+ proj = np.arange(reg_max, dtype=np.float32)
44
+ return np.sum(box_pred * proj, axis=-1) # (N, 4)
45
+
46
+
47
+ def process_mask(protos, mask_coeffs, boxes, model_shape, orig_shape, scale):
48
+ """
49
+ Process masks from prototypes and coefficients.
50
+
51
+ Args:
52
+ protos: (nm, proto_h, proto_w) mask prototypes
53
+ mask_coeffs: (N, nm) mask coefficients
54
+ boxes: (N, 4) boxes in model coordinates (xyxy)
55
+ model_shape: (h, w) model input shape
56
+ orig_shape: (h, w) original image shape
57
+ scale: preprocessing scale factor
58
+
59
+ Returns:
60
+ masks: (N, orig_h, orig_w) binary masks
61
+ """
62
+ nm, proto_h, proto_w = protos.shape
63
+ N = len(mask_coeffs)
64
+
65
+ if N == 0:
66
+ return np.zeros((0, orig_shape[0], orig_shape[1]), dtype=np.uint8)
67
+
68
+ masks = (mask_coeffs @ protos.reshape(nm, -1)).reshape(N, proto_h, proto_w)
69
+ masks = 1 / (1 + np.exp(-masks))
70
+
71
+ width_ratio = proto_w / model_shape[1]
72
+ height_ratio = proto_h / model_shape[0]
73
+ boxes_proto = boxes.copy()
74
+ boxes_proto[:, [0, 2]] *= width_ratio
75
+ boxes_proto[:, [1, 3]] *= height_ratio
76
+
77
+ for i, (x1, y1, x2, y2) in enumerate(boxes_proto.astype(int)):
78
+ x1, y1 = max(0, x1), max(0, y1)
79
+ x2, y2 = min(proto_w, x2), min(proto_h, y2)
80
+ masks[i, :y1, :] = 0
81
+ masks[i, y2:, :] = 0
82
+ masks[i, :, :x1] = 0
83
+ masks[i, :, x2:] = 0
84
+
85
+ masks_upsampled = np.zeros((N, model_shape[0], model_shape[1]), dtype=np.float32)
86
+ for i in range(N):
87
+ masks_upsampled[i] = cv2.resize(masks[i], (model_shape[1], model_shape[0]),
88
+ interpolation=cv2.INTER_LINEAR)
89
+
90
+ new_h = int(orig_shape[0] * scale)
91
+ new_w = int(orig_shape[1] * scale)
92
+ masks_cropped = masks_upsampled[:, :new_h, :new_w]
93
+
94
+ masks_final = np.zeros((N, orig_shape[0], orig_shape[1]), dtype=np.uint8)
95
+ for i in range(N):
96
+ mask_resized = cv2.resize(masks_cropped[i], (orig_shape[1], orig_shape[0]),
97
+ interpolation=cv2.INTER_LINEAR)
98
+ masks_final[i] = (mask_resized > 0.5).astype(np.uint8)
99
+
100
+ return masks_final
101
+
102
+
103
+ def main():
104
+ ap = argparse.ArgumentParser(description='YOLOv8-Seg Inference (AXERARuntime)')
105
+ ap.add_argument('--model-path', type=str, default='yolov8n-seg_640x640.axmodel')
106
+ ap.add_argument('--test-img', type=str, default='bus.jpg')
107
+ ap.add_argument('--img-save-path', type=str, default='result_yolov8_seg.jpg')
108
+ ap.add_argument('--score-thres', type=float, default=0.25)
109
+ ap.add_argument('--nms-thres', type=float, default=0.7)
110
+ ap.add_argument('--providers', type=str, default='AxEngineExecutionProvider')
111
+ opt = ap.parse_args()
112
+
113
+ if not os.path.exists(opt.model_path):
114
+ logger.error(f"Model not found: {opt.model_path}")
115
+ return
116
+
117
+ t0 = time()
118
+ providers = [p.strip() for p in opt.providers.split(",") if p.strip()] or None
119
+ sess = ort.InferenceSession(opt.model_path, providers=providers)
120
+ logger.debug(f"\033[1;31mLoad model time = {(time() - t0) * 1000:.2f} ms\033[0m")
121
+
122
+ inp = sess.get_inputs()[0]
123
+ input_name = inp.name
124
+ m_h, m_w, layout = infer_hw_layout(inp.shape)
125
+
126
+ img = cv2.imread(opt.test_img)
127
+ if img is None:
128
+ logger.error(f"Image not found or unreadable: {opt.test_img}")
129
+ return
130
+
131
+ # Preprocess
132
+ t0 = time()
133
+ orig_h, orig_w = img.shape[:2]
134
+ scale = min(m_h / orig_h, m_w / orig_w)
135
+ new_w, new_h = int(orig_w * scale), int(orig_h * scale)
136
+
137
+ resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
138
+ padded = cv2.copyMakeBorder(
139
+ resized, 0, m_h - new_h, 0, m_w - new_w,
140
+ cv2.BORDER_CONSTANT, value=(127, 127, 127)
141
+ )
142
+ rgb = cv2.cvtColor(padded, cv2.COLOR_BGR2RGB)
143
+ input_tensor = rgb[None, ...].astype(np.uint8) if layout == "NHWC" else np.transpose(rgb, (2, 0, 1))[None, ...].astype(np.uint8)
144
+ logger.debug(f"\033[1;31mPre-process time = {(time() - t0) * 1000:.2f} ms\033[0m")
145
+
146
+ # Inference
147
+ t0 = time()
148
+ ort_outputs = sess.run(None, {input_name: input_tensor})
149
+ out_metas = sess.get_outputs()
150
+ logger.debug(f"\033[1;31mForward time = {(time() - t0) * 1000:.2f} ms\033[0m")
151
+
152
+ # Post-process
153
+ t0 = time()
154
+ strides = (8, 16, 32)
155
+ conf_raw = -np.log(1 / opt.score_thres - 1)
156
+ detections = []
157
+ all_mask_coeffs = []
158
+
159
+ output_items = []
160
+ for meta, data in zip(out_metas, ort_outputs):
161
+ shape = list(meta.shape)
162
+ if any(s is None or isinstance(s, str) for s in shape):
163
+ shape = list(data.shape)
164
+ output_items.append((data, shape))
165
+
166
+ # Process each scale (9 detection outputs + 1 proto = 10 total)
167
+ for scale_idx, stride in enumerate(strides):
168
+ box_idx = scale_idx * 3
169
+ cls_idx = scale_idx * 3 + 1
170
+ mask_idx = scale_idx * 3 + 2
171
+
172
+ if box_idx >= len(output_items) or cls_idx >= len(output_items) or mask_idx >= len(output_items):
173
+ continue
174
+
175
+ box_data, box_shape = output_items[box_idx]
176
+ cls_data, cls_shape = output_items[cls_idx]
177
+ mask_data, mask_shape = output_items[mask_idx]
178
+
179
+ H, W = box_shape[1], box_shape[2]
180
+ box_channels = box_shape[-1]
181
+
182
+ # Determine if DFL is used (YOLOv8: 4*reg_max = 64)
183
+ reg_max = None
184
+ if box_channels > 4 and box_channels % 4 == 0:
185
+ reg_max = box_channels // 4
186
+
187
+ box_data = box_data[0].reshape(-1, box_channels)
188
+ cls_data = cls_data[0].reshape(-1, cls_shape[-1])
189
+ mask_data = mask_data[0].reshape(-1, mask_shape[-1])
190
+
191
+ cls_scores = np.max(cls_data, axis=1)
192
+ cls_ids = np.argmax(cls_data, axis=1)
193
+
194
+ valid_mask = cls_scores >= conf_raw
195
+ if not np.any(valid_mask):
196
+ continue
197
+
198
+ v_box = box_data[valid_mask]
199
+ v_score = 1 / (1 + np.exp(-cls_scores[valid_mask]))
200
+ v_id = cls_ids[valid_mask]
201
+ v_mask = mask_data[valid_mask]
202
+
203
+ gy, gx = np.indices((H, W))
204
+ anchors = np.stack((gx.ravel(), gy.ravel()), axis=-1).astype(np.float32) + 0.5
205
+ anchors = anchors[valid_mask]
206
+
207
+ # Decode boxes (DFL -> ltrb -> xyxy)
208
+ if reg_max is not None:
209
+ v_box = dfl_decode(v_box, reg_max)
210
+ lt = v_box[:, :2]
211
+ rb = v_box[:, 2:]
212
+ x1y1 = anchors - lt
213
+ x2y2 = anchors + rb
214
+ boxes = np.hstack([x1y1, x2y2]) * stride
215
+
216
+ for i in range(len(boxes)):
217
+ detections.append([*boxes[i], v_score[i], v_id[i]])
218
+ all_mask_coeffs.append(v_mask[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_mask_coeffs = np.array(all_mask_coeffs)
229
+
230
+ # NMS
231
+ xywh = detections[:, :4].copy()
232
+ xywh[:, 2] = xywh[:, 2] - xywh[:, 0]
233
+ xywh[:, 3] = xywh[:, 3] - xywh[:, 1]
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
+ detections = detections[indices]
244
+ all_mask_coeffs = all_mask_coeffs[indices]
245
+
246
+ # Get proto output (last output)
247
+ proto = ort_outputs[-1][0] # (nm, proto_h, proto_w)
248
+ logger.debug(f"Proto shape: {proto.shape}")
249
+
250
+ # Process masks (before scaling boxes!)
251
+ boxes_model = detections[:, :4].copy()
252
+ masks = process_mask(proto, all_mask_coeffs, boxes_model, (m_h, m_w), (orig_h, orig_w), scale)
253
+
254
+ # Scale boxes to original image coordinates
255
+ detections[:, :4] = detections[:, :4] / scale
256
+ detections[:, [0, 2]] = np.clip(detections[:, [0, 2]], 0, orig_w)
257
+ detections[:, [1, 3]] = np.clip(detections[:, [1, 3]], 0, orig_h)
258
+
259
+ # COCO class names
260
+ coco_names = [
261
+ "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
262
+ "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
263
+ "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
264
+ "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
265
+ "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
266
+ "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
267
+ "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard",
268
+ "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase",
269
+ "scissors", "teddy bear", "hair drier", "toothbrush"
270
+ ]
271
+
272
+ base_colors = [
273
+ (255, 42, 4), (235, 219, 11), (243, 243, 243), (183, 223, 0), (104, 31, 17),
274
+ (221, 111, 255), (79, 68, 255), (0, 237, 204), (68, 243, 0), (255, 0, 189),
275
+ (255, 180, 0), (186, 0, 221), (255, 255, 0), (0, 192, 38), (179, 255, 1),
276
+ (255, 36, 125), (104, 0, 123), (108, 27, 255), (47, 109, 252), (11, 255, 162),
277
+ ]
278
+
279
+ logger.info(f"\033[1;32mDraw Results ({len(detections)} objects): \033[0m")
280
+
281
+ for i, det in enumerate(detections):
282
+ box = det[:4].astype(int)
283
+ conf = det[4]
284
+ cls_id = int(det[5])
285
+ color = [int(c) for c in base_colors[cls_id % len(base_colors)]]
286
+ cls_name = coco_names[cls_id] if cls_id < len(coco_names) else str(cls_id)
287
+
288
+ logger.info(f"({box[0]}, {box[1]}, {box[2]}, {box[3]}) -> {cls_name}: {conf:.2f}")
289
+
290
+ if i < len(masks):
291
+ mask = masks[i]
292
+ mask_colored = np.zeros_like(img)
293
+ mask_colored[mask > 0] = color
294
+ img = cv2.addWeighted(img, 1.0, mask_colored, 0.5, 0)
295
+
296
+ cv2.rectangle(img, (box[0], box[1]), (box[2], box[3]), color, 2)
297
+ label = f"{cls_name} {conf:.2f}"
298
+ cv2.putText(img, label, (box[0], box[1] - 10),
299
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
300
+
301
+ cv2.imwrite(opt.img_save_path, img)
302
+ logger.info(f"Saved to {opt.img_save_path}")
303
+
304
+
305
+ if __name__ == "__main__":
306
+ 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,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import torch
3
+ from ultralytics import YOLO
4
+ from ultralytics.nn.modules.head import Segment
5
+ import os
6
+ import shutil
7
+
8
+
9
+ def npu_segment_forward(self, x):
10
+ """
11
+ YOLOv8 Segment Head Modified for NPU.
12
+
13
+ YOLOv8 Segment structure (NOT end2end):
14
+ - cv2: box regression layers (DFL, out channels = 4 * reg_max = 64)
15
+ - cv3: classification layers (out channels = nc = 80)
16
+ - cv4: mask coefficient layers (out channels = nm = 32)
17
+ - proto: Proto module for generating mask prototypes
18
+
19
+ Output:
20
+ List of Tensors (10 items: 3 scales * 3 outputs + 1 proto), NHWC for detection, NCHW for proto
21
+ [
22
+ Scale1_Box_Raw (B, 80, 80, 4*reg_max), <-- raw DFL box logits
23
+ Scale1_Cls_Raw (B, 80, 80, nc), <-- class scores (raw logits), nc=80
24
+ Scale1_Mask_Raw (B, 80, 80, nm), <-- mask coefficients, nm=32
25
+ Scale2_Box_Raw (B, 40, 40, 4*reg_max),
26
+ Scale2_Cls_Raw (B, 40, 40, nc),
27
+ Scale2_Mask_Raw (B, 40, 40, nm),
28
+ Scale3_Box_Raw (B, 20, 20, 4*reg_max),
29
+ Scale3_Cls_Raw (B, 20, 20, nc),
30
+ Scale3_Mask_Raw (B, 20, 20, nm),
31
+ Proto (B, nm, H, W), <-- mask prototypes (160x160 for 640 input)
32
+ ]
33
+ """
34
+ if not isinstance(x, (list, tuple)):
35
+ x = [x]
36
+
37
+ res = []
38
+
39
+ box_layers = self.cv2
40
+ cls_layers = self.cv3
41
+ mask_layers = self.cv4
42
+
43
+ for i in range(self.nl):
44
+ # 1. Box branch (raw DFL logits) - NHWC
45
+ bboxes = box_layers[i](x[i]).permute(0, 2, 3, 1)
46
+
47
+ # 2. Cls branch (raw logits) - NHWC
48
+ scores = cls_layers[i](x[i]).permute(0, 2, 3, 1)
49
+
50
+ # 3. Mask coefficients branch - NHWC
51
+ masks = mask_layers[i](x[i]).permute(0, 2, 3, 1)
52
+
53
+ res.append(bboxes)
54
+ res.append(scores)
55
+ res.append(masks)
56
+
57
+ # 4. Proto output - NCHW (keep original format for mask processing)
58
+ proto = self.proto(x[0])
59
+ res.append(proto)
60
+
61
+ return res
62
+
63
+
64
+ def batch_export_yolov8_seg():
65
+ variants = ['n', 's', 'm', 'l', 'x']
66
+ imgsz = 640
67
+
68
+ # Execute Monkey Patch
69
+ Segment.forward = npu_segment_forward
70
+ print("Monkey patch applied for Segment: Output Layout forced to NHWC + Proto.")
71
+
72
+ for v in variants:
73
+ model_name = f"yolov8{v}-seg"
74
+ pt_path = f"{model_name}.pt"
75
+ onnx_final_name = f"{model_name}_640x640.onnx"
76
+ print(f"\n--- Processing {model_name} ---")
77
+ try:
78
+ # Load model
79
+ model = YOLO(pt_path)
80
+
81
+ # Reapply monkey patch
82
+ Segment.forward = npu_segment_forward
83
+
84
+ # Ensure the model's head also uses the new forward
85
+ if hasattr(model.model, 'model') and len(model.model.model) > 0:
86
+ head = model.model.model[-1]
87
+ if isinstance(head, Segment):
88
+ head.forward = lambda x: npu_segment_forward(head, x)
89
+
90
+ # Execute export
91
+ exported_path = model.export(
92
+ format="onnx",
93
+ imgsz=imgsz,
94
+ dynamic=False,
95
+ opset=11,
96
+ simplify=True,
97
+ nms=False
98
+ )
99
+
100
+ # Move and rename
101
+ if exported_path:
102
+ shutil.move(exported_path, onnx_final_name)
103
+ print(f"Success: {onnx_final_name}")
104
+ except Exception as e:
105
+ print(f"Failed to export {model_name}: {e}")
106
+ import traceback
107
+ traceback.print_exc()
108
+
109
+
110
+ if __name__ == "__main__":
111
+ batch_export_yolov8_seg()
onnx_infer.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ orig_h, orig_w = image.shape[:2]
14
+ m_h, m_w = input_size
15
+
16
+ scale = min(m_h / orig_h, m_w / orig_w)
17
+ new_w, new_h = int(orig_w * scale), int(orig_h * scale)
18
+ img_resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
19
+
20
+ # Left-top aligned padding
21
+ input_bgr = cv2.copyMakeBorder(
22
+ img_resized, 0, m_h - new_h, 0, m_w - new_w,
23
+ cv2.BORDER_CONSTANT, value=(114, 114, 114)
24
+ )
25
+
26
+ input_rgb = cv2.cvtColor(input_bgr, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
27
+ input_tensor = np.transpose(input_rgb, (2, 0, 1))[None, ...]
28
+
29
+ return input_tensor, scale, (orig_h, orig_w)
30
+
31
+
32
+ def softmax(x, axis=-1):
33
+ """Compute softmax along axis."""
34
+ e_x = np.exp(x - np.max(x, axis=axis, keepdims=True))
35
+ return e_x / np.sum(e_x, axis=axis, keepdims=True)
36
+
37
+
38
+ def dfl_decode(box_pred, reg_max=16):
39
+ """Decode DFL (Distribution Focal Loss) box predictions to ltrb distances."""
40
+ N = box_pred.shape[0]
41
+ box_pred = box_pred.reshape(N, 4, reg_max)
42
+ box_pred = softmax(box_pred, axis=-1)
43
+ proj = np.arange(reg_max, dtype=np.float32)
44
+ return np.sum(box_pred * proj, axis=-1) # (N, 4)
45
+
46
+
47
+ def decode_bboxes(bbox_preds, anchors, stride, reg_max=None):
48
+ """Decode bounding boxes. If reg_max given and channels match, apply DFL first."""
49
+ if reg_max is not None and bbox_preds.shape[-1] == 4 * reg_max:
50
+ bbox_preds = dfl_decode(bbox_preds, reg_max)
51
+ lt = bbox_preds[:, :2]
52
+ rb = bbox_preds[:, 2:]
53
+ x1y1 = anchors - lt
54
+ x2y2 = anchors + rb
55
+ boxes = np.hstack([x1y1, x2y2]) * stride
56
+ return boxes
57
+
58
+
59
+ def scale_boxes_lefttop(boxes, scale, orig_shape):
60
+ """Scale boxes from model output to original image coordinates (left-top aligned)."""
61
+ boxes = boxes.copy()
62
+ boxes[..., :4] /= scale
63
+ boxes[..., [0, 2]] = np.clip(boxes[..., [0, 2]], 0, orig_shape[1])
64
+ boxes[..., [1, 3]] = np.clip(boxes[..., [1, 3]], 0, orig_shape[0])
65
+ return boxes
66
+
67
+
68
+ def process_mask(protos, mask_coeffs, boxes, model_shape, orig_shape, scale):
69
+ """
70
+ Process masks from prototypes and coefficients.
71
+
72
+ Args:
73
+ protos: (nm, proto_h, proto_w) mask prototypes
74
+ mask_coeffs: (N, nm) mask coefficients
75
+ boxes: (N, 4) boxes in model coordinates (xyxy)
76
+ model_shape: (h, w) model input shape
77
+ orig_shape: (h, w) original image shape
78
+ scale: preprocessing scale factor
79
+
80
+ Returns:
81
+ masks: (N, orig_h, orig_w) binary masks
82
+ """
83
+ nm, proto_h, proto_w = protos.shape
84
+ N = len(mask_coeffs)
85
+
86
+ if N == 0:
87
+ return np.zeros((0, orig_shape[0], orig_shape[1]), dtype=np.uint8)
88
+
89
+ # Compute masks: (N, nm) @ (nm, proto_h*proto_w) -> (N, proto_h, proto_w)
90
+ masks = (mask_coeffs @ protos.reshape(nm, -1)).reshape(N, proto_h, proto_w)
91
+ # Sigmoid activation
92
+ masks = 1 / (1 + np.exp(-masks))
93
+
94
+ # Scale boxes to proto coordinates
95
+ width_ratio = proto_w / model_shape[1]
96
+ height_ratio = proto_h / model_shape[0]
97
+ boxes_proto = boxes.copy()
98
+ boxes_proto[:, [0, 2]] *= width_ratio
99
+ boxes_proto[:, [1, 3]] *= height_ratio
100
+
101
+ # Crop masks to bounding box regions
102
+ for i, (x1, y1, x2, y2) in enumerate(boxes_proto.astype(int)):
103
+ x1, y1 = max(0, x1), max(0, y1)
104
+ x2, y2 = min(proto_w, x2), min(proto_h, y2)
105
+ masks[i, :y1, :] = 0
106
+ masks[i, y2:, :] = 0
107
+ masks[i, :, :x1] = 0
108
+ masks[i, :, x2:] = 0
109
+
110
+ # Upsample masks to model input size
111
+ masks_upsampled = np.zeros((N, model_shape[0], model_shape[1]), dtype=np.float32)
112
+ for i in range(N):
113
+ masks_upsampled[i] = cv2.resize(masks[i], (model_shape[1], model_shape[0]),
114
+ interpolation=cv2.INTER_LINEAR)
115
+
116
+ # Crop to valid region (left-top aligned) and resize to original
117
+ new_h = int(orig_shape[0] * scale)
118
+ new_w = int(orig_shape[1] * scale)
119
+ masks_cropped = masks_upsampled[:, :new_h, :new_w]
120
+
121
+ # Resize to original image size
122
+ masks_final = np.zeros((N, orig_shape[0], orig_shape[1]), dtype=np.uint8)
123
+ for i in range(N):
124
+ mask_resized = cv2.resize(masks_cropped[i], (orig_shape[1], orig_shape[0]),
125
+ interpolation=cv2.INTER_LINEAR)
126
+ masks_final[i] = (mask_resized > 0.5).astype(np.uint8)
127
+
128
+ return masks_final
129
+
130
+
131
+ def main():
132
+ parser = argparse.ArgumentParser(description='YOLOv8-Seg ONNX Inference')
133
+ parser.add_argument('-m', '--model', type=str, default='yolov8n-seg_640x640.onnx',
134
+ dest='model_path', help='Path to YOLOv8-Seg *.onnx Model.')
135
+ parser.add_argument('-i', '--img', type=str, default='bus.jpg',
136
+ dest='test_img', help='Path to Test Image.')
137
+ parser.add_argument('-o', '--output', type=str, default='result_yolov8_seg.jpg',
138
+ dest='img_save_path', help='Path to Save Result Image.')
139
+ parser.add_argument('--score-thres', type=float, default=0.25,
140
+ help='Confidence threshold.')
141
+ parser.add_argument('--nms-thres', type=float, default=0.7,
142
+ help='IoU threshold for NMS.')
143
+ opt = parser.parse_args()
144
+
145
+ if not os.path.exists(opt.model_path):
146
+ print(f"Error: Model not found: {opt.model_path}")
147
+ return
148
+
149
+ if not os.path.exists(opt.test_img):
150
+ print(f"Error: Image not found: {opt.test_img}")
151
+ return
152
+
153
+ # Load ONNX model
154
+ providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
155
+ try:
156
+ session = ort.InferenceSession(opt.model_path, providers=providers)
157
+ except:
158
+ session = ort.InferenceSession(opt.model_path, providers=['CPUExecutionProvider'])
159
+
160
+ input_name = session.get_inputs()[0].name
161
+ output_names = [o.name for o in session.get_outputs()]
162
+ input_shape = session.get_inputs()[0].shape
163
+ imgsz = (input_shape[2], input_shape[3])
164
+
165
+ # Load image
166
+ img0 = cv2.imread(opt.test_img)
167
+ if img0 is None:
168
+ print(f"Error: Cannot read image: {opt.test_img}")
169
+ return
170
+
171
+ # Preprocess
172
+ img, scale, orig_shape = preprocess_image(img0.copy(), imgsz)
173
+
174
+ # Inference
175
+ outputs = session.run(output_names, {input_name: img})
176
+
177
+ # Parse outputs: 9 detection outputs + 1 proto
178
+ strides = [8, 16, 32]
179
+ conf_raw = -np.log(1 / opt.score_thres - 1)
180
+ detections = []
181
+ all_mask_coeffs = []
182
+
183
+ # Process each scale
184
+ for scale_idx, stride in enumerate(strides):
185
+ box_idx = scale_idx * 3
186
+ cls_idx = scale_idx * 3 + 1
187
+ mask_idx = scale_idx * 3 + 2
188
+
189
+ box_data = outputs[box_idx] # (1, H, W, C) where C = 4 or 4*reg_max
190
+ cls_data = outputs[cls_idx] # (1, H, W, nc)
191
+ mask_data = outputs[mask_idx] # (1, H, W, nm)
192
+
193
+ H, W = box_data.shape[1:3]
194
+ box_channels = box_data.shape[-1]
195
+
196
+ # Determine if DFL is used (YOLOv8: 4*reg_max = 64)
197
+ reg_max = None
198
+ if box_channels > 4 and box_channels % 4 == 0:
199
+ reg_max = box_channels // 4
200
+
201
+ # Reshape
202
+ box_data = box_data[0].reshape(-1, box_channels)
203
+ cls_data = cls_data[0].reshape(-1, cls_data.shape[-1])
204
+ mask_data = mask_data[0].reshape(-1, mask_data.shape[-1])
205
+
206
+ # Get max class scores
207
+ cls_scores = np.max(cls_data, axis=1)
208
+ cls_ids = np.argmax(cls_data, axis=1)
209
+
210
+ # Filter by confidence
211
+ valid_mask = cls_scores >= conf_raw
212
+ if not np.any(valid_mask):
213
+ continue
214
+
215
+ v_box = box_data[valid_mask]
216
+ v_score = 1 / (1 + np.exp(-cls_scores[valid_mask]))
217
+ v_id = cls_ids[valid_mask]
218
+ v_mask = mask_data[valid_mask]
219
+
220
+ # Generate anchors
221
+ gy, gx = np.indices((H, W))
222
+ anchors = np.stack((gx.ravel(), gy.ravel()), axis=-1).astype(np.float32) + 0.5
223
+ anchors = anchors[valid_mask]
224
+
225
+ # Decode boxes
226
+ boxes = decode_bboxes(v_box, anchors, stride, reg_max)
227
+
228
+ # Store detections
229
+ for i in range(len(boxes)):
230
+ detections.append([*boxes[i], v_score[i], v_id[i]])
231
+ all_mask_coeffs.append(v_mask[i])
232
+
233
+ if len(detections) == 0:
234
+ print("No detections found.")
235
+ cv2.imwrite(opt.img_save_path, img0)
236
+ return
237
+
238
+ detections = np.array(detections)
239
+ all_mask_coeffs = np.array(all_mask_coeffs)
240
+
241
+ # NMS
242
+ xywh = detections[:, :4].copy()
243
+ xywh[:, 2] = xywh[:, 2] - xywh[:, 0]
244
+ xywh[:, 3] = xywh[:, 3] - xywh[:, 1]
245
+
246
+ indices = cv2.dnn.NMSBoxes(xywh.tolist(), detections[:, 4].tolist(), opt.score_thres, opt.nms_thres)
247
+
248
+ if len(indices) == 0:
249
+ print("No detections after NMS.")
250
+ cv2.imwrite(opt.img_save_path, img0)
251
+ return
252
+
253
+ indices = indices.flatten()
254
+ detections = detections[indices]
255
+ all_mask_coeffs = all_mask_coeffs[indices]
256
+
257
+ # Get proto output (last output)
258
+ proto = outputs[-1][0] # (nm, proto_h, proto_w)
259
+
260
+ # Process masks (before scaling boxes!)
261
+ boxes_model = detections[:, :4].copy()
262
+ masks = process_mask(proto, all_mask_coeffs, boxes_model, imgsz, orig_shape, scale)
263
+
264
+ # Scale boxes to original image
265
+ detections[:, :4] = scale_boxes_lefttop(detections[:, :4], scale, orig_shape)
266
+
267
+ # COCO class names
268
+ coco_names = [
269
+ "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
270
+ "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
271
+ "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
272
+ "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
273
+ "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
274
+ "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
275
+ "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard",
276
+ "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase",
277
+ "scissors", "teddy bear", "hair drier", "toothbrush"
278
+ ]
279
+
280
+ # Official Ultralytics colors (BGR format)
281
+ base_colors = [
282
+ (255, 42, 4), (235, 219, 11), (243, 243, 243), (183, 223, 0), (104, 31, 17),
283
+ (221, 111, 255), (79, 68, 255), (0, 237, 204), (68, 243, 0), (255, 0, 189),
284
+ (255, 180, 0), (186, 0, 221), (255, 255, 0), (0, 192, 38), (179, 255, 1),
285
+ (255, 36, 125), (104, 0, 123), (108, 27, 255), (47, 109, 252), (11, 255, 162),
286
+ ]
287
+
288
+ for i, det in enumerate(detections):
289
+ box = det[:4].astype(int)
290
+ conf = det[4]
291
+ cls_id = int(det[5])
292
+ color = [int(c) for c in base_colors[cls_id % len(base_colors)]]
293
+ cls_name = coco_names[cls_id] if cls_id < len(coco_names) else str(cls_id)
294
+
295
+ # Draw mask
296
+ if i < len(masks):
297
+ mask = masks[i]
298
+ mask_colored = np.zeros_like(img0)
299
+ mask_colored[mask > 0] = color
300
+ img0 = cv2.addWeighted(img0, 1.0, mask_colored, 0.5, 0)
301
+
302
+ # Draw box
303
+ cv2.rectangle(img0, (box[0], box[1]), (box[2], box[3]), color, 2)
304
+ label = f"{cls_name} {conf:.2f}"
305
+ cv2.putText(img0, label, (box[0], box[1] - 10),
306
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
307
+
308
+ cv2.imwrite(opt.img_save_path, img0)
309
+ print(f"Done! Found {len(detections)} objects. Result saved to {opt.img_save_path}")
310
+
311
+
312
+ if __name__ == "__main__":
313
+ main()
result_yolov8_seg.jpg ADDED

Git LFS Details

  • SHA256: daa0c302c407efa71d30d6d506b0031698adf71c51499d1bf42a462709c386b4
  • Pointer size: 131 Bytes
  • Size of remote file: 498 kB
yolov8l-seg_640x640.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b317e94a6ac695e6295128c5e548c6885f27e45a38e8e8b253b068e05eec175
3
+ size 184013253
yolov8m-seg_640x640.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b2381143275ca867888090aba58a56fe241bbe7173ef426c3985828d05268faf
3
+ size 109171967
yolov8n-seg_640x640.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:924de98d6bb9060205832f2a0787aa30d2591b41a1d6a818a5a4e9ee4fe274b3
3
+ size 13692609
yolov8s-seg_640x640.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:330f3943b4192ab54e33b5ba237445ccbf0c03a0ce68a1dd9f68b6ff324cd06a
3
+ size 47317830
yolov8x-seg_640x640.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6b88d24056e9139557e61ccd4575471ad51fd48ebbe675751567c2ea8df92fb
3
+ size 287309768