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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 39 |
+
# Start from ORT 1.10, ORT requires explicitly setting the providers parameter if you want to use execution providers
|
| 40 |
+
# other than the default CPU provider (as opposed to the previous behavior of providers getting set/registered by default
|
| 41 |
+
# based on the build flags) when instantiating InferenceSession.
|
| 42 |
+
# For example, if NVIDIA GPU is available and ORT Python package is built with CUDA, then call API as following:
|
| 43 |
+
# rt.InferenceSession(path/to/model, providers=['CUDAExecutionProvider'])
|
| 44 |
+
sess = rt.InferenceSession("model.onnx")
|
| 45 |
+
|
| 46 |
+
outputs = sess.get_outputs()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_anchors(anchors_path, tiny=False):
|
| 51 |
+
'''loads the anchors from a file'''
|
| 52 |
+
with open(anchors_path) as f:
|
| 53 |
+
anchors = f.readline()
|
| 54 |
+
anchors = np.array(anchors.split(','), dtype=np.float32)
|
| 55 |
+
return anchors.reshape(3, 3, 2)
|
| 56 |
+
|
| 57 |
+
def postprocess_bbbox(pred_bbox, ANCHORS, STRIDES, XYSCALE=[1,1,1]):
|
| 58 |
+
'''define anchor boxes'''
|
| 59 |
+
for i, pred in enumerate(pred_bbox):
|
| 60 |
+
conv_shape = pred.shape
|
| 61 |
+
output_size = conv_shape[1]
|
| 62 |
+
conv_raw_dxdy = pred[:, :, :, :, 0:2]
|
| 63 |
+
conv_raw_dwdh = pred[:, :, :, :, 2:4]
|
| 64 |
+
xy_grid = np.meshgrid(np.arange(output_size), np.arange(output_size))
|
| 65 |
+
xy_grid = np.expand_dims(np.stack(xy_grid, axis=-1), axis=2)
|
| 66 |
+
|
| 67 |
+
xy_grid = np.tile(np.expand_dims(xy_grid, axis=0), [1, 1, 1, 3, 1])
|
| 68 |
+
xy_grid = xy_grid.astype(np.float)
|
| 69 |
+
|
| 70 |
+
pred_xy = ((special.expit(conv_raw_dxdy) * XYSCALE[i]) - 0.5 * (XYSCALE[i] - 1) + xy_grid) * STRIDES[i]
|
| 71 |
+
pred_wh = (np.exp(conv_raw_dwdh) * ANCHORS[i])
|
| 72 |
+
pred[:, :, :, :, 0:4] = np.concatenate([pred_xy, pred_wh], axis=-1)
|
| 73 |
+
|
| 74 |
+
pred_bbox = [np.reshape(x, (-1, np.shape(x)[-1])) for x in pred_bbox]
|
| 75 |
+
pred_bbox = np.concatenate(pred_bbox, axis=0)
|
| 76 |
+
return pred_bbox
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def postprocess_boxes(pred_bbox, org_img_shape, input_size, score_threshold):
|
| 80 |
+
'''remove boundary boxs with a low detection probability'''
|
| 81 |
+
valid_scale=[0, np.inf]
|
| 82 |
+
pred_bbox = np.array(pred_bbox)
|
| 83 |
+
|
| 84 |
+
pred_xywh = pred_bbox[:, 0:4]
|
| 85 |
+
pred_conf = pred_bbox[:, 4]
|
| 86 |
+
pred_prob = pred_bbox[:, 5:]
|
| 87 |
+
|
| 88 |
+
# # (1) (x, y, w, h) --> (xmin, ymin, xmax, ymax)
|
| 89 |
+
pred_coor = np.concatenate([pred_xywh[:, :2] - pred_xywh[:, 2:] * 0.5,
|
| 90 |
+
pred_xywh[:, :2] + pred_xywh[:, 2:] * 0.5], axis=-1)
|
| 91 |
+
# # (2) (xmin, ymin, xmax, ymax) -> (xmin_org, ymin_org, xmax_org, ymax_org)
|
| 92 |
+
org_h, org_w = org_img_shape
|
| 93 |
+
resize_ratio = min(input_size / org_w, input_size / org_h)
|
| 94 |
+
|
| 95 |
+
dw = (input_size - resize_ratio * org_w) / 2
|
| 96 |
+
dh = (input_size - resize_ratio * org_h) / 2
|
| 97 |
+
|
| 98 |
+
pred_coor[:, 0::2] = 1.0 * (pred_coor[:, 0::2] - dw) / resize_ratio
|
| 99 |
+
pred_coor[:, 1::2] = 1.0 * (pred_coor[:, 1::2] - dh) / resize_ratio
|
| 100 |
+
|
| 101 |
+
# # (3) clip some boxes that are out of range
|
| 102 |
+
pred_coor = np.concatenate([np.maximum(pred_coor[:, :2], [0, 0]),
|
| 103 |
+
np.minimum(pred_coor[:, 2:], [org_w - 1, org_h - 1])], axis=-1)
|
| 104 |
+
invalid_mask = np.logical_or((pred_coor[:, 0] > pred_coor[:, 2]), (pred_coor[:, 1] > pred_coor[:, 3]))
|
| 105 |
+
pred_coor[invalid_mask] = 0
|
| 106 |
+
|
| 107 |
+
# # (4) discard some invalid boxes
|
| 108 |
+
bboxes_scale = np.sqrt(np.multiply.reduce(pred_coor[:, 2:4] - pred_coor[:, 0:2], axis=-1))
|
| 109 |
+
scale_mask = np.logical_and((valid_scale[0] < bboxes_scale), (bboxes_scale < valid_scale[1]))
|
| 110 |
+
|
| 111 |
+
# # (5) discard some boxes with low scores
|
| 112 |
+
classes = np.argmax(pred_prob, axis=-1)
|
| 113 |
+
scores = pred_conf * pred_prob[np.arange(len(pred_coor)), classes]
|
| 114 |
+
score_mask = scores > score_threshold
|
| 115 |
+
mask = np.logical_and(scale_mask, score_mask)
|
| 116 |
+
coors, scores, classes = pred_coor[mask], scores[mask], classes[mask]
|
| 117 |
+
|
| 118 |
+
return np.concatenate([coors, scores[:, np.newaxis], classes[:, np.newaxis]], axis=-1)
|
| 119 |
+
|
| 120 |
+
def bboxes_iou(boxes1, boxes2):
|
| 121 |
+
'''calculate the Intersection Over Union value'''
|
| 122 |
+
boxes1 = np.array(boxes1)
|
| 123 |
+
boxes2 = np.array(boxes2)
|
| 124 |
+
|
| 125 |
+
boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1])
|
| 126 |
+
boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., 3] - boxes2[..., 1])
|
| 127 |
+
|
| 128 |
+
left_up = np.maximum(boxes1[..., :2], boxes2[..., :2])
|
| 129 |
+
right_down = np.minimum(boxes1[..., 2:], boxes2[..., 2:])
|
| 130 |
+
|
| 131 |
+
inter_section = np.maximum(right_down - left_up, 0.0)
|
| 132 |
+
inter_area = inter_section[..., 0] * inter_section[..., 1]
|
| 133 |
+
union_area = boxes1_area + boxes2_area - inter_area
|
| 134 |
+
ious = np.maximum(1.0 * inter_area / union_area, np.finfo(np.float32).eps)
|
| 135 |
+
|
| 136 |
+
return ious
|
| 137 |
+
|
| 138 |
+
def nms(bboxes, iou_threshold, sigma=0.3, method='nms'):
|
| 139 |
+
"""
|
| 140 |
+
:param bboxes: (xmin, ymin, xmax, ymax, score, class)
|
| 141 |
+
|
| 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 |
+
gr.Interface(inference,gr.inputs.Image(type="filepath"),gr.outputs.Image(type="pil")).launch()
|
| 251 |
+
|