Dolpheyn commited on
Commit
d239a7a
·
1 Parent(s): 7357a7b

Upload model.py

Browse files
Files changed (1) hide show
  1. model.py +153 -0
model.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+
4
+ class yolox():
5
+ def __init__(self, model, p6=False, confThreshold=0.5, nmsThreshold=0.5, objThreshold=0.5):
6
+ with open('coco.names', 'rt') as f:
7
+ self.class_names = f.read().rstrip('\n').split('\n')
8
+ self.net = cv2.dnn.readNet(model)
9
+ self.input_size = (640, 640)
10
+ self.mean = (0.485, 0.456, 0.406)
11
+ self.std = (0.229, 0.224, 0.225)
12
+ if not p6:
13
+ self.strides = [8, 16, 32]
14
+ else:
15
+ self.strides = [8, 16, 32, 64]
16
+ self.confThreshold = confThreshold
17
+ self.nmsThreshold = nmsThreshold
18
+ self.objThreshold = objThreshold
19
+ def preprocess(self, image):
20
+ if len(image.shape) == 3:
21
+ padded_img = np.ones((self.input_size[0], self.input_size[1], 3)) * 114.0
22
+ else:
23
+ padded_img = np.ones(self.input_size) * 114.0
24
+ img = np.array(image)
25
+ r = min(self.input_size[0] / img.shape[0], self.input_size[1] / img.shape[1])
26
+ resized_img = cv2.resize(
27
+ img, (int(img.shape[1] * r), int(img.shape[0] * r)), interpolation=cv2.INTER_LINEAR
28
+ ).astype(np.float32)
29
+ padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img
30
+ image = padded_img
31
+
32
+ image = image.astype(np.float32)
33
+ image = image[:, :, ::-1]
34
+ image /= 255.0
35
+ image -= self.mean
36
+ image /= self.std
37
+ return image, r
38
+
39
+ def demo_postprocess(self, outputs):
40
+ grids = []
41
+ expanded_strides = []
42
+ hsizes = [self.input_size[0] // stride for stride in self.strides]
43
+ wsizes = [self.input_size[1] // stride for stride in self.strides]
44
+
45
+ for hsize, wsize, stride in zip(hsizes, wsizes, self.strides):
46
+ xv, yv = np.meshgrid(np.arange(hsize), np.arange(wsize))
47
+ grid = np.stack((xv, yv), 2).reshape(1, -1, 2)
48
+ grids.append(grid)
49
+ shape = grid.shape[:2]
50
+ expanded_strides.append(np.full((*shape, 1), stride))
51
+
52
+ grids = np.concatenate(grids, 1)
53
+ expanded_strides = np.concatenate(expanded_strides, 1)
54
+ outputs[..., :2] = (outputs[..., :2] + grids) * expanded_strides
55
+ outputs[..., 2:4] = np.exp(outputs[..., 2:4]) * expanded_strides
56
+ return outputs
57
+
58
+ def nms(self, boxes, scores):
59
+ """Single class NMS implemented in Numpy."""
60
+ x1 = boxes[:, 0]
61
+ y1 = boxes[:, 1]
62
+ x2 = boxes[:, 2]
63
+ y2 = boxes[:, 3]
64
+
65
+ areas = (x2 - x1 + 1) * (y2 - y1 + 1)
66
+ order = scores.argsort()[::-1]
67
+
68
+ keep = []
69
+ while order.size > 0:
70
+ i = order[0]
71
+ keep.append(i)
72
+ xx1 = np.maximum(x1[i], x1[order[1:]])
73
+ yy1 = np.maximum(y1[i], y1[order[1:]])
74
+ xx2 = np.minimum(x2[i], x2[order[1:]])
75
+ yy2 = np.minimum(y2[i], y2[order[1:]])
76
+
77
+ w = np.maximum(0.0, xx2 - xx1 + 1)
78
+ h = np.maximum(0.0, yy2 - yy1 + 1)
79
+ inter = w * h
80
+ ovr = inter / (areas[i] + areas[order[1:]] - inter)
81
+
82
+ inds = np.where(ovr <= self.nmsThreshold)[0]
83
+ order = order[inds + 1]
84
+
85
+ return keep
86
+
87
+ def multiclass_nms(self, boxes, scores):
88
+ """Multiclass NMS implemented in Numpy"""
89
+ final_dets = []
90
+ num_classes = scores.shape[1]
91
+ for cls_ind in range(num_classes):
92
+ cls_scores = scores[:, cls_ind]
93
+ valid_score_mask = cls_scores > self.confThreshold
94
+ if valid_score_mask.sum() == 0:
95
+ continue
96
+ else:
97
+ valid_scores = cls_scores[valid_score_mask]
98
+ valid_boxes = boxes[valid_score_mask]
99
+ keep = self.nms(valid_boxes, valid_scores)
100
+ if len(keep) > 0:
101
+ cls_inds = np.ones((len(keep), 1)) * cls_ind
102
+ dets = np.concatenate([valid_boxes[keep], valid_scores[keep, None], cls_inds], 1)
103
+ final_dets.append(dets)
104
+ if len(final_dets) == 0:
105
+ return None
106
+ return np.concatenate(final_dets, 0)
107
+
108
+ def vis(self, img, boxes, scores, cls_ids):
109
+ detected_classes = []
110
+ for i in range(len(boxes)):
111
+ box = boxes[i]
112
+ cls_id = int(cls_ids[i])
113
+ score = scores[i]
114
+ if score < self.confThreshold:
115
+ continue
116
+ x0 = int(box[0])
117
+ y0 = int(box[1])
118
+ x1 = int(box[2])
119
+ y1 = int(box[3])
120
+
121
+ class_name = self.class_names[cls_id]
122
+ detected_classes.append(class_name)
123
+ text = '{}:{:.1f}%'.format(class_name, score * 100)
124
+ font = cv2.FONT_HERSHEY_SIMPLEX
125
+ txt_size = cv2.getTextSize(text, font, 0.4, 1)[0]
126
+ cv2.rectangle(img, (x0, y0), (x1, y1), (0, 0, 255), 2)
127
+ cv2.rectangle(img, (x0, y0 + 1), (x0 + txt_size[0] + 1, y0 + int(1.5 * txt_size[1])), (255, 255, 255), -1)
128
+ cv2.putText(img, text, (x0, y0 + txt_size[1]), font, 0.4, (0, 0, 0), thickness=1)
129
+ return img, detected_classes
130
+
131
+ def detect(self, srcimg):
132
+ detected_classes = []
133
+ img, ratio = self.preprocess(srcimg)
134
+ blob = cv2.dnn.blobFromImage(img)
135
+ self.net.setInput(blob)
136
+ outs = self.net.forward(self.net.getUnconnectedOutLayersNames())
137
+ predictions = self.demo_postprocess(outs[0])[0]
138
+
139
+ boxes = predictions[:, :4]
140
+ scores = predictions[:, 4:5] * predictions[:, 5:]
141
+
142
+ boxes_xyxy = np.ones_like(boxes)
143
+ boxes_xyxy[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.
144
+ boxes_xyxy[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.
145
+ boxes_xyxy[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.
146
+ boxes_xyxy[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.
147
+ boxes_xyxy /= ratio
148
+ dets = self.multiclass_nms(boxes_xyxy, scores)
149
+ if dets is not None:
150
+ final_boxes, final_scores, final_cls_inds = dets[:, :4], dets[:, 4], dets[:, 5]
151
+ srcimg, detected_classes = self.vis(srcimg, final_boxes, final_scores, final_cls_inds)
152
+ return srcimg, ", ".join(detected_classes) if len(detected_classes) > 0 else ""
153
+