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
294
295
296
297
298
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import argparse
  3. import cv2
  4. import numpy as np
  5. from tflite_runtime import interpreter as tflite
  6. from ultralytics.utils import ASSETS, yaml_load
  7. from ultralytics.utils.checks import check_yaml
  8. # Declare as global variables, can be updated based trained model image size
  9. img_width = 640
  10. img_height = 640
  11. class LetterBox:
  12. """Resizes and reshapes images while maintaining aspect ratio by adding padding, suitable for YOLO models."""
  13. def __init__(
  14. self, new_shape=(img_width, img_height), auto=False, scaleFill=False, scaleup=True, center=True, stride=32
  15. ):
  16. """Initializes LetterBox with parameters for reshaping and transforming image while maintaining aspect ratio."""
  17. self.new_shape = new_shape
  18. self.auto = auto
  19. self.scaleFill = scaleFill
  20. self.scaleup = scaleup
  21. self.stride = stride
  22. self.center = center # Put the image in the middle or top-left
  23. def __call__(self, labels=None, image=None):
  24. """Return updated labels and image with added border."""
  25. if labels is None:
  26. labels = {}
  27. img = labels.get("img") if image is None else image
  28. shape = img.shape[:2] # current shape [height, width]
  29. new_shape = labels.pop("rect_shape", self.new_shape)
  30. if isinstance(new_shape, int):
  31. new_shape = (new_shape, new_shape)
  32. # Scale ratio (new / old)
  33. r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
  34. if not self.scaleup: # only scale down, do not scale up (for better val mAP)
  35. r = min(r, 1.0)
  36. # Compute padding
  37. ratio = r, r # width, height ratios
  38. new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
  39. dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
  40. if self.auto: # minimum rectangle
  41. dw, dh = np.mod(dw, self.stride), np.mod(dh, self.stride) # wh padding
  42. elif self.scaleFill: # stretch
  43. dw, dh = 0.0, 0.0
  44. new_unpad = (new_shape[1], new_shape[0])
  45. ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
  46. if self.center:
  47. dw /= 2 # divide padding into 2 sides
  48. dh /= 2
  49. if shape[::-1] != new_unpad: # resize
  50. img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
  51. top, bottom = int(round(dh - 0.1)) if self.center else 0, int(round(dh + 0.1))
  52. left, right = int(round(dw - 0.1)) if self.center else 0, int(round(dw + 0.1))
  53. img = cv2.copyMakeBorder(
  54. img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114)
  55. ) # add border
  56. if labels.get("ratio_pad"):
  57. labels["ratio_pad"] = (labels["ratio_pad"], (left, top)) # for evaluation
  58. if len(labels):
  59. labels = self._update_labels(labels, ratio, dw, dh)
  60. labels["img"] = img
  61. labels["resized_shape"] = new_shape
  62. return labels
  63. else:
  64. return img
  65. def _update_labels(self, labels, ratio, padw, padh):
  66. """Update labels."""
  67. labels["instances"].convert_bbox(format="xyxy")
  68. labels["instances"].denormalize(*labels["img"].shape[:2][::-1])
  69. labels["instances"].scale(*ratio)
  70. labels["instances"].add_padding(padw, padh)
  71. return labels
  72. class Yolov8TFLite:
  73. """Class for performing object detection using YOLOv8 model converted to TensorFlow Lite format."""
  74. def __init__(self, tflite_model, input_image, confidence_thres, iou_thres):
  75. """
  76. Initializes an instance of the Yolov8TFLite class.
  77. Args:
  78. tflite_model: Path to the TFLite model.
  79. input_image: Path to the input image.
  80. confidence_thres: Confidence threshold for filtering detections.
  81. iou_thres: IoU (Intersection over Union) threshold for non-maximum suppression.
  82. """
  83. self.tflite_model = tflite_model
  84. self.input_image = input_image
  85. self.confidence_thres = confidence_thres
  86. self.iou_thres = iou_thres
  87. # Load the class names from the COCO dataset
  88. self.classes = yaml_load(check_yaml("coco8.yaml"))["names"]
  89. # Generate a color palette for the classes
  90. self.color_palette = np.random.uniform(0, 255, size=(len(self.classes), 3))
  91. def draw_detections(self, img, box, score, class_id):
  92. """
  93. Draws bounding boxes and labels on the input image based on the detected objects.
  94. Args:
  95. img: The input image to draw detections on.
  96. box: Detected bounding box.
  97. score: Corresponding detection score.
  98. class_id: Class ID for the detected object.
  99. Returns:
  100. None
  101. """
  102. # Extract the coordinates of the bounding box
  103. x1, y1, w, h = box
  104. # Retrieve the color for the class ID
  105. color = self.color_palette[class_id]
  106. # Draw the bounding box on the image
  107. cv2.rectangle(img, (int(x1), int(y1)), (int(x1 + w), int(y1 + h)), color, 2)
  108. # Create the label text with class name and score
  109. label = f"{self.classes[class_id]}: {score:.2f}"
  110. # Calculate the dimensions of the label text
  111. (label_width, label_height), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
  112. # Calculate the position of the label text
  113. label_x = x1
  114. label_y = y1 - 10 if y1 - 10 > label_height else y1 + 10
  115. # Draw a filled rectangle as the background for the label text
  116. cv2.rectangle(
  117. img,
  118. (int(label_x), int(label_y - label_height)),
  119. (int(label_x + label_width), int(label_y + label_height)),
  120. color,
  121. cv2.FILLED,
  122. )
  123. # Draw the label text on the image
  124. cv2.putText(img, label, (int(label_x), int(label_y)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)
  125. def preprocess(self):
  126. """
  127. Preprocesses the input image before performing inference.
  128. Returns:
  129. image_data: Preprocessed image data ready for inference.
  130. """
  131. # Read the input image using OpenCV
  132. self.img = cv2.imread(self.input_image)
  133. print("image before", self.img)
  134. # Get the height and width of the input image
  135. self.img_height, self.img_width = self.img.shape[:2]
  136. letterbox = LetterBox(new_shape=[img_width, img_height], auto=False, stride=32)
  137. image = letterbox(image=self.img)
  138. image = [image]
  139. image = np.stack(image)
  140. image = image[..., ::-1].transpose((0, 3, 1, 2))
  141. img = np.ascontiguousarray(image)
  142. # n, h, w, c
  143. image = img.astype(np.float32)
  144. return image / 255
  145. def postprocess(self, input_image, output):
  146. """
  147. Performs post-processing on the model's output to extract bounding boxes, scores, and class IDs.
  148. Args:
  149. input_image (numpy.ndarray): The input image.
  150. output (numpy.ndarray): The output of the model.
  151. Returns:
  152. numpy.ndarray: The input image with detections drawn on it.
  153. """
  154. boxes = []
  155. scores = []
  156. class_ids = []
  157. for pred in output:
  158. pred = np.transpose(pred)
  159. for box in pred:
  160. x, y, w, h = box[:4]
  161. x1 = x - w / 2
  162. y1 = y - h / 2
  163. boxes.append([x1, y1, w, h])
  164. idx = np.argmax(box[4:])
  165. scores.append(box[idx + 4])
  166. class_ids.append(idx)
  167. indices = cv2.dnn.NMSBoxes(boxes, scores, self.confidence_thres, self.iou_thres)
  168. for i in indices:
  169. # Get the box, score, and class ID corresponding to the index
  170. box = boxes[i]
  171. gain = min(img_width / self.img_width, img_height / self.img_height)
  172. pad = (
  173. round((img_width - self.img_width * gain) / 2 - 0.1),
  174. round((img_height - self.img_height * gain) / 2 - 0.1),
  175. )
  176. box[0] = (box[0] - pad[0]) / gain
  177. box[1] = (box[1] - pad[1]) / gain
  178. box[2] = box[2] / gain
  179. box[3] = box[3] / gain
  180. score = scores[i]
  181. class_id = class_ids[i]
  182. if score > 0.25:
  183. print(box, score, class_id)
  184. # Draw the detection on the input image
  185. self.draw_detections(input_image, box, score, class_id)
  186. return input_image
  187. def main(self):
  188. """
  189. Performs inference using a TFLite model and returns the output image with drawn detections.
  190. Returns:
  191. output_img: The output image with drawn detections.
  192. """
  193. # Create an interpreter for the TFLite model
  194. interpreter = tflite.Interpreter(model_path=self.tflite_model)
  195. self.model = interpreter
  196. interpreter.allocate_tensors()
  197. # Get the model inputs
  198. input_details = interpreter.get_input_details()
  199. output_details = interpreter.get_output_details()
  200. # Store the shape of the input for later use
  201. input_shape = input_details[0]["shape"]
  202. self.input_width = input_shape[1]
  203. self.input_height = input_shape[2]
  204. # Preprocess the image data
  205. img_data = self.preprocess()
  206. img_data = img_data
  207. # img_data = img_data.cpu().numpy()
  208. # Set the input tensor to the interpreter
  209. print(input_details[0]["index"])
  210. print(img_data.shape)
  211. img_data = img_data.transpose((0, 2, 3, 1))
  212. scale, zero_point = input_details[0]["quantization"]
  213. img_data_int8 = (img_data / scale + zero_point).astype(np.int8)
  214. interpreter.set_tensor(input_details[0]["index"], img_data_int8)
  215. # Run inference
  216. interpreter.invoke()
  217. # Get the output tensor from the interpreter
  218. output = interpreter.get_tensor(output_details[0]["index"])
  219. scale, zero_point = output_details[0]["quantization"]
  220. output = (output.astype(np.float32) - zero_point) * scale
  221. output[:, [0, 2]] *= img_width
  222. output[:, [1, 3]] *= img_height
  223. print(output)
  224. # Perform post-processing on the outputs to obtain output image.
  225. return self.postprocess(self.img, output)
  226. if __name__ == "__main__":
  227. # Create an argument parser to handle command-line arguments
  228. parser = argparse.ArgumentParser()
  229. parser.add_argument(
  230. "--model", type=str, default="yolov8n_full_integer_quant.tflite", help="Input your TFLite model."
  231. )
  232. parser.add_argument("--img", type=str, default=str(ASSETS / "bus.jpg"), help="Path to input image.")
  233. parser.add_argument("--conf-thres", type=float, default=0.5, help="Confidence threshold")
  234. parser.add_argument("--iou-thres", type=float, default=0.5, help="NMS IoU threshold")
  235. args = parser.parse_args()
  236. # Create an instance of the Yolov8TFLite class with the specified arguments
  237. detection = Yolov8TFLite(args.model, args.img, args.conf_thres, args.iou_thres)
  238. # Perform object detection and obtain the output image
  239. output_image = detection.main()
  240. # Display the output image in a window
  241. cv2.imshow("Output", output_image)
  242. # Wait for a key press to exit
  243. cv2.waitKey(0)
Tip!

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

Comments

Loading...