update
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- cow_pic/000000235857.jpg → 000000235857.jpg +0 -0
- AX650/{cow_ax650_npu3_v5.axmodel → cow_ax650_npu3.axmodel} +0 -0
- AX650/cow_ax650_npu3_26.axmodel +0 -3
- README.md +5 -14
- axmodel_infer_cow_yolo26.py +0 -543
- axmodel_infer_cow_yolov5.py +46 -49
- cow_pic/002_005662.jpg → axmodel_res.jpg +2 -2
- axmodel_res_sample.jpg +0 -3
- cow_pic/002_000264.jpg +0 -3
- cow_pic/002_003436.jpg +0 -3
- cow_pic/002_006511.jpg +0 -3
- cow_pic/002_007108.jpg +0 -3
- cow_pic/002_007213.jpg +0 -3
- cow_pic/003_000123.jpg +0 -3
- cow_pic/003_000792.jpg +0 -3
- cow_pic/003_001187.jpg +0 -3
- cow_pic/004_000284.jpg +0 -3
- cow_pic/004_001357.jpg +0 -3
- cow_pic/004_004980.jpg +0 -3
- cow_pic/004_005252.jpg +0 -3
- cow_pic/004_006297.jpg +0 -3
- cow_pic/004_007017.jpg +0 -3
- cow_pic/004_007153.jpg +0 -3
- cow_pic/005_000347.jpg +0 -3
- cow_pic/005_000523.jpg +0 -3
- cow_pic/006_000147.jpg +0 -3
- cow_pic/006_000307.jpg +0 -3
- cow_pic/006_001563.jpg +0 -3
- cow_pic/006_003026.jpg +0 -3
- cow_pic/006_006298.jpg +0 -3
- cow_pic/007_001324.jpg +0 -3
- cow_pic/007_001853.jpg +0 -3
- cow_pic/Bargur_000127.jpg +0 -3
- cow_pic/BeefCattleBehavior_000200.jpg +0 -3
- cow_pic/COLO_YOLO_000786.jpg +0 -3
- cow_pic/CattleWeightDetectSide_001235.jpg +0 -3
- cow_pic/CattleWeightDetectSide_003239.jpg +0 -3
- cow_pic/CowAndPeople642025_002794.jpg +0 -3
- cow_pic/CowAndPeople642025_003949.jpg +0 -3
- cow_pic/CowAndPeople642025_005457.jpg +0 -3
- cow_pic/CowAndPeople642025_006911.jpg +0 -3
- cow_pic/CowBreedClassification1_000829.jpg +0 -3
- cow_pic/CowBreedClassificationDataset_000614.jpg +0 -3
- cow_pic/CowLieStandWalk_003551.jpg +0 -3
- cow_pic/CowsandBuffalo_000168.jpg +0 -3
- cow_pic/CowsandBuffalo_001108.jpg +0 -3
- cow_pic/Cowv3ivoc_000268.jpg +0 -3
- cow_pic/Cowv3ivoc_000503.jpg +0 -3
- cow_pic/Ladakhi_000105.jpg +0 -3
- cow_pic/Mewati_000012.jpg +0 -3
cow_pic/000000235857.jpg → 000000235857.jpg
RENAMED
|
File without changes
|
AX650/{cow_ax650_npu3_v5.axmodel → cow_ax650_npu3.axmodel}
RENAMED
|
File without changes
|
AX650/cow_ax650_npu3_26.axmodel
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:d7a61eefeaf3613c061ddde59b5831b2c8a3d7cff0976926795fe150e722e4ca
|
| 3 |
-
size 1884250
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -6,7 +6,6 @@ pipeline_tag: object-detection
|
|
| 6 |
tags:
|
| 7 |
- Axera
|
| 8 |
- YOLOv5
|
| 9 |
-
- YOLO26
|
| 10 |
- NPU
|
| 11 |
- Ultralytics
|
| 12 |
- Cow Detection
|
|
@@ -15,7 +14,7 @@ tags:
|
|
| 15 |
|
| 16 |
# Cow-axera
|
| 17 |
|
| 18 |
-
This version of **Cow-axera** has been converted to run on the Axera NPU using **w8a16** quantization. It is trained
|
| 19 |
|
| 20 |
## Supported Classes
|
| 21 |
|
|
@@ -57,17 +56,15 @@ pip install axengine-0.1.3-py3-none-any.whl
|
|
| 57 |
### Inference with AX650 Host, such as M4N-Dock(爱芯派Pro)
|
| 58 |
|
| 59 |
Input image sample:
|
| 60 |
-

|
| 77 |
[INFO] Compiler version: 6.0 6965315a
|
| 78 |
-
Processing image: 002_000264.jpg
|
| 79 |
-
class: cow left:262 top:8 right:556 bottom:646 conf: 95%
|
| 80 |
-
Processing image: 000000235857.jpg
|
| 81 |
class: cow left:356 top:79 right:464 bottom:119 conf: 76%
|
| 82 |
class: cow left:57 top:109 right:322 bottom:284 conf: 94%
|
| 83 |
class: cow left:251 top:104 right:550 bottom:355 conf: 95%
|
| 84 |
-
..
|
| 85 |
-
Processing image: thutho_000128.jpg
|
| 86 |
-
class: cow left:24 top:32 right:249 bottom:168 conf: 93%
|
| 87 |
-
Saved res to cow_yolov5_res
|
| 88 |
|
| 89 |
```
|
| 90 |
|
| 91 |
Output image sample:
|
| 92 |
-

|
| 57 |
|
| 58 |
Input image sample:
|
| 59 |
+

|
| 60 |
|
| 61 |
run
|
| 62 |
```bash
|
|
|
|
|
|
|
| 63 |
python3 axmodel_infer_yolov5.py
|
| 64 |
```
|
| 65 |
|
| 66 |
```bash
|
| 67 |
+
root@ax650:~/cow-axera# python3 axmodel_infer_cow_yolov5.py
|
| 68 |
[INFO] Available providers: ['AxEngineExecutionProvider', 'AXCLRTExecutionProvider']
|
| 69 |
[INFO] Using provider: AxEngineExecutionProvider
|
| 70 |
[INFO] Chip type: ChipType.MC50
|
|
|
|
| 72 |
[INFO] Engine version: 2.12.0s
|
| 73 |
[INFO] Model type: 2 (triple core)
|
| 74 |
[INFO] Compiler version: 6.0 6965315a
|
|
|
|
|
|
|
|
|
|
| 75 |
class: cow left:356 top:79 right:464 bottom:119 conf: 76%
|
| 76 |
class: cow left:57 top:109 right:322 bottom:284 conf: 94%
|
| 77 |
class: cow left:251 top:104 right:550 bottom:355 conf: 95%
|
| 78 |
+
Saved res to ./axmodel_res.jpg
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
```
|
| 81 |
|
| 82 |
Output image sample:
|
| 83 |
+

|
axmodel_infer_cow_yolo26.py
DELETED
|
@@ -1,543 +0,0 @@
|
|
| 1 |
-
import axengine as axe
|
| 2 |
-
import cv2
|
| 3 |
-
import numpy as np
|
| 4 |
-
import time
|
| 5 |
-
import glob
|
| 6 |
-
import os
|
| 7 |
-
|
| 8 |
-
names = [
|
| 9 |
-
"Cow"
|
| 10 |
-
]
|
| 11 |
-
|
| 12 |
-
def non_max_suppression(
|
| 13 |
-
prediction,
|
| 14 |
-
conf_thres: float = 0.25,
|
| 15 |
-
iou_thres: float = 0.45,
|
| 16 |
-
classes=None,
|
| 17 |
-
agnostic: bool = False,
|
| 18 |
-
multi_label: bool = False,
|
| 19 |
-
labels=(),
|
| 20 |
-
max_det: int = 300,
|
| 21 |
-
nc: int = 0, # number of classes (optional)
|
| 22 |
-
max_time_img: float = 0.05,
|
| 23 |
-
max_nms: int = 30000,
|
| 24 |
-
max_wh: int = 7680,
|
| 25 |
-
rotated: bool = False,
|
| 26 |
-
end2end: bool = False,
|
| 27 |
-
return_idxs: bool = False,
|
| 28 |
-
):
|
| 29 |
-
"""Perform non-maximum suppression (NMS) on prediction results using NumPy only."""
|
| 30 |
-
# Checks
|
| 31 |
-
assert 0 <= conf_thres <= 1, f"Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0"
|
| 32 |
-
assert 0 <= iou_thres <= 1, f"Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0"
|
| 33 |
-
if isinstance(prediction, (list, tuple)):
|
| 34 |
-
prediction = prediction[0]
|
| 35 |
-
|
| 36 |
-
# Convert to numpy if needed
|
| 37 |
-
if not isinstance(prediction, np.ndarray):
|
| 38 |
-
prediction = np.asarray(prediction)
|
| 39 |
-
|
| 40 |
-
if classes is not None:
|
| 41 |
-
classes = np.asarray(classes)
|
| 42 |
-
if prediction.shape[-1] == 6 or end2end: # end-to-end model (BNC, i.e. 1,300,6)
|
| 43 |
-
output = []
|
| 44 |
-
for pred in prediction:
|
| 45 |
-
mask = pred[:, 4] > conf_thres
|
| 46 |
-
filtered = pred[mask][:max_det]
|
| 47 |
-
if classes is not None:
|
| 48 |
-
class_mask = np.any(filtered[:, 5:6] == classes, axis=1)
|
| 49 |
-
filtered = filtered[class_mask]
|
| 50 |
-
output.append(filtered)
|
| 51 |
-
return output
|
| 52 |
-
|
| 53 |
-
bs = prediction.shape[0] # batch size
|
| 54 |
-
nc = nc or (prediction.shape[1] - 4) # number of classes
|
| 55 |
-
extra = prediction.shape[1] - nc - 4 # number of extra info
|
| 56 |
-
mi = 4 + nc # mask start index
|
| 57 |
-
xc = np.max(prediction[:, 4:mi], axis=1) > conf_thres # candidates
|
| 58 |
-
|
| 59 |
-
# Create index arrays
|
| 60 |
-
xinds = np.arange(prediction.shape[-1], dtype=np.int32)
|
| 61 |
-
xinds_expanded = np.tile(xinds[np.newaxis, :, np.newaxis], (bs, 1, 1))
|
| 62 |
-
|
| 63 |
-
time_limit = 2.0 + max_time_img * bs
|
| 64 |
-
multi_label &= nc > 1
|
| 65 |
-
|
| 66 |
-
prediction = np.transpose(prediction, (0, 2, 1)) # shape(1,6300,84)
|
| 67 |
-
if not rotated:
|
| 68 |
-
prediction[..., :4] = xywh2xyxy(prediction[..., :4]) # xywh to xyxy
|
| 69 |
-
|
| 70 |
-
t = time.time()
|
| 71 |
-
output = []
|
| 72 |
-
keepi = []
|
| 73 |
-
|
| 74 |
-
for xi in range(bs):
|
| 75 |
-
x = prediction[xi]
|
| 76 |
-
xk = xinds_expanded[xi]
|
| 77 |
-
|
| 78 |
-
# Apply confidence threshold
|
| 79 |
-
filt = xc[xi]
|
| 80 |
-
x = x[filt]
|
| 81 |
-
xk_filtered = xk[filt]
|
| 82 |
-
|
| 83 |
-
if x.shape[0] == 0:
|
| 84 |
-
output.append(np.zeros((0, 6 + extra), dtype=np.float32))
|
| 85 |
-
keepi.append(np.zeros((0, 1), dtype=np.int32))
|
| 86 |
-
continue
|
| 87 |
-
|
| 88 |
-
# Split boxes and classes
|
| 89 |
-
box = x[:, :4]
|
| 90 |
-
cls = x[:, 4:4+nc]
|
| 91 |
-
mask = x[:, 4+nc:] if extra > 0 else np.empty((x.shape[0], 0))
|
| 92 |
-
|
| 93 |
-
if multi_label:
|
| 94 |
-
i, j = np.where(cls > conf_thres)
|
| 95 |
-
selected_box = box[i]
|
| 96 |
-
selected_conf = cls[i, j:j+1]
|
| 97 |
-
selected_j = j[:, np.newaxis]
|
| 98 |
-
selected_mask = mask[i]
|
| 99 |
-
x = np.concatenate([selected_box, selected_conf, selected_j.astype(np.float32), selected_mask], axis=1)
|
| 100 |
-
xk_filtered = xk_filtered[i]
|
| 101 |
-
else:
|
| 102 |
-
conf = np.max(cls, axis=1, keepdims=True)
|
| 103 |
-
j = np.argmax(cls, axis=1, keepdims=True)
|
| 104 |
-
filt = conf[:, 0] > conf_thres
|
| 105 |
-
x = np.concatenate([box, conf, j.astype(np.float32), mask], axis=1)[filt]
|
| 106 |
-
xk_filtered = xk_filtered[filt]
|
| 107 |
-
|
| 108 |
-
# Filter by class
|
| 109 |
-
if classes is not None:
|
| 110 |
-
class_mask = np.any(x[:, 5:6] == classes, axis=1)
|
| 111 |
-
x = x[class_mask]
|
| 112 |
-
xk_filtered = xk_filtered[class_mask]
|
| 113 |
-
|
| 114 |
-
n = x.shape[0]
|
| 115 |
-
if n == 0:
|
| 116 |
-
output.append(np.zeros((0, 6 + extra), dtype=np.float32))
|
| 117 |
-
keepi.append(np.zeros((0, 1), dtype=np.int32))
|
| 118 |
-
continue
|
| 119 |
-
|
| 120 |
-
if n > max_nms:
|
| 121 |
-
sorted_idx = np.argsort(-x[:, 4])[:max_nms]
|
| 122 |
-
x = x[sorted_idx]
|
| 123 |
-
xk_filtered = xk_filtered[sorted_idx]
|
| 124 |
-
|
| 125 |
-
# NMS
|
| 126 |
-
c = x[:, 5:6] * (0 if agnostic else max_wh)
|
| 127 |
-
scores = x[:, 4]
|
| 128 |
-
|
| 129 |
-
if not rotated:
|
| 130 |
-
boxes = x[:, :4] + c
|
| 131 |
-
i = numpy_nms(boxes, scores, iou_thres)
|
| 132 |
-
else:
|
| 133 |
-
boxes = np.concatenate([x[:, :2] + c, x[:, 2:4], x[:, -1:]], axis=-1)
|
| 134 |
-
i = numpy_nms(boxes[:, :4], scores, iou_thres) # Simplified for rotated boxes
|
| 135 |
-
|
| 136 |
-
i = i[:max_det]
|
| 137 |
-
|
| 138 |
-
output.append(x[i])
|
| 139 |
-
keepi.append(xk_filtered[i:i].reshape(-1, 1))
|
| 140 |
-
|
| 141 |
-
if (time.time() - t) > time_limit:
|
| 142 |
-
print(f"NMS time limit {time_limit:.3f}s exceeded")
|
| 143 |
-
break
|
| 144 |
-
|
| 145 |
-
return (output, keepi) if return_idxs else output
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
def numpy_nms(boxes, scores, iou_threshold):
|
| 149 |
-
"""Pure NumPy NMS implementation.
|
| 150 |
-
|
| 151 |
-
Args:
|
| 152 |
-
boxes: array of shape (N, 4) in format [x1, y1, x2, y2]
|
| 153 |
-
scores: array of shape (N,)
|
| 154 |
-
iou_threshold: NMS threshold
|
| 155 |
-
|
| 156 |
-
Returns:
|
| 157 |
-
indices of boxes to keep
|
| 158 |
-
"""
|
| 159 |
-
if len(boxes) == 0:
|
| 160 |
-
return np.array([], dtype=np.int32)
|
| 161 |
-
|
| 162 |
-
# Get coordinates
|
| 163 |
-
x1 = boxes[:, 0]
|
| 164 |
-
y1 = boxes[:, 1]
|
| 165 |
-
x2 = boxes[:, 2]
|
| 166 |
-
y2 = boxes[:, 3]
|
| 167 |
-
|
| 168 |
-
# Calculate areas
|
| 169 |
-
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
|
| 170 |
-
|
| 171 |
-
# Sort by score descending
|
| 172 |
-
order = np.argsort(-scores)
|
| 173 |
-
|
| 174 |
-
keep = []
|
| 175 |
-
while len(order) > 0:
|
| 176 |
-
i = order[0]
|
| 177 |
-
keep.append(i)
|
| 178 |
-
|
| 179 |
-
if len(order) == 1:
|
| 180 |
-
break
|
| 181 |
-
|
| 182 |
-
# Calculate intersection with all remaining boxes
|
| 183 |
-
xx1 = np.maximum(x1[i], x1[order[1:]])
|
| 184 |
-
yy1 = np.maximum(y1[i], y1[order[1:]])
|
| 185 |
-
xx2 = np.minimum(x2[i], x2[order[1:]])
|
| 186 |
-
yy2 = np.minimum(y2[i], y2[order[1:]])
|
| 187 |
-
|
| 188 |
-
# Calculate width and height
|
| 189 |
-
w = np.maximum(0, xx2 - xx1 + 1)
|
| 190 |
-
h = np.maximum(0, yy2 - yy1 + 1)
|
| 191 |
-
|
| 192 |
-
# Calculate intersection area
|
| 193 |
-
inter = w * h
|
| 194 |
-
|
| 195 |
-
# Calculate union area
|
| 196 |
-
union = areas[i] + areas[order[1:]] - inter
|
| 197 |
-
|
| 198 |
-
# Calculate IoU
|
| 199 |
-
iou = inter / union
|
| 200 |
-
|
| 201 |
-
# Keep boxes with IoU below threshold
|
| 202 |
-
inds = np.where(iou <= iou_threshold)[0]
|
| 203 |
-
order = order[inds + 1]
|
| 204 |
-
|
| 205 |
-
return np.array(keep, dtype=np.int32)
|
| 206 |
-
|
| 207 |
-
def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
|
| 208 |
-
|
| 209 |
-
shape = im.shape[:2]
|
| 210 |
-
if isinstance(new_shape, int):
|
| 211 |
-
new_shape = (new_shape, new_shape)
|
| 212 |
-
|
| 213 |
-
r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
|
| 214 |
-
if not scaleup:
|
| 215 |
-
r = min(r, 1.0)
|
| 216 |
-
|
| 217 |
-
ratio = r, r
|
| 218 |
-
new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
|
| 219 |
-
dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]
|
| 220 |
-
if auto:
|
| 221 |
-
dw, dh = np.mod(dw, stride), np.mod(dh, stride)
|
| 222 |
-
elif scaleFill:
|
| 223 |
-
dw, dh = 0.0, 0.0
|
| 224 |
-
new_unpad = (new_shape[1], new_shape[0])
|
| 225 |
-
ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]
|
| 226 |
-
|
| 227 |
-
dw /= 2
|
| 228 |
-
dh /= 2
|
| 229 |
-
|
| 230 |
-
if shape[::-1] != new_unpad:
|
| 231 |
-
im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
|
| 232 |
-
top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
|
| 233 |
-
left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
|
| 234 |
-
im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)
|
| 235 |
-
return im, ratio, (dw, dh)
|
| 236 |
-
|
| 237 |
-
def data_process_cv2(frame, input_shape):
|
| 238 |
-
im0 = cv2.imread(frame)
|
| 239 |
-
img = letterbox(im0, input_shape, auto=False, stride=32)[0]
|
| 240 |
-
org_data = img.copy()
|
| 241 |
-
img = np.ascontiguousarray(img)
|
| 242 |
-
img = np.asarray(img, dtype=np.uint8)
|
| 243 |
-
img = np.expand_dims(img, 0)
|
| 244 |
-
return img, im0, org_data
|
| 245 |
-
|
| 246 |
-
# Define xywh2xyxy function for converting bounding box format
|
| 247 |
-
def xywh2xyxy(x):
|
| 248 |
-
y = x.copy()
|
| 249 |
-
y[:, 0] = x[:, 0] - x[:, 2] / 2
|
| 250 |
-
y[:, 1] = x[:, 1] - x[:, 3] / 2
|
| 251 |
-
y[:, 2] = x[:, 0] + x[:, 2] / 2
|
| 252 |
-
y[:, 3] = x[:, 1] + x[:, 3] / 2
|
| 253 |
-
return y
|
| 254 |
-
|
| 255 |
-
def xyxy2xywh(x):
|
| 256 |
-
# Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
|
| 257 |
-
y = np.copy(x)
|
| 258 |
-
y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
|
| 259 |
-
y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
|
| 260 |
-
y[:, 2] = x[:, 2] - x[:, 0] # width
|
| 261 |
-
y[:, 3] = x[:, 3] - x[:, 1] # height
|
| 262 |
-
return y
|
| 263 |
-
|
| 264 |
-
def post_process_yolo(det, im, im0, gn, save_path, img_name):
|
| 265 |
-
detections = []
|
| 266 |
-
if len(det):
|
| 267 |
-
det[:, :4] = scale_boxes(im.shape[:2], det[:, :4], im0.shape).round()
|
| 268 |
-
colors = Colors()
|
| 269 |
-
for *xyxy, conf, cls in reversed(det):
|
| 270 |
-
print("class:",int(cls), "left:%.0f" % xyxy[0],"top:%.0f" % xyxy[1],"right:%.0f" % xyxy[2],"bottom:%.0f" % xyxy[3], "conf:",'{:.0f}%'.format(float(conf)*100))
|
| 271 |
-
int_coords = [int(tensor.item()) for tensor in xyxy]
|
| 272 |
-
detections.append(int_coords)
|
| 273 |
-
c = int(cls)
|
| 274 |
-
label = names[c]
|
| 275 |
-
res_img = plot_one_box(xyxy, im0, label=f'{label}:{conf:.2f}', color=colors(c, True), line_thickness=4)
|
| 276 |
-
cv2.imwrite(f'{save_path}/{img_name}.jpg',res_img)
|
| 277 |
-
# xywh = (xyxy2xywh(np.array(xyxy,dtype=np.float32).reshape(1, 4)) / gn).reshape(-1).tolist() # normalized xywh
|
| 278 |
-
# line = (cls, *xywh) # label format
|
| 279 |
-
# with open(f'{save_path}/{img_name}.txt', 'a') as f:
|
| 280 |
-
# f.write(('%g ' * len(line)).rstrip() % line + '\n')
|
| 281 |
-
return detections
|
| 282 |
-
|
| 283 |
-
def scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None):
|
| 284 |
-
if ratio_pad is None:
|
| 285 |
-
gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])
|
| 286 |
-
pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2
|
| 287 |
-
else:
|
| 288 |
-
gain = ratio_pad[0][0]
|
| 289 |
-
pad = ratio_pad[1]
|
| 290 |
-
|
| 291 |
-
boxes[..., [0, 2]] -= pad[0]
|
| 292 |
-
boxes[..., [1, 3]] -= pad[1]
|
| 293 |
-
boxes[..., :4] /= gain
|
| 294 |
-
clip_boxes(boxes, img0_shape)
|
| 295 |
-
return boxes
|
| 296 |
-
|
| 297 |
-
def clip_boxes(boxes, shape):
|
| 298 |
-
boxes[..., [0, 2]] = boxes[..., [0, 2]].clip(0, shape[1])
|
| 299 |
-
boxes[..., [1, 3]] = boxes[..., [1, 3]].clip(0, shape[0])
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
class Colors:
|
| 303 |
-
# Ultralytics color palette https://ultralytics.com/
|
| 304 |
-
def __init__(self):
|
| 305 |
-
"""
|
| 306 |
-
Initializes the Colors class with a palette derived from Ultralytics color scheme, converting hex codes to RGB.
|
| 307 |
-
Colors derived from `hex = matplotlib.colors.TABLEAU_COLORS.values()`.
|
| 308 |
-
"""
|
| 309 |
-
hexs = (
|
| 310 |
-
"FF3838",
|
| 311 |
-
"FF9D97",
|
| 312 |
-
"FF701F",
|
| 313 |
-
"FFB21D",
|
| 314 |
-
"CFD231",
|
| 315 |
-
"48F90A",
|
| 316 |
-
"92CC17",
|
| 317 |
-
"3DDB86",
|
| 318 |
-
"1A9334",
|
| 319 |
-
"00D4BB",
|
| 320 |
-
"2C99A8",
|
| 321 |
-
"00C2FF",
|
| 322 |
-
"344593",
|
| 323 |
-
"6473FF",
|
| 324 |
-
"0018EC",
|
| 325 |
-
"8438FF",
|
| 326 |
-
"520085",
|
| 327 |
-
"CB38FF",
|
| 328 |
-
"FF95C8",
|
| 329 |
-
"FF37C7",
|
| 330 |
-
)
|
| 331 |
-
self.palette = [self.hex2rgb(f"#{c}") for c in hexs]
|
| 332 |
-
self.n = len(self.palette)
|
| 333 |
-
|
| 334 |
-
def __call__(self, i, bgr=False):
|
| 335 |
-
"""Returns color from palette by index `i`, in BGR format if `bgr=True`, else RGB; `i` is an integer index."""
|
| 336 |
-
c = self.palette[int(i) % self.n]
|
| 337 |
-
return (c[2], c[1], c[0]) if bgr else c
|
| 338 |
-
|
| 339 |
-
@staticmethod
|
| 340 |
-
def hex2rgb(h):
|
| 341 |
-
"""Converts hex color codes to RGB values (i.e. default PIL order)."""
|
| 342 |
-
return tuple(int(h[1 + i: 1 + i + 2], 16) for i in (0, 2, 4))
|
| 343 |
-
|
| 344 |
-
def plot_one_box(x, im, color=None, label=None, line_thickness=3, steps=2, orig_shape=None):
|
| 345 |
-
# Ensure image is contiguous
|
| 346 |
-
if not im.flags['C_CONTIGUOUS']:
|
| 347 |
-
im = np.ascontiguousarray(im)
|
| 348 |
-
|
| 349 |
-
tl = line_thickness or round(0.002 * (im.shape[0] + im.shape[1]) / 2) + 1
|
| 350 |
-
c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
|
| 351 |
-
cv2.rectangle(im, c1, c2, color, thickness=tl*1//3, lineType=cv2.LINE_AA)
|
| 352 |
-
if label:
|
| 353 |
-
if len(label.split(':')) > 1:
|
| 354 |
-
tf = max(tl - 1, 1)
|
| 355 |
-
t_size = cv2.getTextSize(label, 0, fontScale=tl / 6, thickness=tf)[0]
|
| 356 |
-
c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
|
| 357 |
-
cv2.rectangle(im, c1, c2, color, -1, cv2.LINE_AA)
|
| 358 |
-
cv2.putText(im, label, (c1[0], c1[1] - 2), 0, tl / 6, [225, 255, 255], thickness=tf//2, lineType=cv2.LINE_AA)
|
| 359 |
-
return im
|
| 360 |
-
|
| 361 |
-
def model_load(model):
|
| 362 |
-
providers = ['AxEngineExecutionProvider']
|
| 363 |
-
session = axe.InferenceSession(model, providers=providers)
|
| 364 |
-
input_name = session.get_inputs()[0].name
|
| 365 |
-
output_names = [ x.name for x in session.get_outputs()]
|
| 366 |
-
return session, output_names
|
| 367 |
-
|
| 368 |
-
def make_anchors(feats, strides, grid_cell_offset=0.5):
|
| 369 |
-
"""Generate anchors from features."""
|
| 370 |
-
anchor_points, stride_tensor = [], []
|
| 371 |
-
assert feats is not None
|
| 372 |
-
dtype = feats[0].dtype
|
| 373 |
-
for i, stride in enumerate(strides):
|
| 374 |
-
h, w = feats[i].shape[2:] if isinstance(feats, list) else (int(feats[i][0]), int(feats[i][1]))
|
| 375 |
-
sx = np.arange(w, dtype=dtype) + grid_cell_offset # shift x
|
| 376 |
-
sy = np.arange(h, dtype=dtype) + grid_cell_offset # shift y
|
| 377 |
-
sy, sx = np.meshgrid(sy, sx, indexing='ij')
|
| 378 |
-
anchor_points.append(np.stack((sx, sy), axis=-1).reshape(-1, 2))
|
| 379 |
-
stride_tensor.append(np.full((h * w, 1), stride, dtype=dtype))
|
| 380 |
-
return np.concatenate(anchor_points), np.concatenate(stride_tensor)
|
| 381 |
-
|
| 382 |
-
def dist2bbox(distance, anchor_points, xywh=True, dim=-1):
|
| 383 |
-
"""Transform distance(ltrb) to box(xywh or xyxy)."""
|
| 384 |
-
lt, rb = np.split(distance, 2, axis=dim)
|
| 385 |
-
x1y1 = anchor_points - lt
|
| 386 |
-
x2y2 = anchor_points + rb
|
| 387 |
-
if xywh:
|
| 388 |
-
c_xy = (x1y1 + x2y2) / 2
|
| 389 |
-
wh = x2y2 - x1y1
|
| 390 |
-
return np.concatenate((c_xy, wh), axis=dim) # xywh bbox
|
| 391 |
-
return np.concatenate((x1y1, x2y2), axis=dim) # xyxy bbox
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
class DFL:
|
| 395 |
-
"""
|
| 396 |
-
NumPy implementation of Distribution Focal Loss (DFL) integral module.
|
| 397 |
-
Original paper: Generalized Focal Loss (IEEE TPAMI 2023)
|
| 398 |
-
"""
|
| 399 |
-
|
| 400 |
-
def __init__(self, c1=16):
|
| 401 |
-
"""Initialize with given number of distribution channels"""
|
| 402 |
-
self.c1 = c1
|
| 403 |
-
# 初始化权重矩阵(等效于原conv层的固定权重)
|
| 404 |
-
self.weights = np.arange(c1, dtype=np.float32).reshape(1, c1, 1, 1)
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
def __call__(self, x):
|
| 408 |
-
"""
|
| 409 |
-
前向传播逻辑
|
| 410 |
-
参数:
|
| 411 |
-
x: 输入张量,形状为(batch, channels, anchors)
|
| 412 |
-
返回:
|
| 413 |
-
处理后的张量,形状为(batch, 4, anchors)
|
| 414 |
-
"""
|
| 415 |
-
b, c, a = x.shape
|
| 416 |
-
|
| 417 |
-
# 等效于原view->transpose->softmax操作
|
| 418 |
-
x_reshaped = x.reshape(b, 4, self.c1, a)
|
| 419 |
-
x_transposed = np.transpose(x_reshaped, (0, 2, 1, 3))
|
| 420 |
-
x_softmax = np.exp(x_transposed) / np.sum(np.exp(x_transposed), axis=1, keepdims=True)
|
| 421 |
-
|
| 422 |
-
# 等效卷积操作(通过张量乘积实现)
|
| 423 |
-
conv_result = np.sum(self.weights * x_softmax, axis=1)
|
| 424 |
-
|
| 425 |
-
return conv_result.reshape(b, 4, a)
|
| 426 |
-
|
| 427 |
-
class YOLO26Detector:
|
| 428 |
-
def __init__(self, model_path, imgsz=[640,640]):
|
| 429 |
-
self.model_path = model_path
|
| 430 |
-
self.session, self.output_names = model_load(self.model_path)
|
| 431 |
-
self.imgsz = imgsz
|
| 432 |
-
self.stride = [16.,32.]
|
| 433 |
-
self.reg_max = 1
|
| 434 |
-
self.nc = len(names)
|
| 435 |
-
self.nl = len(self.stride)
|
| 436 |
-
self.dfl = DFL(self.reg_max)
|
| 437 |
-
self.max_det = 300
|
| 438 |
-
|
| 439 |
-
def postprocess(self, preds: np.ndarray) -> np.ndarray:
|
| 440 |
-
"""Post-processes YOLO model predictions using NumPy.
|
| 441 |
-
|
| 442 |
-
Args:
|
| 443 |
-
preds (np.ndarray): Raw predictions with shape (batch_size, num_anchors, 4 + nc)
|
| 444 |
-
|
| 445 |
-
Returns:
|
| 446 |
-
(np.ndarray): Processed predictions with shape (batch_size, min(max_det, num_anchors), 6)
|
| 447 |
-
"""
|
| 448 |
-
boxes = preds[:, :, :4]
|
| 449 |
-
scores = preds[:, :, 4:]
|
| 450 |
-
scores_topk, conf, idx = self.get_topk_index(scores, self.max_det)
|
| 451 |
-
|
| 452 |
-
# Gather corresponding boxes
|
| 453 |
-
boxes_selected = boxes[np.arange(boxes.shape[0])[:, None], idx[:, :, 0].astype(int)]
|
| 454 |
-
|
| 455 |
-
return np.concatenate([boxes_selected, scores_topk, conf], axis=-1)
|
| 456 |
-
|
| 457 |
-
def get_topk_index(self, scores: np.ndarray, max_det: int) -> tuple:
|
| 458 |
-
"""Get top-k indices from scores using NumPy.
|
| 459 |
-
|
| 460 |
-
Args:
|
| 461 |
-
scores (np.ndarray): Scores array with shape (batch_size, num_anchors, num_classes).
|
| 462 |
-
max_det (int): Maximum detections per image.
|
| 463 |
-
|
| 464 |
-
Returns:
|
| 465 |
-
(tuple): Top scores, class indices, and filtered indices.
|
| 466 |
-
"""
|
| 467 |
-
batch_size, anchors, nc = scores.shape
|
| 468 |
-
k = max_det
|
| 469 |
-
|
| 470 |
-
# Get max class score for each anchor: shape (batch_size, anchors)
|
| 471 |
-
max_scores = np.max(scores, axis=2)
|
| 472 |
-
|
| 473 |
-
# Get top-k indices for each batch
|
| 474 |
-
# Using argsort for each batch separately
|
| 475 |
-
output_scores = np.zeros((batch_size, k, 1), dtype=np.float32)
|
| 476 |
-
output_classes = np.zeros((batch_size, k, 1), dtype=np.float32)
|
| 477 |
-
output_indices = np.zeros((batch_size, k, 1), dtype=np.int32)
|
| 478 |
-
|
| 479 |
-
for b in range(batch_size):
|
| 480 |
-
# Get topk indices from max_scores
|
| 481 |
-
topk_indices = np.argsort(-max_scores[b])[:k]
|
| 482 |
-
|
| 483 |
-
# Pad if needed
|
| 484 |
-
if len(topk_indices) < k:
|
| 485 |
-
topk_indices = np.pad(topk_indices, (0, k - len(topk_indices)), mode='constant')
|
| 486 |
-
|
| 487 |
-
# Get scores for topk indices
|
| 488 |
-
topk_scores_array = scores[b, topk_indices] # shape (k, nc)
|
| 489 |
-
|
| 490 |
-
# Get class with max score
|
| 491 |
-
class_indices = np.argmax(topk_scores_array, axis=1)
|
| 492 |
-
topk_values = np.max(topk_scores_array, axis=1)
|
| 493 |
-
|
| 494 |
-
output_scores[b, :, 0] = topk_values
|
| 495 |
-
output_classes[b, :, 0] = class_indices
|
| 496 |
-
output_indices[b, :, 0] = topk_indices
|
| 497 |
-
|
| 498 |
-
return output_scores, output_classes, output_indices
|
| 499 |
-
|
| 500 |
-
def detect_objects(self, image, save_path):
|
| 501 |
-
im, im0, org_data = data_process_cv2(image, self.imgsz)
|
| 502 |
-
img_name = os.path.basename(image).split('.')[0]
|
| 503 |
-
x = self.session.run(self.output_names, {self.session.get_inputs()[0].name: im})
|
| 504 |
-
x = [np.transpose(x[i],(0,3,1,2)) for i in range(self.nl)] #to nchw
|
| 505 |
-
anchors, strides = (np.transpose(x_arr, (1, 0)) for x_arr in make_anchors(x, self.stride, 0.5))
|
| 506 |
-
box = [x[i][:, :self.reg_max * 4, :] for i in range(self.nl)]
|
| 507 |
-
cls = [x[i][:, self.reg_max * 4:, :] for i in range(self.nl)]
|
| 508 |
-
boxes = np.concatenate([box[i].reshape(1, 4 * self.reg_max, -1) for i in range(self.nl)], axis=-1)
|
| 509 |
-
scores = np.concatenate([cls[i].reshape(1, self.nc, -1) for i in range(self.nl)], axis=-1)
|
| 510 |
-
if self.reg_max > 1:
|
| 511 |
-
dbox = dist2bbox(self.dfl(boxes), np.expand_dims(anchors, axis=0), xywh=False, dim=1) * strides
|
| 512 |
-
else: # 弃用DFL
|
| 513 |
-
dbox = dist2bbox(boxes, np.expand_dims(anchors, axis=0), xywh=False, dim=1) * strides
|
| 514 |
-
y = np.concatenate((dbox, 1/(1 + np.exp(-scores))), axis=1)
|
| 515 |
-
y = y.transpose([0, 2, 1])
|
| 516 |
-
pred = self.postprocess(y) # Now returns numpy array directly
|
| 517 |
-
pred = non_max_suppression(
|
| 518 |
-
pred,
|
| 519 |
-
0.3,
|
| 520 |
-
0.45,
|
| 521 |
-
None,
|
| 522 |
-
False,
|
| 523 |
-
max_det=300,
|
| 524 |
-
nc=0,
|
| 525 |
-
end2end=True,
|
| 526 |
-
rotated=False,
|
| 527 |
-
return_idxs=None,
|
| 528 |
-
)
|
| 529 |
-
gn = np.array(org_data.shape)[[1, 0, 1, 0]].astype(np.float32)
|
| 530 |
-
res = post_process_yolo(pred[0], org_data, im0, gn, save_path, img_name)
|
| 531 |
-
return res, im0
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
if __name__ == '__main__':
|
| 535 |
-
|
| 536 |
-
detector = YOLO26Detector(model_path='./cow_ax650_npu3_26.axmodel',imgsz=[640,640])
|
| 537 |
-
img_path = './cow_pic'
|
| 538 |
-
det_path='./cow_yolo26_res'
|
| 539 |
-
os.makedirs(det_path, exist_ok=True)
|
| 540 |
-
imgs = glob.glob(f"{img_path}/*.jpg")
|
| 541 |
-
for idx,img in enumerate(imgs):
|
| 542 |
-
print(f"{idx}/{len(imgs)}: {img}")
|
| 543 |
-
det_result, res_img = detector.detect_objects(img,det_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
axmodel_infer_cow_yolov5.py
CHANGED
|
@@ -253,63 +253,60 @@ def sigmoid(x):
|
|
| 253 |
return 1 / (1 + np.exp(-x))
|
| 254 |
|
| 255 |
if __name__ == "__main__":
|
| 256 |
-
model_path = "./
|
| 257 |
-
|
| 258 |
-
save_path = '
|
| 259 |
-
os.makedirs(save_path, exist_ok=True)
|
| 260 |
imgsz = (320,480)
|
| 261 |
names=['cow']
|
| 262 |
|
| 263 |
session = axe.InferenceSession(model_path, None)
|
| 264 |
input_name = session.get_inputs()[0].name
|
| 265 |
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
# preds = model_inference(model_path, img)
|
| 275 |
-
preds = session.run(None, {input_name: img})
|
| 276 |
|
| 277 |
-
|
| 278 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
anchors[i] /= np.array(stride[i])
|
| 291 |
-
grid, anchor_grid = _make_grid(anchors,nx, ny, i)
|
| 292 |
-
pred = sigmoid(pred)
|
| 293 |
-
|
| 294 |
-
xy, wh, conf = pred[...,:2],pred[...,2:4],pred[...,4:]
|
| 295 |
-
xy = (xy * 2 + grid) * stride[i]
|
| 296 |
-
wh = (wh * 2) ** 2 * anchor_grid
|
| 297 |
-
y = np.concatenate((xy, wh, conf), 4)
|
| 298 |
-
z.append(y.reshape(bs, na * nx * ny, no))
|
| 299 |
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
print(f'Saved res to {save_path}')
|
|
|
|
| 253 |
return 1 / (1 + np.exp(-x))
|
| 254 |
|
| 255 |
if __name__ == "__main__":
|
| 256 |
+
model_path = "./cow_ax650_npu3.axmodel"
|
| 257 |
+
img_file = "./000000235857.jpg"
|
| 258 |
+
save_path = './axmodel_res.jpg'
|
|
|
|
| 259 |
imgsz = (320,480)
|
| 260 |
names=['cow']
|
| 261 |
|
| 262 |
session = axe.InferenceSession(model_path, None)
|
| 263 |
input_name = session.get_inputs()[0].name
|
| 264 |
|
| 265 |
+
im0 = cv2.imread(img_file)
|
| 266 |
+
img = letterbox(im0, imgsz, auto=False, stride=32)[0]
|
| 267 |
+
img = np.ascontiguousarray(img[:, :, ::-1].transpose(2, 0, 1))
|
| 268 |
+
img = np.asarray(img, dtype=np.uint8)
|
| 269 |
+
img = np.expand_dims(img, 0)
|
| 270 |
+
|
| 271 |
+
# preds = model_inference(model_path, img)
|
| 272 |
+
preds = session.run(None, {input_name: img})
|
|
|
|
|
|
|
| 273 |
|
| 274 |
+
anchors=[[19, 24, 47, 40, 60, 81],[104, 94, 163, 151, 334, 256]]
|
| 275 |
+
stride=[16,32]
|
| 276 |
+
|
| 277 |
+
na = len(anchors[0]) // 2
|
| 278 |
+
nl = len(anchors)
|
| 279 |
+
nc = len(names)
|
| 280 |
+
no = len(names) + 5
|
| 281 |
+
|
| 282 |
+
z = []
|
| 283 |
+
for i,pred in enumerate(preds):
|
| 284 |
+
bs, _, ny, nx = pred.shape
|
| 285 |
|
| 286 |
+
pred = pred.reshape(bs, na, no, ny, nx).transpose(0, 1, 3, 4, 2)
|
| 287 |
+
anchors[i] /= np.array(stride[i])
|
| 288 |
+
grid, anchor_grid = _make_grid(anchors,nx, ny, i)
|
| 289 |
+
pred = sigmoid(pred)
|
| 290 |
|
| 291 |
+
xy, wh, conf = pred[...,:2],pred[...,2:4],pred[...,4:]
|
| 292 |
+
xy = (xy * 2 + grid) * stride[i]
|
| 293 |
+
wh = (wh * 2) ** 2 * anchor_grid
|
| 294 |
+
y = np.concatenate((xy, wh, conf), 4)
|
| 295 |
+
z.append(y.reshape(bs, na * nx * ny, no))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
+
preds=np.concatenate(z, 1)
|
| 298 |
+
|
| 299 |
+
conf_thres = 0.3
|
| 300 |
+
iou_thres = 0.45
|
| 301 |
+
preds = non_max_suppression(preds, conf_thres, iou_thres)
|
| 302 |
+
|
| 303 |
+
for i, det in enumerate(preds):
|
| 304 |
+
if len(det):
|
| 305 |
+
scale_coords(img.shape[2:], det[:, :4], im0.shape)
|
| 306 |
+
for det_index, (*xyxy, conf, cls) in enumerate(reversed(det[:, :6])):
|
| 307 |
+
print("class:",names[int(cls)], "left:%.0f" % xyxy[0],"top:%.0f" % xyxy[1],"right:%.0f" % xyxy[2],"bottom:%.0f" % xyxy[3], "conf:",'{:.0f}%'.format(float(conf)*100))
|
| 308 |
+
c = int(cls)
|
| 309 |
+
label = f'{names[c]} {conf:.2f}'
|
| 310 |
+
plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=2,steps=3, orig_shape=im0.shape[:2])
|
| 311 |
+
cv2.imwrite(f'{save_path}', im0)
|
| 312 |
print(f'Saved res to {save_path}')
|
cow_pic/002_005662.jpg → axmodel_res.jpg
RENAMED
|
File without changes
|
axmodel_res_sample.jpg
DELETED
Git LFS Details
|
cow_pic/002_000264.jpg
DELETED
Git LFS Details
|
cow_pic/002_003436.jpg
DELETED
Git LFS Details
|
cow_pic/002_006511.jpg
DELETED
Git LFS Details
|
cow_pic/002_007108.jpg
DELETED
Git LFS Details
|
cow_pic/002_007213.jpg
DELETED
Git LFS Details
|
cow_pic/003_000123.jpg
DELETED
Git LFS Details
|
cow_pic/003_000792.jpg
DELETED
Git LFS Details
|
cow_pic/003_001187.jpg
DELETED
Git LFS Details
|
cow_pic/004_000284.jpg
DELETED
Git LFS Details
|
cow_pic/004_001357.jpg
DELETED
Git LFS Details
|
cow_pic/004_004980.jpg
DELETED
Git LFS Details
|
cow_pic/004_005252.jpg
DELETED
Git LFS Details
|
cow_pic/004_006297.jpg
DELETED
Git LFS Details
|
cow_pic/004_007017.jpg
DELETED
Git LFS Details
|
cow_pic/004_007153.jpg
DELETED
Git LFS Details
|
cow_pic/005_000347.jpg
DELETED
Git LFS Details
|
cow_pic/005_000523.jpg
DELETED
Git LFS Details
|
cow_pic/006_000147.jpg
DELETED
Git LFS Details
|
cow_pic/006_000307.jpg
DELETED
Git LFS Details
|
cow_pic/006_001563.jpg
DELETED
Git LFS Details
|
cow_pic/006_003026.jpg
DELETED
Git LFS Details
|
cow_pic/006_006298.jpg
DELETED
Git LFS Details
|
cow_pic/007_001324.jpg
DELETED
Git LFS Details
|
cow_pic/007_001853.jpg
DELETED
Git LFS Details
|
cow_pic/Bargur_000127.jpg
DELETED
Git LFS Details
|
cow_pic/BeefCattleBehavior_000200.jpg
DELETED
Git LFS Details
|
cow_pic/COLO_YOLO_000786.jpg
DELETED
Git LFS Details
|
cow_pic/CattleWeightDetectSide_001235.jpg
DELETED
Git LFS Details
|
cow_pic/CattleWeightDetectSide_003239.jpg
DELETED
Git LFS Details
|
cow_pic/CowAndPeople642025_002794.jpg
DELETED
Git LFS Details
|
cow_pic/CowAndPeople642025_003949.jpg
DELETED
Git LFS Details
|
cow_pic/CowAndPeople642025_005457.jpg
DELETED
Git LFS Details
|
cow_pic/CowAndPeople642025_006911.jpg
DELETED
Git LFS Details
|
cow_pic/CowBreedClassification1_000829.jpg
DELETED
Git LFS Details
|
cow_pic/CowBreedClassificationDataset_000614.jpg
DELETED
Git LFS Details
|
cow_pic/CowLieStandWalk_003551.jpg
DELETED
Git LFS Details
|
cow_pic/CowsandBuffalo_000168.jpg
DELETED
Git LFS Details
|
cow_pic/CowsandBuffalo_001108.jpg
DELETED
Git LFS Details
|
cow_pic/Cowv3ivoc_000268.jpg
DELETED
Git LFS Details
|
cow_pic/Cowv3ivoc_000503.jpg
DELETED
Git LFS Details
|
cow_pic/Ladakhi_000105.jpg
DELETED
Git LFS Details
|
cow_pic/Mewati_000012.jpg
DELETED
Git LFS Details
|