yolov5_inference.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. """
  2. 定义yolox推理流程
  3. """
  4. import cv2
  5. import numpy as np
  6. import onnxruntime as ort
  7. class YOLOV5Inference:
  8. def __init__(self, model_path, input_size=(640, 640), swap=(2, 0, 1)):
  9. """
  10. 初始化YOLOX模型推理流程
  11. :param model_path: 图像分类模型onnx文件路径
  12. :param input_size: 模型输入大小
  13. :param swap: 变换方式,pytorch需要进行轴变换(默认参数),tensorflow无需进行轴变换
  14. """
  15. self.model_path = model_path
  16. self.input_size = input_size
  17. self.swap = swap
  18. def input_processing(self, image_path):
  19. """
  20. 对输入图片进行预处理
  21. :param image_path: 图片路径
  22. :return: 图片经过处理完成的ndarray
  23. """
  24. img = cv2.imread(image_path)
  25. if len(img.shape) == 3:
  26. padded_img = np.ones((self.input_size[0], self.input_size[1], 3), dtype=np.uint8) * 114
  27. else:
  28. padded_img = np.ones(self.input_size, dtype=np.uint8) * 114
  29. r = min(self.input_size[0] / img.shape[0], self.input_size[1] / img.shape[1])
  30. resized_img = cv2.resize(
  31. img,
  32. (int(img.shape[1] * r), int(img.shape[0] * r)),
  33. interpolation=cv2.INTER_LINEAR,
  34. ).astype(np.uint8)
  35. padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img
  36. padded_img = padded_img.transpose(self.swap).copy()
  37. padded_img = np.ascontiguousarray(padded_img, dtype=np.float32)
  38. height, width, channels = img.shape
  39. return padded_img, r, height, width, channels
  40. def predict(self, image_path):
  41. """
  42. 对单张图片进行推理
  43. :param image_path: 图片路径
  44. :return: 推理结果
  45. """
  46. img, ratio, height, width, channels = self.input_processing(image_path)
  47. session = ort.InferenceSession(self.model_path)
  48. ort_inputs = {session.get_inputs()[0].name: img[None, :, :, :]}
  49. output = session.run(None, ort_inputs)
  50. output = self.output_processing(output[0], ratio)
  51. return output
  52. def output_processing(self, outputs, ratio):
  53. """
  54. YOLOv5 的输出处理流程
  55. :param outputs: 模型输出 (1, 25200, 85)
  56. :param ratio: 预处理时的缩放比例
  57. """
  58. outputs = outputs[0]
  59. boxes = outputs[:, :4]
  60. obj_conf = outputs[:, 4:5]
  61. class_conf = outputs[:, 5:]
  62. scores = obj_conf * class_conf
  63. # xywh to xyxy
  64. boxes_xyxy = np.zeros_like(boxes)
  65. boxes_xyxy[:, 0] = boxes[:, 0] - boxes[:, 2] / 2 # x1
  66. boxes_xyxy[:, 1] = boxes[:, 1] - boxes[:, 3] / 2 # y1
  67. boxes_xyxy[:, 2] = boxes[:, 0] + boxes[:, 2] / 2 # x2
  68. boxes_xyxy[:, 3] = boxes[:, 1] + boxes[:, 3] / 2 # y2
  69. # 还原原图坐标
  70. boxes_xyxy /= ratio
  71. # NMS
  72. dets = multiclass_nms(boxes_xyxy, scores, nms_thr=0.45, score_thr=0.25)
  73. return dets
  74. def nms(boxes, scores, nms_thr):
  75. """Single class NMS implemented in Numpy."""
  76. x1 = boxes[:, 0]
  77. y1 = boxes[:, 1]
  78. x2 = boxes[:, 2]
  79. y2 = boxes[:, 3]
  80. areas = (x2 - x1 + 1) * (y2 - y1 + 1)
  81. order = scores.argsort()[::-1]
  82. keep = []
  83. while order.size > 0:
  84. i = order[0]
  85. keep.append(i)
  86. xx1 = np.maximum(x1[i], x1[order[1:]])
  87. yy1 = np.maximum(y1[i], y1[order[1:]])
  88. xx2 = np.minimum(x2[i], x2[order[1:]])
  89. yy2 = np.minimum(y2[i], y2[order[1:]])
  90. w = np.maximum(0.0, xx2 - xx1 + 1)
  91. h = np.maximum(0.0, yy2 - yy1 + 1)
  92. inter = w * h
  93. ovr = inter / (areas[i] + areas[order[1:]] - inter)
  94. inds = np.where(ovr <= nms_thr)[0]
  95. order = order[inds + 1]
  96. return keep
  97. def multiclass_nms_class_agnostic(boxes, scores, nms_thr, score_thr):
  98. """Multiclass NMS implemented in Numpy. Class-agnostic version."""
  99. cls_inds = scores.argmax(1)
  100. cls_scores = scores[np.arange(len(cls_inds)), cls_inds]
  101. valid_score_mask = cls_scores > score_thr
  102. if valid_score_mask.sum() == 0:
  103. return None
  104. valid_scores = cls_scores[valid_score_mask]
  105. valid_boxes = boxes[valid_score_mask]
  106. valid_cls_inds = cls_inds[valid_score_mask]
  107. keep = nms(valid_boxes, valid_scores, nms_thr)
  108. if keep:
  109. dets = np.concatenate(
  110. [valid_boxes[keep], valid_scores[keep, None], valid_cls_inds[keep, None]], 1
  111. )
  112. return dets
  113. def multiclass_nms_class_aware(boxes, scores, nms_thr, score_thr):
  114. """Multiclass NMS implemented in Numpy. Class-aware version."""
  115. final_dets = []
  116. num_classes = scores.shape[1]
  117. for cls_ind in range(num_classes):
  118. cls_scores = scores[:, cls_ind]
  119. valid_score_mask = cls_scores > score_thr
  120. if valid_score_mask.sum() == 0:
  121. continue
  122. else:
  123. valid_scores = cls_scores[valid_score_mask]
  124. valid_boxes = boxes[valid_score_mask]
  125. keep = nms(valid_boxes, valid_scores, nms_thr)
  126. if len(keep) > 0:
  127. cls_inds = np.ones((len(keep), 1)) * cls_ind
  128. dets = np.concatenate(
  129. [valid_boxes[keep], valid_scores[keep, None], cls_inds], 1
  130. )
  131. final_dets.append(dets)
  132. if len(final_dets) == 0:
  133. return None
  134. return np.concatenate(final_dets, 0)
  135. def multiclass_nms(boxes, scores, nms_thr, score_thr, class_agnostic=True):
  136. """Multiclass NMS implemented in Numpy"""
  137. if class_agnostic:
  138. nms_method = multiclass_nms_class_agnostic
  139. else:
  140. nms_method = multiclass_nms_class_aware
  141. return nms_method(boxes, scores, nms_thr, score_thr)