yolox_inference.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. """
  2. 定义yolox推理流程
  3. """
  4. import cv2
  5. import numpy as np
  6. from mindx.sdk import Tensor # mxVision 中的 Tensor 数据结构
  7. from mindx.sdk import base # mxVision 推理接口
  8. class YOLOXInference:
  9. def __init__(self, model_path, input_size=(640, 640), swap=(2, 0, 1)):
  10. """
  11. 初始化YOLOX模型推理流程
  12. :param model_path: 图像分类模型onnx文件路径
  13. :param input_size: 模型输入大小
  14. :param swap: 变换方式,pytorch需要进行轴变换(默认参数),tensorflow无需进行轴变换
  15. """
  16. self.model_path = model_path
  17. self.input_size = input_size
  18. self.swap = swap
  19. def input_processing(self, image_path):
  20. """
  21. 对输入图片进行预处理
  22. :param image_path: 图片路径
  23. :return: 图片经过处理完成的ndarray
  24. """
  25. img = cv2.imread(image_path)
  26. if len(img.shape) == 3:
  27. padded_img = np.ones((self.input_size[0], self.input_size[1], 3), dtype=np.uint8) * 114
  28. else:
  29. padded_img = np.ones(self.input_size, dtype=np.uint8) * 114
  30. r = min(self.input_size[0] / img.shape[0], self.input_size[1] / img.shape[1])
  31. resized_img = cv2.resize(
  32. img,
  33. (int(img.shape[1] * r), int(img.shape[0] * r)),
  34. interpolation=cv2.INTER_LINEAR,
  35. ).astype(np.uint8)
  36. padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img
  37. padded_img = padded_img.transpose(self.swap).copy()
  38. padded_img = np.ascontiguousarray(padded_img, dtype=np.float32)
  39. height, width, channels = img.shape
  40. return padded_img, r, height, width, channels
  41. def predict(self, image_path):
  42. """
  43. 对单张图片进行推理
  44. :param image_path: 图片路径
  45. :return: 推理结果
  46. """
  47. img, ratio, height, width, channels = self.input_processing(image_path)
  48. # 使用mindx框架进行om权重文件推理
  49. base.mx_init()
  50. model = base.model(modelPath=self.model_path) # 初始化 base.model 类
  51. if model is None:
  52. raise Exception("模型导入失败!请检查model_path和device_id.")
  53. # 确保img_tensor是正确的输入格式
  54. input_tensors = img[None, :, :, :]
  55. input_tensors = Tensor(input_tensors) # 将numpy转为转为Tensor类
  56. outputs = model.infer([input_tensors])[0] # 执行推理
  57. outputs.to_host()
  58. outputs = np.array(outputs) # 将Tensor数据转移到内存
  59. output = self.output_processing(outputs, ratio)
  60. return output
  61. def output_processing(self, outputs, ratio, p6=False):
  62. """
  63. 对模型输出进行后处理工作
  64. :param outputs: 模型原始输出
  65. :return: 经过处理完成的模型输出
  66. """
  67. grids = []
  68. expanded_strides = []
  69. strides = [8, 16, 32] if not p6 else [8, 16, 32, 64]
  70. hsizes = [self.input_size[0] // stride for stride in strides]
  71. wsizes = [self.input_size[1] // stride for stride in strides]
  72. for hsize, wsize, stride in zip(hsizes, wsizes, strides):
  73. xv, yv = np.meshgrid(np.arange(wsize), np.arange(hsize))
  74. grid = np.stack((xv, yv), 2).reshape(1, -1, 2)
  75. grids.append(grid)
  76. shape = grid.shape[:2]
  77. expanded_strides.append(np.full((*shape, 1), stride))
  78. grids = np.concatenate(grids, 1)
  79. expanded_strides = np.concatenate(expanded_strides, 1)
  80. outputs[..., :2] = (outputs[..., :2] + grids) * expanded_strides
  81. outputs[..., 2:4] = np.exp(outputs[..., 2:4]) * expanded_strides
  82. outputs = outputs[0] # 获取第一张图片的检测结果
  83. boxes = outputs[:, :4]
  84. scores = outputs[:, 4:5] * outputs[:, 5:]
  85. boxes_xyxy = np.ones_like(boxes)
  86. boxes_xyxy[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.
  87. boxes_xyxy[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.
  88. boxes_xyxy[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.
  89. boxes_xyxy[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.
  90. boxes_xyxy /= ratio
  91. dets = multiclass_nms(boxes_xyxy, scores, nms_thr=0.45, score_thr=0.1)
  92. return dets
  93. def nms(boxes, scores, nms_thr):
  94. """Single class NMS implemented in Numpy."""
  95. x1 = boxes[:, 0]
  96. y1 = boxes[:, 1]
  97. x2 = boxes[:, 2]
  98. y2 = boxes[:, 3]
  99. areas = (x2 - x1 + 1) * (y2 - y1 + 1)
  100. order = scores.argsort()[::-1]
  101. keep = []
  102. while order.size > 0:
  103. i = order[0]
  104. keep.append(i)
  105. xx1 = np.maximum(x1[i], x1[order[1:]])
  106. yy1 = np.maximum(y1[i], y1[order[1:]])
  107. xx2 = np.minimum(x2[i], x2[order[1:]])
  108. yy2 = np.minimum(y2[i], y2[order[1:]])
  109. w = np.maximum(0.0, xx2 - xx1 + 1)
  110. h = np.maximum(0.0, yy2 - yy1 + 1)
  111. inter = w * h
  112. ovr = inter / (areas[i] + areas[order[1:]] - inter)
  113. inds = np.where(ovr <= nms_thr)[0]
  114. order = order[inds + 1]
  115. return keep
  116. def multiclass_nms_class_agnostic(boxes, scores, nms_thr, score_thr):
  117. """Multiclass NMS implemented in Numpy. Class-agnostic version."""
  118. cls_inds = scores.argmax(1)
  119. cls_scores = scores[np.arange(len(cls_inds)), cls_inds]
  120. valid_score_mask = cls_scores > score_thr
  121. if valid_score_mask.sum() == 0:
  122. return None
  123. valid_scores = cls_scores[valid_score_mask]
  124. valid_boxes = boxes[valid_score_mask]
  125. valid_cls_inds = cls_inds[valid_score_mask]
  126. keep = nms(valid_boxes, valid_scores, nms_thr)
  127. if keep:
  128. dets = np.concatenate(
  129. [valid_boxes[keep], valid_scores[keep, None], valid_cls_inds[keep, None]], 1
  130. )
  131. return dets
  132. def multiclass_nms_class_aware(boxes, scores, nms_thr, score_thr):
  133. """Multiclass NMS implemented in Numpy. Class-aware version."""
  134. final_dets = []
  135. num_classes = scores.shape[1]
  136. for cls_ind in range(num_classes):
  137. cls_scores = scores[:, cls_ind]
  138. valid_score_mask = cls_scores > score_thr
  139. if valid_score_mask.sum() == 0:
  140. continue
  141. else:
  142. valid_scores = cls_scores[valid_score_mask]
  143. valid_boxes = boxes[valid_score_mask]
  144. keep = nms(valid_boxes, valid_scores, nms_thr)
  145. if len(keep) > 0:
  146. cls_inds = np.ones((len(keep), 1)) * cls_ind
  147. dets = np.concatenate(
  148. [valid_boxes[keep], valid_scores[keep, None], cls_inds], 1
  149. )
  150. final_dets.append(dets)
  151. if len(final_dets) == 0:
  152. return None
  153. return np.concatenate(final_dets, 0)
  154. def multiclass_nms(boxes, scores, nms_thr, score_thr, class_agnostic=True):
  155. """Multiclass NMS implemented in Numpy"""
  156. if class_agnostic:
  157. nms_method = multiclass_nms_class_agnostic
  158. else:
  159. nms_method = multiclass_nms_class_aware
  160. return nms_method(boxes, scores, nms_thr, score_thr)