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

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

Comments

Loading...