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 9.4 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
229
230
231
232
233
234
235
236
237
238
239
240
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import argparse
  3. from typing import List
  4. import cv2
  5. import numpy as np
  6. import onnxruntime as ort
  7. import torch
  8. from ultralytics.utils import ASSETS, yaml_load
  9. from ultralytics.utils.checks import check_requirements, check_yaml
  10. class RTDETR:
  11. """
  12. RTDETR object detection model class for handling inference and visualization.
  13. This class implements the RT-DETR (Real-Time Detection Transformer) model for object detection tasks,
  14. supporting ONNX model inference and visualization of detection results.
  15. Attributes:
  16. model_path (str): Path to the ONNX model file.
  17. img_path (str): Path to the input image.
  18. conf_thres (float): Confidence threshold for filtering detections.
  19. iou_thres (float): IoU threshold for non-maximum suppression.
  20. session (ort.InferenceSession): ONNX runtime inference session.
  21. model_input (list): Model input metadata.
  22. input_width (int): Width dimension required by the model.
  23. input_height (int): Height dimension required by the model.
  24. classes (List[str]): List of class names from COCO dataset.
  25. color_palette (np.ndarray): Random color palette for visualization.
  26. img (np.ndarray): Loaded input image.
  27. img_height (int): Height of the input image.
  28. img_width (int): Width of the input image.
  29. """
  30. def __init__(self, model_path: str, img_path: str, conf_thres: float = 0.5, iou_thres: float = 0.5):
  31. """
  32. Initialize the RTDETR object detection model.
  33. Args:
  34. model_path (str): Path to the ONNX model file.
  35. img_path (str): Path to the input image.
  36. conf_thres (float): Confidence threshold for filtering detections.
  37. iou_thres (float): IoU threshold for non-maximum suppression.
  38. """
  39. self.model_path = model_path
  40. self.img_path = img_path
  41. self.conf_thres = conf_thres
  42. self.iou_thres = iou_thres
  43. # Set up the ONNX runtime session with CUDA and CPU execution providers
  44. self.session = ort.InferenceSession(model_path, providers=["CUDAExecutionProvider", "CPUExecutionProvider"])
  45. self.model_input = self.session.get_inputs()
  46. self.input_width = self.model_input[0].shape[2]
  47. self.input_height = self.model_input[0].shape[3]
  48. # Load class names from the COCO dataset YAML file
  49. self.classes = yaml_load(check_yaml("coco8.yaml"))["names"]
  50. # Generate a color palette for drawing bounding boxes
  51. self.color_palette = np.random.uniform(0, 255, size=(len(self.classes), 3))
  52. def draw_detections(self, box: np.ndarray, score: float, class_id: int) -> None:
  53. """
  54. Draw bounding boxes and labels on the input image for detected objects.
  55. Args:
  56. box (np.ndarray): Detected bounding box coordinates [x1, y1, x2, y2].
  57. score (float): Confidence score of the detection.
  58. class_id (int): Class ID for the detected object.
  59. """
  60. # Extract the coordinates of the bounding box
  61. x1, y1, x2, y2 = box
  62. # Retrieve the color for the class ID
  63. color = self.color_palette[class_id]
  64. # Draw the bounding box on the image
  65. cv2.rectangle(self.img, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)
  66. # Create the label text with class name and score
  67. label = f"{self.classes[class_id]}: {score:.2f}"
  68. # Calculate the dimensions of the label text
  69. (label_width, label_height), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
  70. # Calculate the position of the label text
  71. label_x = x1
  72. label_y = y1 - 10 if y1 - 10 > label_height else y1 + 10
  73. # Draw a filled rectangle as the background for the label text
  74. cv2.rectangle(
  75. self.img,
  76. (int(label_x), int(label_y - label_height)),
  77. (int(label_x + label_width), int(label_y + label_height)),
  78. color,
  79. cv2.FILLED,
  80. )
  81. # Draw the label text on the image
  82. cv2.putText(
  83. self.img, label, (int(label_x), int(label_y)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA
  84. )
  85. def preprocess(self) -> np.ndarray:
  86. """
  87. Preprocess the input image for model inference.
  88. Loads the image, converts color space, resizes to model input dimensions, and normalizes pixel values.
  89. Returns:
  90. (np.ndarray): Preprocessed image data with shape (1, 3, H, W) ready for inference.
  91. """
  92. # Read the input image using OpenCV
  93. self.img = cv2.imread(self.img_path)
  94. # Get the height and width of the input image
  95. self.img_height, self.img_width = self.img.shape[:2]
  96. # Convert the image color space from BGR to RGB
  97. img = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB)
  98. # Resize the image to match the input shape
  99. img = cv2.resize(img, (self.input_width, self.input_height))
  100. # Normalize the image data by dividing it by 255.0
  101. image_data = np.array(img) / 255.0
  102. # Transpose the image to have the channel dimension as the first dimension
  103. image_data = np.transpose(image_data, (2, 0, 1)) # Channel first
  104. # Expand the dimensions of the image data to match the expected input shape
  105. image_data = np.expand_dims(image_data, axis=0).astype(np.float32)
  106. return image_data
  107. def bbox_cxcywh_to_xyxy(self, boxes: np.ndarray) -> np.ndarray:
  108. """
  109. Convert bounding boxes from (cx, cy, w, h) format to (x_min, y_min, x_max, y_max) format.
  110. Args:
  111. boxes (np.ndarray): Array of shape (N, 4) where each row represents a bounding box in (cx, cy, w, h) format.
  112. Returns:
  113. (np.ndarray): Array of shape (N, 4) with bounding boxes in (x_min, y_min, x_max, y_max) format.
  114. """
  115. # Calculate half width and half height of the bounding boxes
  116. half_width = boxes[:, 2] / 2
  117. half_height = boxes[:, 3] / 2
  118. # Calculate the coordinates of the bounding boxes
  119. x_min = boxes[:, 0] - half_width
  120. y_min = boxes[:, 1] - half_height
  121. x_max = boxes[:, 0] + half_width
  122. y_max = boxes[:, 1] + half_height
  123. # Return the bounding boxes in (x_min, y_min, x_max, y_max) format
  124. return np.column_stack((x_min, y_min, x_max, y_max))
  125. def postprocess(self, model_output: List[np.ndarray]) -> np.ndarray:
  126. """
  127. Postprocess model output to extract and visualize detections.
  128. Args:
  129. model_output (List[np.ndarray]): Output tensors from the model inference.
  130. Returns:
  131. (np.ndarray): Annotated image with detection bounding boxes and labels.
  132. """
  133. # Squeeze the model output to remove unnecessary dimensions
  134. outputs = np.squeeze(model_output[0])
  135. # Extract bounding boxes and scores from the model output
  136. boxes = outputs[:, :4]
  137. scores = outputs[:, 4:]
  138. # Get the class labels and scores for each detection
  139. labels = np.argmax(scores, axis=1)
  140. scores = np.max(scores, axis=1)
  141. # Apply confidence threshold to filter out low-confidence detections
  142. mask = scores > self.conf_thres
  143. boxes, scores, labels = boxes[mask], scores[mask], labels[mask]
  144. # Convert bounding boxes to (x_min, y_min, x_max, y_max) format
  145. boxes = self.bbox_cxcywh_to_xyxy(boxes)
  146. # Scale bounding boxes to match the original image dimensions
  147. boxes[:, 0::2] *= self.img_width
  148. boxes[:, 1::2] *= self.img_height
  149. # Draw detections on the image
  150. for box, score, label in zip(boxes, scores, labels):
  151. self.draw_detections(box, score, label)
  152. return self.img
  153. def main(self) -> np.ndarray:
  154. """
  155. Execute object detection on the input image using the ONNX model.
  156. Performs the complete detection pipeline: preprocessing, inference, and postprocessing.
  157. Returns:
  158. (np.ndarray): Output image with detection annotations.
  159. """
  160. # Preprocess the image for model input
  161. image_data = self.preprocess()
  162. # Run the model inference
  163. model_output = self.session.run(None, {self.model_input[0].name: image_data})
  164. # Process and return the model output
  165. return self.postprocess(model_output)
  166. if __name__ == "__main__":
  167. # Set up argument parser for command-line arguments
  168. parser = argparse.ArgumentParser()
  169. parser.add_argument("--model", type=str, default="rtdetr-l.onnx", help="Path to the ONNX model file.")
  170. parser.add_argument("--img", type=str, default=str(ASSETS / "bus.jpg"), help="Path to the input image.")
  171. parser.add_argument("--conf-thres", type=float, default=0.5, help="Confidence threshold for object detection.")
  172. parser.add_argument("--iou-thres", type=float, default=0.5, help="IoU threshold for non-maximum suppression.")
  173. args = parser.parse_args()
  174. # Check for dependencies and set up ONNX runtime
  175. check_requirements("onnxruntime-gpu" if torch.cuda.is_available() else "onnxruntime")
  176. # Create the detector instance with specified parameters
  177. detection = RTDETR(args.model, args.img, args.conf_thres, args.iou_thres)
  178. # Perform detection and get the output image
  179. output_image = detection.main()
  180. # Display the annotated output image
  181. cv2.namedWindow("Output", cv2.WINDOW_NORMAL)
  182. cv2.imshow("Output", output_image)
  183. cv2.waitKey(0)
Tip!

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

Comments

Loading...