Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

main.py 8.6 KB

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

Press p or to see the previous file or, n or to see the next file

Comments

Loading...