HugoHE commited on
Commit
7258567
·
1 Parent(s): 972170f

Create new file

Browse files
Files changed (1) hide show
  1. inference.py +186 -0
inference.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import onnxruntime
4
+ from PIL import Image
5
+
6
+ class_names = [100, 120, 20, 30, 40, 15, 50, 60, 70, 80]
7
+ def preprocess(img, input_size, swap=(2, 0, 1)):
8
+ if len(img.shape) == 3:
9
+ padded_img = np.ones((input_size[0], input_size[1], 3), dtype=np.uint8) * 114
10
+ else:
11
+ padded_img = np.ones(input_size, dtype=np.uint8) * 114
12
+
13
+ r = min(input_size[0] / img.shape[0], input_size[1] / img.shape[1])
14
+ resized_img = cv2.resize(
15
+ img,
16
+ (int(img.shape[1] * r), int(img.shape[0] * r)),
17
+ interpolation=cv2.INTER_LINEAR,
18
+ ).astype(np.uint8)
19
+ padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img
20
+
21
+ padded_img = padded_img.transpose(swap)
22
+ padded_img = np.ascontiguousarray(padded_img, dtype=np.float32)
23
+ return padded_img, r
24
+
25
+ def nms(boxes, scores, nms_thr):
26
+ """Single class NMS implemented in Numpy."""
27
+ x1 = boxes[:, 0]
28
+ y1 = boxes[:, 1]
29
+ x2 = boxes[:, 2]
30
+ y2 = boxes[:, 3]
31
+
32
+ areas = (x2 - x1 + 1) * (y2 - y1 + 1)
33
+ order = scores.argsort()[::-1]
34
+
35
+ keep = []
36
+ while order.size > 0:
37
+ i = order[0]
38
+ keep.append(i)
39
+ xx1 = np.maximum(x1[i], x1[order[1:]])
40
+ yy1 = np.maximum(y1[i], y1[order[1:]])
41
+ xx2 = np.minimum(x2[i], x2[order[1:]])
42
+ yy2 = np.minimum(y2[i], y2[order[1:]])
43
+
44
+ w = np.maximum(0.0, xx2 - xx1 + 1)
45
+ h = np.maximum(0.0, yy2 - yy1 + 1)
46
+ inter = w * h
47
+ ovr = inter / (areas[i] + areas[order[1:]] - inter)
48
+
49
+ inds = np.where(ovr <= nms_thr)[0]
50
+ order = order[inds + 1]
51
+
52
+ return keep
53
+
54
+ def multiclass_nms(boxes, scores, nms_thr, score_thr, class_agnostic=True):
55
+ """Multiclass NMS implemented in Numpy"""
56
+ if class_agnostic:
57
+ nms_method = multiclass_nms_class_agnostic
58
+ else:
59
+ nms_method = multiclass_nms_class_aware
60
+ return nms_method(boxes, scores, nms_thr, score_thr)
61
+
62
+
63
+ def multiclass_nms_class_aware(boxes, scores, nms_thr, score_thr):
64
+ """Multiclass NMS implemented in Numpy. Class-aware version."""
65
+ final_dets = []
66
+ num_classes = scores.shape[1]
67
+ for cls_ind in range(num_classes):
68
+ cls_scores = scores[:, cls_ind]
69
+ valid_score_mask = cls_scores > score_thr
70
+ if valid_score_mask.sum() == 0:
71
+ continue
72
+ else:
73
+ valid_scores = cls_scores[valid_score_mask]
74
+ valid_boxes = boxes[valid_score_mask]
75
+ keep = nms(valid_boxes, valid_scores, nms_thr)
76
+ if len(keep) > 0:
77
+ cls_inds = np.ones((len(keep), 1)) * cls_ind
78
+ dets = np.concatenate(
79
+ [valid_boxes[keep], valid_scores[keep, None], cls_inds], 1
80
+ )
81
+ final_dets.append(dets)
82
+ if len(final_dets) == 0:
83
+ return None
84
+ return np.concatenate(final_dets, 0)
85
+
86
+
87
+ def multiclass_nms_class_agnostic(boxes, scores, nms_thr, score_thr):
88
+ """Multiclass NMS implemented in Numpy. Class-agnostic version."""
89
+ cls_inds = scores.argmax(1)
90
+ cls_scores = scores[np.arange(len(cls_inds)), cls_inds]
91
+
92
+ valid_score_mask = cls_scores > score_thr
93
+ if valid_score_mask.sum() == 0:
94
+ return None
95
+ valid_scores = cls_scores[valid_score_mask]
96
+ valid_boxes = boxes[valid_score_mask]
97
+ valid_cls_inds = cls_inds[valid_score_mask]
98
+ keep = nms(valid_boxes, valid_scores, nms_thr)
99
+ if keep:
100
+ dets = np.concatenate(
101
+ [valid_boxes[keep], valid_scores[keep, None], valid_cls_inds[keep, None]], 1
102
+ )
103
+ return dets
104
+
105
+ def demo_postprocess(outputs, img_size, p6=False):
106
+
107
+ grids = []
108
+ expanded_strides = []
109
+
110
+ if not p6:
111
+ strides = [8, 16, 32]
112
+ else:
113
+ strides = [8, 16, 32, 64]
114
+
115
+ hsizes = [img_size[0] // stride for stride in strides]
116
+ wsizes = [img_size[1] // stride for stride in strides]
117
+
118
+ for hsize, wsize, stride in zip(hsizes, wsizes, strides):
119
+ xv, yv = np.meshgrid(np.arange(wsize), np.arange(hsize))
120
+ grid = np.stack((xv, yv), 2).reshape(1, -1, 2)
121
+ grids.append(grid)
122
+ shape = grid.shape[:2]
123
+ expanded_strides.append(np.full((*shape, 1), stride))
124
+
125
+ grids = np.concatenate(grids, 1)
126
+ expanded_strides = np.concatenate(expanded_strides, 1)
127
+ outputs[..., :2] = (outputs[..., :2] + grids) * expanded_strides
128
+ outputs[..., 2:4] = np.exp(outputs[..., 2:4]) * expanded_strides
129
+
130
+ return outputs
131
+
132
+ def prediction(img):
133
+
134
+ img, ratio = preprocess(img, [640, 640])
135
+
136
+ session = onnxruntime.InferenceSession("yolox_s.onnx")
137
+
138
+ ort_inputs = {session.get_inputs()[0].name: img[None, :, :, :]}
139
+ output = session.run(None, ort_inputs)
140
+ predictions = demo_postprocess(output[0], [640, 640])[0]
141
+
142
+ boxes = predictions[:, :4]
143
+ scores = predictions[:, 4:5] * predictions[:, 5:]
144
+
145
+ boxes_xyxy = np.ones_like(boxes)
146
+ boxes_xyxy[:, 0] = boxes[:, 0] - boxes[:, 2]/2.
147
+ boxes_xyxy[:, 1] = boxes[:, 1] - boxes[:, 3]/2.
148
+ boxes_xyxy[:, 2] = boxes[:, 0] + boxes[:, 2]/2.
149
+ boxes_xyxy[:, 3] = boxes[:, 1] + boxes[:, 3]/2.
150
+ boxes_xyxy /= ratio
151
+ dets = multiclass_nms(boxes_xyxy, scores, nms_thr=0.45, score_thr=0.1)
152
+ if dets is not None:
153
+ boxes, cls_ids, score = dets[:, :4], dets[:, 4], dets[:, 5]
154
+ return boxes, cls_ids, score
155
+
156
+ def vis(img, boxes, scores, cls_ids, conf=0.5):
157
+ for i in range(len(boxes)):
158
+ box = boxes[i]
159
+ cls_id = int(cls_ids[i])
160
+ score = scores[i]
161
+ if score < conf:
162
+ continue
163
+ x0 = int(box[0])
164
+ y0 = int(box[1])
165
+ x1 = int(box[2])
166
+ y1 = int(box[3])
167
+
168
+ color = (0, 0, 255)
169
+ text = '{} km/h:{:.1f}%'.format(class_names[cls_id], score * 100)
170
+ txt_color = (255, 255, 255)
171
+ font = cv2.FONT_HERSHEY_DUPLEX
172
+
173
+ txt_size = cv2.getTextSize(text, font, 0.6, 1)[0]
174
+ cv2.rectangle(img, (x0, y0), (x1, y1), color, 2)
175
+
176
+ txt_bk_color = (0, 0, 255)
177
+ cv2.rectangle(
178
+ img,
179
+ (x0, y0 - 1),
180
+ (x0 + txt_size[0] + 1, y0 - int(1.5*txt_size[1])),
181
+ txt_bk_color,
182
+ -1
183
+ )
184
+ cv2.putText(img, text, (x0, y0-int(0.5*txt_size[1])), font, 0.6, txt_color, thickness=1)
185
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
186
+ return Image.fromarray(img)