main.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import argparse
  2. import cv2
  3. import numpy as np
  4. import onnxruntime as ort
  5. import torch
  6. from ultralytics.utils import ASSETS, yaml_load
  7. from ultralytics.utils.checks import check_requirements, check_yaml
  8. class Yolov8:
  9. def __init__(self, onnx_model, input_image, confidence_thres, iou_thres):
  10. """
  11. Initializes an instance of the Yolov8 class.
  12. Args:
  13. onnx_model: Path to the ONNX model.
  14. input_image: Path to the input image.
  15. confidence_thres: Confidence threshold for filtering detections.
  16. iou_thres: IoU (Intersection over Union) threshold for non-maximum suppression.
  17. """
  18. self.onnx_model = onnx_model
  19. self.input_image = input_image
  20. self.confidence_thres = confidence_thres
  21. self.iou_thres = iou_thres
  22. # Load the class names from the COCO dataset
  23. self.classes = yaml_load(check_yaml('coco128.yaml'))['names']
  24. # Generate a color palette for the classes
  25. self.color_palette = np.random.uniform(0, 255, size=(len(self.classes), 3))
  26. def draw_detections(self, img, box, score, class_id):
  27. """
  28. Draws bounding boxes and labels on the input image based on the detected objects.
  29. Args:
  30. img: The input image to draw detections on.
  31. box: Detected bounding box.
  32. score: Corresponding detection score.
  33. class_id: Class ID for the detected object.
  34. Returns:
  35. None
  36. """
  37. # Extract the coordinates of the bounding box
  38. x1, y1, w, h = box
  39. # Retrieve the color for the class ID
  40. color = self.color_palette[class_id]
  41. # Draw the bounding box on the image
  42. cv2.rectangle(img, (int(x1), int(y1)), (int(x1 + w), int(y1 + h)), color, 2)
  43. # Create the label text with class name and score
  44. label = f'{self.classes[class_id]}: {score:.2f}'
  45. # Calculate the dimensions of the label text
  46. (label_width, label_height), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
  47. # Calculate the position of the label text
  48. label_x = x1
  49. label_y = y1 - 10 if y1 - 10 > label_height else y1 + 10
  50. # Draw a filled rectangle as the background for the label text
  51. cv2.rectangle(img, (label_x, label_y - label_height), (label_x + label_width, label_y + label_height), color,
  52. cv2.FILLED)
  53. # Draw the label text on the image
  54. cv2.putText(img, label, (label_x, label_y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)
  55. def preprocess(self):
  56. """
  57. Preprocesses the input image before performing inference.
  58. Returns:
  59. image_data: Preprocessed image data ready for inference.
  60. """
  61. # Read the input image using OpenCV
  62. self.img = cv2.imread(self.input_image)
  63. # Get the height and width of the input image
  64. self.img_height, self.img_width = self.img.shape[:2]
  65. # Convert the image color space from BGR to RGB
  66. img = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB)
  67. # Resize the image to match the input shape
  68. img = cv2.resize(img, (self.input_width, self.input_height))
  69. # Normalize the image data by dividing it by 255.0
  70. image_data = np.array(img) / 255.0
  71. # Transpose the image to have the channel dimension as the first dimension
  72. image_data = np.transpose(image_data, (2, 0, 1)) # Channel first
  73. # Expand the dimensions of the image data to match the expected input shape
  74. image_data = np.expand_dims(image_data, axis=0).astype(np.float32)
  75. # Return the preprocessed image data
  76. return image_data
  77. def postprocess(self, input_image, output):
  78. """
  79. Performs post-processing on the model's output to extract bounding boxes, scores, and class IDs.
  80. Args:
  81. input_image (numpy.ndarray): The input image.
  82. output (numpy.ndarray): The output of the model.
  83. Returns:
  84. numpy.ndarray: The input image with detections drawn on it.
  85. """
  86. # Transpose and squeeze the output to match the expected shape
  87. outputs = np.transpose(np.squeeze(output[0]))
  88. # Get the number of rows in the outputs array
  89. rows = outputs.shape[0]
  90. # Lists to store the bounding boxes, scores, and class IDs of the detections
  91. boxes = []
  92. scores = []
  93. class_ids = []
  94. # Calculate the scaling factors for the bounding box coordinates
  95. x_factor = self.img_width / self.input_width
  96. y_factor = self.img_height / self.input_height
  97. # Iterate over each row in the outputs array
  98. for i in range(rows):
  99. # Extract the class scores from the current row
  100. classes_scores = outputs[i][4:]
  101. # Find the maximum score among the class scores
  102. max_score = np.amax(classes_scores)
  103. # If the maximum score is above the confidence threshold
  104. if max_score >= self.confidence_thres:
  105. # Get the class ID with the highest score
  106. class_id = np.argmax(classes_scores)
  107. # Extract the bounding box coordinates from the current row
  108. x, y, w, h = outputs[i][0], outputs[i][1], outputs[i][2], outputs[i][3]
  109. # Calculate the scaled coordinates of the bounding box
  110. left = int((x - w / 2) * x_factor)
  111. top = int((y - h / 2) * y_factor)
  112. width = int(w * x_factor)
  113. height = int(h * y_factor)
  114. # Add the class ID, score, and box coordinates to the respective lists
  115. class_ids.append(class_id)
  116. scores.append(max_score)
  117. boxes.append([left, top, width, height])
  118. # Apply non-maximum suppression to filter out overlapping bounding boxes
  119. indices = cv2.dnn.NMSBoxes(boxes, scores, self.confidence_thres, self.iou_thres)
  120. # Iterate over the selected indices after non-maximum suppression
  121. for i in indices:
  122. # Get the box, score, and class ID corresponding to the index
  123. box = boxes[i]
  124. score = scores[i]
  125. class_id = class_ids[i]
  126. # Draw the detection on the input image
  127. self.draw_detections(input_image, box, score, class_id)
  128. # Return the modified input image
  129. return input_image
  130. def main(self):
  131. """
  132. Performs inference using an ONNX model and returns the output image with drawn detections.
  133. Returns:
  134. output_img: The output image with drawn detections.
  135. """
  136. # Create an inference session using the ONNX model and specify execution providers
  137. session = ort.InferenceSession(self.onnx_model, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
  138. # Get the model inputs
  139. model_inputs = session.get_inputs()
  140. # Store the shape of the input for later use
  141. input_shape = model_inputs[0].shape
  142. self.input_width = input_shape[2]
  143. self.input_height = input_shape[3]
  144. # Preprocess the image data
  145. img_data = self.preprocess()
  146. # Run inference using the preprocessed image data
  147. outputs = session.run(None, {model_inputs[0].name: img_data})
  148. # Perform post-processing on the outputs to obtain output image.
  149. return self.postprocess(self.img, outputs) # output image
  150. if __name__ == '__main__':
  151. # Create an argument parser to handle command-line arguments
  152. parser = argparse.ArgumentParser()
  153. parser.add_argument('--model', type=str, default='yolov8n.onnx', help='Input your ONNX model.')
  154. parser.add_argument('--img', type=str, default=str(ASSETS / 'bus.jpg'), help='Path to input image.')
  155. parser.add_argument('--conf-thres', type=float, default=0.5, help='Confidence threshold')
  156. parser.add_argument('--iou-thres', type=float, default=0.5, help='NMS IoU threshold')
  157. args = parser.parse_args()
  158. # Check the requirements and select the appropriate backend (CPU or GPU)
  159. check_requirements('onnxruntime-gpu' if torch.cuda.is_available() else 'onnxruntime')
  160. # Create an instance of the Yolov8 class with the specified arguments
  161. detection = Yolov8(args.model, args.img, args.conf_thres, args.iou_thres)
  162. # Perform object detection and obtain the output image
  163. output_image = detection.main()
  164. # Display the output image in a window
  165. cv2.namedWindow('Output', cv2.WINDOW_NORMAL)
  166. cv2.imshow('Output', output_image)
  167. # Wait for a key press to exit
  168. cv2.waitKey(0)