main.py 11 KB

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