Create utils.py
Browse files
utils.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
import onnxruntime as ort
|
| 4 |
+
|
| 5 |
+
def preprocess(image, size=(640, 640)):
|
| 6 |
+
h, w = image.shape[:2]
|
| 7 |
+
max_size = max(h, w)
|
| 8 |
+
scale_factor = size[0] / max_size
|
| 9 |
+
pad_h = (max_size - h) // 2
|
| 10 |
+
pad_w = (max_size - w) // 2
|
| 11 |
+
pad_image = np.zeros((max_size, max_size, 3), dtype=image.dtype)
|
| 12 |
+
pad_image[pad_h:h + pad_h, pad_w:w + pad_w] = image
|
| 13 |
+
image = cv2.resize(pad_image, size,
|
| 14 |
+
interpolation=cv2.INTER_LINEAR).astype('float32')
|
| 15 |
+
image /= 255.0
|
| 16 |
+
image = image[None]
|
| 17 |
+
return image, scale_factor, (pad_h, pad_w)
|
| 18 |
+
|
| 19 |
+
def inference(ort_session,
|
| 20 |
+
ori_image,
|
| 21 |
+
size=(640, 640),
|
| 22 |
+
**kwargs):
|
| 23 |
+
# normal export
|
| 24 |
+
# with NMS and postprocessing
|
| 25 |
+
h, w = ori_image.shape[:2]
|
| 26 |
+
image, scale_factor, pad_param = preprocess(ori_image[:, :, [2, 1, 0]],
|
| 27 |
+
size)
|
| 28 |
+
input_ort = ort.OrtValue.ortvalue_from_numpy(image.transpose((0, 3, 1, 2)))
|
| 29 |
+
results = ort_session.run(["num_dets", "labels", "scores", "boxes"],
|
| 30 |
+
{"images": input_ort})
|
| 31 |
+
num_dets, labels, scores, bboxes = results
|
| 32 |
+
num_dets = num_dets[0][0]
|
| 33 |
+
labels = labels[0, :num_dets]
|
| 34 |
+
scores = scores[0, :num_dets]
|
| 35 |
+
bboxes = bboxes[0, :num_dets]
|
| 36 |
+
|
| 37 |
+
bboxes -= np.array(
|
| 38 |
+
[pad_param[1], pad_param[0], pad_param[1], pad_param[0]])
|
| 39 |
+
bboxes /= scale_factor
|
| 40 |
+
bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, w)
|
| 41 |
+
bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, h)
|
| 42 |
+
bboxes = bboxes.round().astype('int')
|
| 43 |
+
|
| 44 |
+
return labels, scores, bboxes
|