imkaushalpatel commited on
Commit
b01f4ea
·
1 Parent(s): bbb1406

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +254 -0
app.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from onnx import numpy_helper
4
+ import onnx
5
+ import os
6
+ from PIL import Image
7
+ from matplotlib.pyplot import imshow
8
+ import onnxruntime as rt
9
+ from scipy import special
10
+ import colorsys
11
+ import random
12
+ import gradio as gr
13
+
14
+ def image_preprocess(image, target_size, gt_boxes=None):
15
+
16
+ ih, iw = target_size
17
+ h, w, _ = image.shape
18
+
19
+ scale = min(iw/w, ih/h)
20
+ nw, nh = int(scale * w), int(scale * h)
21
+ image_resized = cv2.resize(image, (nw, nh))
22
+
23
+ image_padded = np.full(shape=[ih, iw, 3], fill_value=128.0)
24
+ dw, dh = (iw - nw) // 2, (ih-nh) // 2
25
+ image_padded[dh:nh+dh, dw:nw+dw, :] = image_resized
26
+ image_padded = image_padded / 255.
27
+
28
+ if gt_boxes is None:
29
+ return image_padded
30
+
31
+ else:
32
+ gt_boxes[:, [0, 2]] = gt_boxes[:, [0, 2]] * scale + dw
33
+ gt_boxes[:, [1, 3]] = gt_boxes[:, [1, 3]] * scale + dh
34
+ return image_padded, gt_boxes
35
+
36
+ input_size = 416
37
+
38
+ os.system("wget https://github.com/AK391/models/raw/main/vision/object_detection_segmentation/yolov4/model/yolov4.onnx")
39
+
40
+ # Start from ORT 1.10, ORT requires explicitly setting the providers parameter if you want to use execution providers
41
+ # other than the default CPU provider (as opposed to the previous behavior of providers getting set/registered by default
42
+ # based on the build flags) when instantiating InferenceSession.
43
+ # For example, if NVIDIA GPU is available and ORT Python package is built with CUDA, then call API as following:
44
+ # rt.InferenceSession(path/to/model, providers=['CUDAExecutionProvider'])
45
+ sess = rt.InferenceSession("yolov4.onnx")
46
+
47
+ outputs = sess.get_outputs()
48
+
49
+
50
+
51
+ def get_anchors(anchors_path, tiny=False):
52
+ '''loads the anchors from a file'''
53
+ with open(anchors_path) as f:
54
+ anchors = f.readline()
55
+ anchors = np.array(anchors.split(','), dtype=np.float32)
56
+ return anchors.reshape(3, 3, 2)
57
+
58
+ def postprocess_bbbox(pred_bbox, ANCHORS, STRIDES, XYSCALE=[1,1,1]):
59
+ '''define anchor boxes'''
60
+ for i, pred in enumerate(pred_bbox):
61
+ conv_shape = pred.shape
62
+ output_size = conv_shape[1]
63
+ conv_raw_dxdy = pred[:, :, :, :, 0:2]
64
+ conv_raw_dwdh = pred[:, :, :, :, 2:4]
65
+ xy_grid = np.meshgrid(np.arange(output_size), np.arange(output_size))
66
+ xy_grid = np.expand_dims(np.stack(xy_grid, axis=-1), axis=2)
67
+
68
+ xy_grid = np.tile(np.expand_dims(xy_grid, axis=0), [1, 1, 1, 3, 1])
69
+ xy_grid = xy_grid.astype(np.float)
70
+
71
+ pred_xy = ((special.expit(conv_raw_dxdy) * XYSCALE[i]) - 0.5 * (XYSCALE[i] - 1) + xy_grid) * STRIDES[i]
72
+ pred_wh = (np.exp(conv_raw_dwdh) * ANCHORS[i])
73
+ pred[:, :, :, :, 0:4] = np.concatenate([pred_xy, pred_wh], axis=-1)
74
+
75
+ pred_bbox = [np.reshape(x, (-1, np.shape(x)[-1])) for x in pred_bbox]
76
+ pred_bbox = np.concatenate(pred_bbox, axis=0)
77
+ return pred_bbox
78
+
79
+
80
+ def postprocess_boxes(pred_bbox, org_img_shape, input_size, score_threshold):
81
+ '''remove boundary boxs with a low detection probability'''
82
+ valid_scale=[0, np.inf]
83
+ pred_bbox = np.array(pred_bbox)
84
+
85
+ pred_xywh = pred_bbox[:, 0:4]
86
+ pred_conf = pred_bbox[:, 4]
87
+ pred_prob = pred_bbox[:, 5:]
88
+
89
+ # # (1) (x, y, w, h) --> (xmin, ymin, xmax, ymax)
90
+ pred_coor = np.concatenate([pred_xywh[:, :2] - pred_xywh[:, 2:] * 0.5,
91
+ pred_xywh[:, :2] + pred_xywh[:, 2:] * 0.5], axis=-1)
92
+ # # (2) (xmin, ymin, xmax, ymax) -> (xmin_org, ymin_org, xmax_org, ymax_org)
93
+ org_h, org_w = org_img_shape
94
+ resize_ratio = min(input_size / org_w, input_size / org_h)
95
+
96
+ dw = (input_size - resize_ratio * org_w) / 2
97
+ dh = (input_size - resize_ratio * org_h) / 2
98
+
99
+ pred_coor[:, 0::2] = 1.0 * (pred_coor[:, 0::2] - dw) / resize_ratio
100
+ pred_coor[:, 1::2] = 1.0 * (pred_coor[:, 1::2] - dh) / resize_ratio
101
+
102
+ # # (3) clip some boxes that are out of range
103
+ pred_coor = np.concatenate([np.maximum(pred_coor[:, :2], [0, 0]),
104
+ np.minimum(pred_coor[:, 2:], [org_w - 1, org_h - 1])], axis=-1)
105
+ invalid_mask = np.logical_or((pred_coor[:, 0] > pred_coor[:, 2]), (pred_coor[:, 1] > pred_coor[:, 3]))
106
+ pred_coor[invalid_mask] = 0
107
+
108
+ # # (4) discard some invalid boxes
109
+ bboxes_scale = np.sqrt(np.multiply.reduce(pred_coor[:, 2:4] - pred_coor[:, 0:2], axis=-1))
110
+ scale_mask = np.logical_and((valid_scale[0] < bboxes_scale), (bboxes_scale < valid_scale[1]))
111
+
112
+ # # (5) discard some boxes with low scores
113
+ classes = np.argmax(pred_prob, axis=-1)
114
+ scores = pred_conf * pred_prob[np.arange(len(pred_coor)), classes]
115
+ score_mask = scores > score_threshold
116
+ mask = np.logical_and(scale_mask, score_mask)
117
+ coors, scores, classes = pred_coor[mask], scores[mask], classes[mask]
118
+
119
+ return np.concatenate([coors, scores[:, np.newaxis], classes[:, np.newaxis]], axis=-1)
120
+
121
+ def bboxes_iou(boxes1, boxes2):
122
+ '''calculate the Intersection Over Union value'''
123
+ boxes1 = np.array(boxes1)
124
+ boxes2 = np.array(boxes2)
125
+
126
+ boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1])
127
+ boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., 3] - boxes2[..., 1])
128
+
129
+ left_up = np.maximum(boxes1[..., :2], boxes2[..., :2])
130
+ right_down = np.minimum(boxes1[..., 2:], boxes2[..., 2:])
131
+
132
+ inter_section = np.maximum(right_down - left_up, 0.0)
133
+ inter_area = inter_section[..., 0] * inter_section[..., 1]
134
+ union_area = boxes1_area + boxes2_area - inter_area
135
+ ious = np.maximum(1.0 * inter_area / union_area, np.finfo(np.float32).eps)
136
+
137
+ return ious
138
+
139
+ def nms(bboxes, iou_threshold, sigma=0.3, method='nms'):
140
+ """
141
+ :param bboxes: (xmin, ymin, xmax, ymax, score, class)
142
+ Note: soft-nms, https://arxiv.org/pdf/1704.04503.pdf
143
+ https://github.com/bharatsingh430/soft-nms
144
+ """
145
+ classes_in_img = list(set(bboxes[:, 5]))
146
+ best_bboxes = []
147
+
148
+ for cls in classes_in_img:
149
+ cls_mask = (bboxes[:, 5] == cls)
150
+ cls_bboxes = bboxes[cls_mask]
151
+
152
+ while len(cls_bboxes) > 0:
153
+ max_ind = np.argmax(cls_bboxes[:, 4])
154
+ best_bbox = cls_bboxes[max_ind]
155
+ best_bboxes.append(best_bbox)
156
+ cls_bboxes = np.concatenate([cls_bboxes[: max_ind], cls_bboxes[max_ind + 1:]])
157
+ iou = bboxes_iou(best_bbox[np.newaxis, :4], cls_bboxes[:, :4])
158
+ weight = np.ones((len(iou),), dtype=np.float32)
159
+
160
+ assert method in ['nms', 'soft-nms']
161
+
162
+ if method == 'nms':
163
+ iou_mask = iou > iou_threshold
164
+ weight[iou_mask] = 0.0
165
+
166
+ if method == 'soft-nms':
167
+ weight = np.exp(-(1.0 * iou ** 2 / sigma))
168
+
169
+ cls_bboxes[:, 4] = cls_bboxes[:, 4] * weight
170
+ score_mask = cls_bboxes[:, 4] > 0.
171
+ cls_bboxes = cls_bboxes[score_mask]
172
+
173
+ return best_bboxes
174
+
175
+ def read_class_names(class_file_name):
176
+ '''loads class name from a file'''
177
+ names = {}
178
+ with open(class_file_name, 'r') as data:
179
+ for ID, name in enumerate(data):
180
+ names[ID] = name.strip('\n')
181
+ return names
182
+
183
+ def draw_bbox(image, bboxes, classes=read_class_names("coco.names"), show_label=True):
184
+ """
185
+ bboxes: [x_min, y_min, x_max, y_max, probability, cls_id] format coordinates.
186
+ """
187
+
188
+ num_classes = len(classes)
189
+ image_h, image_w, _ = image.shape
190
+ hsv_tuples = [(1.0 * x / num_classes, 1., 1.) for x in range(num_classes)]
191
+ colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
192
+ colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))
193
+
194
+ random.seed(0)
195
+ random.shuffle(colors)
196
+ random.seed(None)
197
+
198
+ for i, bbox in enumerate(bboxes):
199
+ coor = np.array(bbox[:4], dtype=np.int32)
200
+ fontScale = 0.5
201
+ score = bbox[4]
202
+ class_ind = int(bbox[5])
203
+ bbox_color = colors[class_ind]
204
+ bbox_thick = int(0.6 * (image_h + image_w) / 600)
205
+ c1, c2 = (coor[0], coor[1]), (coor[2], coor[3])
206
+ cv2.rectangle(image, c1, c2, bbox_color, bbox_thick)
207
+
208
+ if show_label:
209
+ bbox_mess = '%s: %.2f' % (classes[class_ind], score)
210
+ t_size = cv2.getTextSize(bbox_mess, 0, fontScale, thickness=bbox_thick//2)[0]
211
+ cv2.rectangle(image, c1, (c1[0] + t_size[0], c1[1] - t_size[1] - 3), bbox_color, -1)
212
+ cv2.putText(image, bbox_mess, (c1[0], c1[1]-2), cv2.FONT_HERSHEY_SIMPLEX,
213
+ fontScale, (0, 0, 0), bbox_thick//2, lineType=cv2.LINE_AA)
214
+
215
+ return image
216
+
217
+ def inference(img):
218
+ original_image = cv2.imread(img)
219
+ original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)
220
+ original_image_size = original_image.shape[:2]
221
+
222
+ image_data = image_preprocess(np.copy(original_image), [input_size, input_size])
223
+ image_data = image_data[np.newaxis, ...].astype(np.float32)
224
+
225
+ print("Preprocessed image shape:",image_data.shape) # shape of the preprocessed input
226
+
227
+ output_names = list(map(lambda output: output.name, outputs))
228
+ input_name = sess.get_inputs()[0].name
229
+
230
+ detections = sess.run(output_names, {input_name: image_data})
231
+ print("Output shape:", list(map(lambda detection: detection.shape, detections)))
232
+
233
+ ANCHORS = "./yolov4_anchors.txt"
234
+ STRIDES = [8, 16, 32]
235
+ XYSCALE = [1.2, 1.1, 1.05]
236
+
237
+ ANCHORS = get_anchors(ANCHORS)
238
+ STRIDES = np.array(STRIDES)
239
+
240
+
241
+
242
+ pred_bbox = postprocess_bbbox(detections, ANCHORS, STRIDES, XYSCALE)
243
+ bboxes = postprocess_boxes(pred_bbox, original_image_size, input_size, 0.25)
244
+ bboxes = nms(bboxes, 0.213, method='nms')
245
+ image = draw_bbox(original_image, bboxes)
246
+
247
+ image = Image.fromarray(image)
248
+ return image
249
+
250
+ title="YOLOv4"
251
+ description="YOLOv4 optimizes the speed and accuracy of object detection. It is two times faster than EfficientDet. It improves YOLOv3's AP and FPS by 10% and 12%, respectively, with mAP50 of 52.32 on the COCO 2017 dataset and FPS of 41.7 on Tesla 100."
252
+ examples=[["example.png"]]
253
+ gr.Interface(inference,gr.inputs.Image(type="filepath"),gr.outputs.Image(type="pil"),title=title,description=description,examples=examples).launch()
254
+