yolo_model_nms_export.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import time
  4. import cv2
  5. import numpy as np
  6. import onnxruntime
  7. class YOLOv8:
  8. def __init__(self, path, conf_thres=0.7, iou_thres=0.7):
  9. self.conf_threshold = conf_thres
  10. self.iou_threshold = iou_thres
  11. # Initialize model
  12. self.initialize_model(path)
  13. def __call__(self, image):
  14. return self.detect_objects(image)
  15. def initialize_model(self, path):
  16. self.session = onnxruntime.InferenceSession(path,providers=['CUDAExecutionProvider','CPUExecutionProvider'])
  17. # Get model info
  18. self.get_input_details()
  19. self.get_output_details()
  20. def detect_objects(self, image):
  21. input_tensor,ratio = self.prepare_input(image)
  22. # Perform inference on the image
  23. outputs = self.inference(input_tensor)
  24. self.boxes, self.scores, self.class_ids = self.process_output(outputs,ratio)
  25. return self.boxes, self.scores, self.class_ids
  26. def prepare_input(self, image):
  27. self.img_height, self.img_width = image.shape[:2]
  28. input_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  29. # Resize图片不要直接使用resize,需要按比例缩放,空白区域填空纯色即可
  30. input_img,ratio = self.ratioresize(input_img)
  31. # Scale input pixel values to 0 to 1
  32. input_img = input_img / 255.0
  33. input_img = input_img.transpose(2, 0, 1)
  34. input_tensor = input_img[np.newaxis, :, :, :].astype(np.float32)
  35. return input_tensor,ratio
  36. def inference(self, input_tensor):
  37. start = time.perf_counter()
  38. outputs = self.session.run(self.output_names, {self.input_names[0]: input_tensor})
  39. # print(f"Inference time: {(time.perf_counter() - start)*1000:.2f} ms")
  40. return outputs
  41. def process_output(self, output,ratio):
  42. predictions = np.squeeze(output[0]).T
  43. # Filter out object confidence scores below threshold
  44. scores = np.max(predictions[:, 4:], axis=1)
  45. predictions = predictions[scores > self.conf_threshold, :]
  46. scores = scores[scores > self.conf_threshold]
  47. if len(scores) == 0:
  48. return [], [], []
  49. # Get the class with the highest confidence
  50. class_ids = np.argmax(predictions[:, 4:], axis=1)
  51. # Get bounding boxes for each object
  52. boxes = self.extract_boxes(predictions,ratio)
  53. # Apply non-maxima suppression to suppress weak, overlapping bounding boxes
  54. indices = self.nms(boxes, scores, self.iou_threshold)
  55. return boxes[indices], scores[indices], class_ids[indices]
  56. def extract_boxes(self, predictions,ratio):
  57. # Extract boxes from predictions
  58. boxes = predictions[:, :4]
  59. # Scale boxes to original image dimensions
  60. # boxes = self.rescale_boxes(boxes)
  61. boxes *= ratio
  62. # Convert boxes to xyxy format
  63. boxes = self.xywh2xyxy(boxes)
  64. return boxes
  65. def rescale_boxes(self, boxes):
  66. # Rescale boxes to original image dimensions
  67. input_shape = np.array([self.input_width, self.input_height, self.input_width, self.input_height])
  68. boxes = np.divide(boxes, input_shape, dtype=np.float32)
  69. boxes *= np.array([self.img_width, self.img_height, self.img_width, self.img_height])
  70. return boxes
  71. def get_input_details(self):
  72. model_inputs = self.session.get_inputs()
  73. self.input_names = [model_inputs[i].name for i in range(len(model_inputs))]
  74. self.input_shape = model_inputs[0].shape
  75. self.input_height = self.input_shape[2]
  76. self.input_width = self.input_shape[3]
  77. def get_output_details(self):
  78. model_outputs = self.session.get_outputs()
  79. self.output_names = [model_outputs[i].name for i in range(len(model_outputs))]
  80. #等比例缩放图片
  81. def ratioresize(self,im, color=114):
  82. shape = im.shape[:2]
  83. new_h, new_w = self.input_height, self.input_width
  84. padded_img = np.ones((new_h, new_w, 3), dtype=np.uint8) * color
  85. # Scale ratio (new / old)
  86. r = min(new_h / shape[0], new_w / shape[1])
  87. # Compute padding
  88. new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
  89. if shape[::-1] != new_unpad:
  90. im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
  91. padded_img[: new_unpad[1], : new_unpad[0]] = im
  92. padded_img = np.ascontiguousarray(padded_img)
  93. return padded_img, 1 / r
  94. def nms(self, boxes, scores, iou_threshold):
  95. # Sort by score
  96. sorted_indices = np.argsort(scores)[::-1]
  97. keep_boxes = []
  98. while sorted_indices.size > 0:
  99. # Pick the last box
  100. box_id = sorted_indices[0]
  101. keep_boxes.append(box_id)
  102. # Compute IoU of the picked box with the rest
  103. ious = self.compute_iou(boxes[box_id, :], boxes[sorted_indices[1:], :])
  104. # Remove boxes with IoU over the threshold
  105. keep_indices = np.where(ious < iou_threshold)[0]
  106. # print(keep_indices.shape, sorted_indices.shape)
  107. sorted_indices = sorted_indices[keep_indices + 1]
  108. return keep_boxes
  109. def compute_iou(self, box, boxes):
  110. # Compute xmin, ymin, xmax, ymax for both boxes
  111. xmin = np.maximum(box[0], boxes[:, 0])
  112. ymin = np.maximum(box[1], boxes[:, 1])
  113. xmax = np.minimum(box[2], boxes[:, 2])
  114. ymax = np.minimum(box[3], boxes[:, 3])
  115. # Compute intersection area
  116. intersection_area = np.maximum(0, xmax - xmin) * np.maximum(0, ymax - ymin)
  117. # Compute union area
  118. box_area = (box[2] - box[0]) * (box[3] - box[1])
  119. boxes_area = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
  120. union_area = box_area + boxes_area - intersection_area
  121. # Compute IoU
  122. iou = intersection_area / union_area
  123. return iou
  124. def xywh2xyxy(self, x):
  125. # Convert bounding box (x, y, w, h) to bounding box (x1, y1, x2, y2)
  126. y = np.copy(x)
  127. y[..., 0] = x[..., 0] - x[..., 2] / 2
  128. y[..., 1] = x[..., 1] - x[..., 3] / 2
  129. y[..., 2] = x[..., 0] + x[..., 2] / 2
  130. y[..., 3] = x[..., 1] + x[..., 3] / 2
  131. return y
  132. if __name__ == "__main__":
  133. yolov8_detector = YOLOv8(model_path, conf_thres=0.7, iou_thres=0.7)
  134. image = cv2.imread()
  135. boxes, scores, class_ids = yolov8_detector(image)
  136. print(boxes, scores, class_ids)