yolov5_inference.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. import cv2
  2. import numpy as np
  3. from mindx.sdk import Tensor
  4. from mindx.sdk import base
  5. class YOLOV5Inference:
  6. def __init__(self, model_path, input_size=(640, 640), swap=(2, 0, 1),
  7. score_thr=0.3, nms_thr=0.45, class_agnostic=True):
  8. self.model_path = model_path
  9. self.input_size = input_size
  10. self.swap = swap
  11. self.score_thr = score_thr
  12. self.nms_thr = nms_thr
  13. self.class_agnostic = class_agnostic
  14. base.mx_init()
  15. self.model = base.model(modelPath=self.model_path)
  16. if self.model is None:
  17. raise Exception("模型导入失败!请检查model_path。")
  18. def input_processing(self, image_path):
  19. img = cv2.imread(image_path)
  20. if len(img.shape) == 3:
  21. padded_img = np.ones((self.input_size[0], self.input_size[1], 3), dtype=np.uint8) * 114
  22. else:
  23. padded_img = np.ones(self.input_size, dtype=np.uint8) * 114
  24. r = min(self.input_size[0] / img.shape[0], self.input_size[1] / img.shape[1])
  25. resized_img = cv2.resize(
  26. img,
  27. (int(img.shape[1] * r), int(img.shape[0] * r)),
  28. interpolation=cv2.INTER_LINEAR,
  29. ).astype(np.uint8)
  30. padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img
  31. padded_img = padded_img.transpose(self.swap).copy()
  32. padded_img = np.ascontiguousarray(padded_img, dtype=np.float32)
  33. height, width, channels = img.shape
  34. return padded_img, r, height, width, channels
  35. def predict(self, image_path):
  36. img, ratio, height, width, channels = self.input_processing(image_path)
  37. input_tensors = img[None, :, :, :]
  38. input_tensors = Tensor(input_tensors)
  39. outputs = self.model.infer([input_tensors])[0]
  40. outputs.to_host()
  41. outputs = np.array(outputs)
  42. dets = self.output_processing(outputs, ratio)
  43. return dets
  44. def output_processing(self, outputs, ratio):
  45. outputs = outputs[0] # [1, N, 85] -> [N, 85]
  46. boxes = outputs[:, 0:4]
  47. obj_conf = outputs[:, 4]
  48. class_scores = outputs[:, 5:]
  49. scores = obj_conf[:, None] * class_scores
  50. dets = multiclass_nms(boxes, scores, nms_thr=self.nms_thr, score_thr=self.score_thr,
  51. class_agnostic=self.class_agnostic)
  52. if dets is None or len(dets) == 0:
  53. return np.zeros((0, 6))
  54. # 恢复原图尺度
  55. dets[:, :4] /= ratio
  56. return dets
  57. def nms(boxes, scores, nms_thr):
  58. x1 = boxes[:, 0]
  59. y1 = boxes[:, 1]
  60. x2 = boxes[:, 2]
  61. y2 = boxes[:, 3]
  62. areas = (x2 - x1 + 1) * (y2 - y1 + 1)
  63. order = scores.argsort()[::-1]
  64. keep = []
  65. while order.size > 0:
  66. i = order[0]
  67. keep.append(i)
  68. xx1 = np.maximum(x1[i], x1[order[1:]])
  69. yy1 = np.maximum(y1[i], y1[order[1:]])
  70. xx2 = np.minimum(x2[i], x2[order[1:]])
  71. yy2 = np.minimum(y2[i], y2[order[1:]])
  72. w = np.maximum(0.0, xx2 - xx1 + 1)
  73. h = np.maximum(0.0, yy2 - yy1 + 1)
  74. inter = w * h
  75. ovr = inter / (areas[i] + areas[order[1:]] - inter)
  76. inds = np.where(ovr <= nms_thr)[0]
  77. order = order[inds + 1]
  78. return keep
  79. def multiclass_nms_class_agnostic(boxes, scores, nms_thr, score_thr):
  80. cls_inds = scores.argmax(1)
  81. cls_scores = scores[np.arange(len(cls_inds)), cls_inds]
  82. valid_mask = cls_scores > score_thr
  83. if valid_mask.sum() == 0:
  84. return None
  85. valid_boxes = boxes[valid_mask]
  86. valid_scores = cls_scores[valid_mask]
  87. valid_cls_inds = cls_inds[valid_mask]
  88. keep = nms(valid_boxes, valid_scores, nms_thr)
  89. if not keep:
  90. return None
  91. dets = np.concatenate(
  92. [valid_boxes[keep], valid_scores[keep, None], valid_cls_inds[keep, None]], axis=1
  93. )
  94. return dets
  95. def multiclass_nms_class_aware(boxes, scores, nms_thr, score_thr):
  96. final_dets = []
  97. num_classes = scores.shape[1]
  98. for cls_ind in range(num_classes):
  99. cls_scores = scores[:, cls_ind]
  100. valid_mask = cls_scores > score_thr
  101. if valid_mask.sum() == 0:
  102. continue
  103. valid_boxes = boxes[valid_mask]
  104. valid_scores = cls_scores[valid_mask]
  105. keep = nms(valid_boxes, valid_scores, nms_thr)
  106. if not keep:
  107. continue
  108. cls_inds = np.ones((len(keep), 1)) * cls_ind
  109. dets = np.concatenate([valid_boxes[keep], valid_scores[keep, None], cls_inds], axis=1)
  110. final_dets.append(dets)
  111. if not final_dets:
  112. return None
  113. return np.concatenate(final_dets, axis=0)
  114. def multiclass_nms(boxes, scores, nms_thr, score_thr, class_agnostic=True):
  115. if class_agnostic:
  116. return multiclass_nms_class_agnostic(boxes, scores, nms_thr, score_thr)
  117. else:
  118. return multiclass_nms_class_aware(boxes, scores, nms_thr, score_thr)