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 11 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import argparse
  3. import os
  4. from typing import List, Optional
  5. import cv2
  6. import numpy as np
  7. import onnxruntime as ort
  8. import requests
  9. import yaml
  10. def download_file(url: str, local_path: str) -> str:
  11. """
  12. Download a file from a URL to a local path.
  13. Args:
  14. url (str): URL of the file to download.
  15. local_path (str): Local path where the file will be saved.
  16. """
  17. # Check if the local path already exists
  18. if os.path.exists(local_path):
  19. print(f"File already exists at {local_path}. Skipping download.")
  20. return local_path
  21. # Download the file from the URL
  22. print(f"Downloading {url} to {local_path}...")
  23. response = requests.get(url)
  24. with open(local_path, "wb") as f:
  25. f.write(response.content)
  26. return local_path
  27. class RTDETR:
  28. """
  29. RT-DETR (Real-Time Detection Transformer) object detection model for ONNX inference and visualization.
  30. This class implements the RT-DETR model for object detection tasks, supporting ONNX model inference and
  31. visualization of detection results with bounding boxes and class labels.
  32. Attributes:
  33. model_path (str): Path to the ONNX model file.
  34. img_path (str): Path to the input image.
  35. conf_thres (float): Confidence threshold for filtering detections.
  36. iou_thres (float): IoU threshold for non-maximum suppression.
  37. session (ort.InferenceSession): ONNX runtime inference session.
  38. model_input (list): Model input metadata.
  39. input_width (int): Width dimension required by the model.
  40. input_height (int): Height dimension required by the model.
  41. classes (List[str]): List of class names from COCO dataset.
  42. color_palette (np.ndarray): Random color palette for visualization.
  43. img (np.ndarray): Loaded input image.
  44. img_height (int): Height of the input image.
  45. img_width (int): Width of the input image.
  46. Methods:
  47. draw_detections: Draw bounding boxes and labels on the input image.
  48. preprocess: Preprocess the input image for model inference.
  49. bbox_cxcywh_to_xyxy: Convert bounding boxes from center format to corner format.
  50. postprocess: Postprocess model output to extract and visualize detections.
  51. main: Execute the complete object detection pipeline.
  52. Examples:
  53. Initialize RT-DETR detector and run inference
  54. >>> detector = RTDETR("rtdetr-l.onnx", "image.jpg", conf_thres=0.5)
  55. >>> output_image = detector.main()
  56. >>> cv2.imshow("Detections", output_image)
  57. """
  58. def __init__(
  59. self,
  60. model_path: str,
  61. img_path: str,
  62. conf_thres: float = 0.5,
  63. iou_thres: float = 0.5,
  64. class_names: Optional[str] = None,
  65. ):
  66. """
  67. Initialize the RT-DETR object detection model.
  68. Args:
  69. model_path (str): Path to the ONNX model file.
  70. img_path (str): Path to the input image.
  71. conf_thres (float, optional): Confidence threshold for filtering detections.
  72. iou_thres (float, optional): IoU threshold for non-maximum suppression.
  73. class_names (Optional[str], optional): Path to a YAML file containing class names.
  74. If None, uses COCO dataset classes.
  75. """
  76. self.model_path = model_path
  77. self.img_path = img_path
  78. self.conf_thres = conf_thres
  79. self.iou_thres = iou_thres
  80. self.classes = class_names
  81. # Set up the ONNX runtime session with CUDA and CPU execution providers
  82. self.session = ort.InferenceSession(model_path, providers=["CUDAExecutionProvider", "CPUExecutionProvider"])
  83. self.model_input = self.session.get_inputs()
  84. self.input_width = self.model_input[0].shape[2]
  85. self.input_height = self.model_input[0].shape[3]
  86. if self.classes is None:
  87. # Load class names from the COCO dataset YAML file
  88. self.classes = download_file(
  89. "https://raw.githubusercontent.com/ultralytics/"
  90. "ultralytics/refs/heads/main/ultralytics/cfg/datasets/coco8.yaml",
  91. "coco8.yaml",
  92. )
  93. # Parse the YAML file to get class names
  94. with open(self.classes) as f:
  95. class_data = yaml.safe_load(f)
  96. self.classes = list(class_data["names"].values())
  97. # Ensure the classes are a list
  98. if not isinstance(self.classes, list):
  99. raise ValueError("Classes should be a list of class names.")
  100. # Generate a color palette for drawing bounding boxes
  101. self.color_palette: np.ndarray = np.random.uniform(0, 255, size=(len(self.classes), 3))
  102. def draw_detections(self, box: np.ndarray, score: float, class_id: int) -> None:
  103. """Draw bounding box and label on the input image for a detected object."""
  104. # Extract the coordinates of the bounding box
  105. x1, y1, x2, y2 = box
  106. # Retrieve the color for the class ID
  107. color = self.color_palette[class_id]
  108. # Draw the bounding box on the image
  109. cv2.rectangle(self.img, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)
  110. # Create the label text with class name and score
  111. label = f"{self.classes[class_id]}: {score:.2f}"
  112. # Calculate the dimensions of the label text
  113. (label_width, label_height), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
  114. # Calculate the position of the label text
  115. label_x = x1
  116. label_y = y1 - 10 if y1 - 10 > label_height else y1 + 10
  117. # Draw a filled rectangle as the background for the label text
  118. cv2.rectangle(
  119. self.img,
  120. (int(label_x), int(label_y - label_height)),
  121. (int(label_x + label_width), int(label_y + label_height)),
  122. color,
  123. cv2.FILLED,
  124. )
  125. # Draw the label text on the image
  126. cv2.putText(
  127. self.img, label, (int(label_x), int(label_y)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA
  128. )
  129. def preprocess(self) -> np.ndarray:
  130. """
  131. Preprocess the input image for model inference.
  132. Loads the image, converts color space from BGR to RGB, resizes to model input dimensions, and normalizes
  133. pixel values to [0, 1] range.
  134. Returns:
  135. (np.ndarray): Preprocessed image data with shape (1, 3, H, W) ready for inference.
  136. """
  137. # Read the input image using OpenCV
  138. self.img = cv2.imread(self.img_path)
  139. # Get the height and width of the input image
  140. self.img_height, self.img_width = self.img.shape[:2]
  141. # Convert the image color space from BGR to RGB
  142. img = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB)
  143. # Resize the image to match the input shape
  144. img = cv2.resize(img, (self.input_width, self.input_height))
  145. # Normalize the image data by dividing it by 255.0
  146. image_data = np.array(img) / 255.0
  147. # Transpose the image to have the channel dimension as the first dimension
  148. image_data = np.transpose(image_data, (2, 0, 1)) # Channel first
  149. # Expand the dimensions of the image data to match the expected input shape
  150. image_data = np.expand_dims(image_data, axis=0).astype(np.float32)
  151. return image_data
  152. def bbox_cxcywh_to_xyxy(self, boxes: np.ndarray) -> np.ndarray:
  153. """
  154. Convert bounding boxes from center format to corner format.
  155. Args:
  156. boxes (np.ndarray): Array of shape (N, 4) where each row represents a bounding box in
  157. (center_x, center_y, width, height) format.
  158. Returns:
  159. (np.ndarray): Array of shape (N, 4) with bounding boxes in (x_min, y_min, x_max, y_max) format.
  160. """
  161. # Calculate half width and half height of the bounding boxes
  162. half_width = boxes[:, 2] / 2
  163. half_height = boxes[:, 3] / 2
  164. # Calculate the coordinates of the bounding boxes
  165. x_min = boxes[:, 0] - half_width
  166. y_min = boxes[:, 1] - half_height
  167. x_max = boxes[:, 0] + half_width
  168. y_max = boxes[:, 1] + half_height
  169. # Return the bounding boxes in (x_min, y_min, x_max, y_max) format
  170. return np.column_stack((x_min, y_min, x_max, y_max))
  171. def postprocess(self, model_output: List[np.ndarray]) -> np.ndarray:
  172. """
  173. Postprocess model output to extract and visualize detections.
  174. Applies confidence thresholding, converts bounding box format, scales coordinates to original image
  175. dimensions, and draws detection annotations.
  176. Args:
  177. model_output (List[np.ndarray]): Output tensors from the model inference.
  178. Returns:
  179. (np.ndarray): Annotated image with detection bounding boxes and labels.
  180. """
  181. # Squeeze the model output to remove unnecessary dimensions
  182. outputs = np.squeeze(model_output[0])
  183. # Extract bounding boxes and scores from the model output
  184. boxes = outputs[:, :4]
  185. scores = outputs[:, 4:]
  186. # Get the class labels and scores for each detection
  187. labels = np.argmax(scores, axis=1)
  188. scores = np.max(scores, axis=1)
  189. # Apply confidence threshold to filter out low-confidence detections
  190. mask = scores > self.conf_thres
  191. boxes, scores, labels = boxes[mask], scores[mask], labels[mask]
  192. # Convert bounding boxes to (x_min, y_min, x_max, y_max) format
  193. boxes = self.bbox_cxcywh_to_xyxy(boxes)
  194. # Scale bounding boxes to match the original image dimensions
  195. boxes[:, 0::2] *= self.img_width
  196. boxes[:, 1::2] *= self.img_height
  197. # Draw detections on the image
  198. for box, score, label in zip(boxes, scores, labels):
  199. self.draw_detections(box, score, label)
  200. return self.img
  201. def main(self) -> np.ndarray:
  202. """
  203. Execute the complete object detection pipeline on the input image.
  204. Performs preprocessing, ONNX model inference, and postprocessing to generate annotated detection results.
  205. Returns:
  206. (np.ndarray): Output image with detection annotations including bounding boxes and class labels.
  207. """
  208. # Preprocess the image for model input
  209. image_data = self.preprocess()
  210. # Run the model inference
  211. model_output = self.session.run(None, {self.model_input[0].name: image_data})
  212. # Process and return the model output
  213. return self.postprocess(model_output)
  214. if __name__ == "__main__":
  215. # Set up argument parser for command-line arguments
  216. parser = argparse.ArgumentParser()
  217. parser.add_argument("--model", type=str, default="rtdetr-l.onnx", help="Path to the ONNX model file.")
  218. parser.add_argument("--img", type=str, default="bus.jpg", help="Path to the input image.")
  219. parser.add_argument("--conf-thres", type=float, default=0.5, help="Confidence threshold for object detection.")
  220. parser.add_argument("--iou-thres", type=float, default=0.5, help="IoU threshold for non-maximum suppression.")
  221. args = parser.parse_args()
  222. # Create the detector instance with specified parameters
  223. detection = RTDETR(args.model, args.img, args.conf_thres, args.iou_thres)
  224. # Perform detection and get the output image
  225. output_image = detection.main()
  226. # Display the annotated output image
  227. cv2.namedWindow("Output", cv2.WINDOW_NORMAL)
  228. cv2.imshow("Output", output_image)
  229. cv2.waitKey(0)
Tip!

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

Comments

Loading...