yolox_inference.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. """
  2. 定义yolox推理流程
  3. """
  4. import cv2
  5. import numpy as np
  6. import onnxruntime as ort
  7. class YOLOXInference:
  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, p6=False):
  53. """
  54. 对模型输出进行后处理工作
  55. :param outputs: 模型原始输出
  56. :return: 经过处理完成的模型输出
  57. """
  58. grids = []
  59. expanded_strides = []
  60. strides = [8, 16, 32] if not p6 else [8, 16, 32, 64]
  61. hsizes = [self.input_size[0] // stride for stride in strides]
  62. wsizes = [self.input_size[1] // stride for stride in strides]
  63. for hsize, wsize, stride in zip(hsizes, wsizes, strides):
  64. xv, yv = np.meshgrid(np.arange(wsize), np.arange(hsize))
  65. grid = np.stack((xv, yv), 2).reshape(1, -1, 2)
  66. grids.append(grid)
  67. shape = grid.shape[:2]
  68. expanded_strides.append(np.full((*shape, 1), stride))
  69. grids = np.concatenate(grids, 1)
  70. expanded_strides = np.concatenate(expanded_strides, 1)
  71. outputs[..., :2] = (outputs[..., :2] + grids) * expanded_strides
  72. outputs[..., 2:4] = np.exp(outputs[..., 2:4]) * expanded_strides
  73. outputs = outputs[0] # 获取第一张图片的检测结果
  74. boxes = outputs[:, :4]
  75. scores = outputs[:, 4:5] * outputs[:, 5:]
  76. boxes_xyxy = np.ones_like(boxes)
  77. boxes_xyxy[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.
  78. boxes_xyxy[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.
  79. boxes_xyxy[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.
  80. boxes_xyxy[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.
  81. boxes_xyxy /= ratio
  82. dets = multiclass_nms(boxes_xyxy, scores, nms_thr=0.45, score_thr=0.1)
  83. return dets
  84. def nms(boxes, scores, nms_thr):
  85. """Single class NMS implemented in Numpy."""
  86. x1 = boxes[:, 0]
  87. y1 = boxes[:, 1]
  88. x2 = boxes[:, 2]
  89. y2 = boxes[:, 3]
  90. areas = (x2 - x1 + 1) * (y2 - y1 + 1)
  91. order = scores.argsort()[::-1]
  92. keep = []
  93. while order.size > 0:
  94. i = order[0]
  95. keep.append(i)
  96. xx1 = np.maximum(x1[i], x1[order[1:]])
  97. yy1 = np.maximum(y1[i], y1[order[1:]])
  98. xx2 = np.minimum(x2[i], x2[order[1:]])
  99. yy2 = np.minimum(y2[i], y2[order[1:]])
  100. w = np.maximum(0.0, xx2 - xx1 + 1)
  101. h = np.maximum(0.0, yy2 - yy1 + 1)
  102. inter = w * h
  103. ovr = inter / (areas[i] + areas[order[1:]] - inter)
  104. inds = np.where(ovr <= nms_thr)[0]
  105. order = order[inds + 1]
  106. return keep
  107. def multiclass_nms_class_agnostic(boxes, scores, nms_thr, score_thr):
  108. """Multiclass NMS implemented in Numpy. Class-agnostic version."""
  109. cls_inds = scores.argmax(1)
  110. cls_scores = scores[np.arange(len(cls_inds)), cls_inds]
  111. valid_score_mask = cls_scores > score_thr
  112. if valid_score_mask.sum() == 0:
  113. return None
  114. valid_scores = cls_scores[valid_score_mask]
  115. valid_boxes = boxes[valid_score_mask]
  116. valid_cls_inds = cls_inds[valid_score_mask]
  117. keep = nms(valid_boxes, valid_scores, nms_thr)
  118. if keep:
  119. dets = np.concatenate(
  120. [valid_boxes[keep], valid_scores[keep, None], valid_cls_inds[keep, None]], 1
  121. )
  122. return dets
  123. def multiclass_nms_class_aware(boxes, scores, nms_thr, score_thr):
  124. """Multiclass NMS implemented in Numpy. Class-aware version."""
  125. final_dets = []
  126. num_classes = scores.shape[1]
  127. for cls_ind in range(num_classes):
  128. cls_scores = scores[:, cls_ind]
  129. valid_score_mask = cls_scores > score_thr
  130. if valid_score_mask.sum() == 0:
  131. continue
  132. else:
  133. valid_scores = cls_scores[valid_score_mask]
  134. valid_boxes = boxes[valid_score_mask]
  135. keep = nms(valid_boxes, valid_scores, nms_thr)
  136. if len(keep) > 0:
  137. cls_inds = np.ones((len(keep), 1)) * cls_ind
  138. dets = np.concatenate(
  139. [valid_boxes[keep], valid_scores[keep, None], cls_inds], 1
  140. )
  141. final_dets.append(dets)
  142. if len(final_dets) == 0:
  143. return None
  144. return np.concatenate(final_dets, 0)
  145. def multiclass_nms(boxes, scores, nms_thr, score_thr, class_agnostic=True):
  146. """Multiclass NMS implemented in Numpy"""
  147. if class_agnostic:
  148. nms_method = multiclass_nms_class_agnostic
  149. else:
  150. nms_method = multiclass_nms_class_aware
  151. return nms_method(boxes, scores, nms_thr, score_thr)