main.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import argparse
  3. from typing import Tuple, Union
  4. import cv2
  5. import numpy as np
  6. import tensorflow as tf
  7. import yaml
  8. from ultralytics.utils import ASSETS
  9. try:
  10. from tflite_runtime.interpreter import Interpreter
  11. except ImportError:
  12. import tensorflow as tf
  13. Interpreter = tf.lite.Interpreter
  14. class YOLOv8TFLite:
  15. """
  16. YOLOv8TFLite.
  17. A class for performing object detection using the YOLOv8 model with TensorFlow Lite.
  18. Attributes:
  19. model (str): Path to the TensorFlow Lite model file.
  20. conf (float): Confidence threshold for filtering detections.
  21. iou (float): Intersection over Union threshold for non-maximum suppression.
  22. metadata (Optional[str]): Path to the metadata file, if any.
  23. Methods:
  24. detect(img_path: str) -> np.ndarray:
  25. Performs inference and returns the output image with drawn detections.
  26. """
  27. def __init__(self, model: str, conf: float = 0.25, iou: float = 0.45, metadata: Union[str, None] = None):
  28. """
  29. Initializes an instance of the YOLOv8TFLite class.
  30. Args:
  31. model (str): Path to the TFLite model.
  32. conf (float, optional): Confidence threshold for filtering detections. Defaults to 0.25.
  33. iou (float, optional): IoU (Intersection over Union) threshold for non-maximum suppression. Defaults to 0.45.
  34. metadata (Union[str, None], optional): Path to the metadata file or None if not used. Defaults to None.
  35. """
  36. self.conf = conf
  37. self.iou = iou
  38. if metadata is None:
  39. self.classes = {i: i for i in range(1000)}
  40. else:
  41. with open(metadata) as f:
  42. self.classes = yaml.safe_load(f)["names"]
  43. np.random.seed(42)
  44. self.color_palette = np.random.uniform(128, 255, size=(len(self.classes), 3))
  45. self.model = Interpreter(model_path=model)
  46. self.model.allocate_tensors()
  47. input_details = self.model.get_input_details()[0]
  48. self.in_width, self.in_height = input_details["shape"][1:3]
  49. self.in_index = input_details["index"]
  50. self.in_scale, self.in_zero_point = input_details["quantization"]
  51. self.int8 = input_details["dtype"] == np.int8
  52. output_details = self.model.get_output_details()[0]
  53. self.out_index = output_details["index"]
  54. self.out_scale, self.out_zero_point = output_details["quantization"]
  55. def letterbox(self, img: np.ndarray, new_shape: Tuple = (640, 640)) -> Tuple[np.ndarray, Tuple[float, float]]:
  56. """Resizes and reshapes images while maintaining aspect ratio by adding padding, suitable for YOLO models."""
  57. shape = img.shape[:2] # current shape [height, width]
  58. # Scale ratio (new / old)
  59. r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
  60. # Compute padding
  61. new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
  62. dw, dh = (new_shape[1] - new_unpad[0]) / 2, (new_shape[0] - new_unpad[1]) / 2 # wh padding
  63. if shape[::-1] != new_unpad: # resize
  64. img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
  65. top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
  66. left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
  67. img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114))
  68. return img, (top / img.shape[0], left / img.shape[1])
  69. def draw_detections(self, img: np.ndarray, box: np.ndarray, score: np.float32, class_id: int) -> None:
  70. """
  71. Draws bounding boxes and labels on the input image based on the detected objects.
  72. Args:
  73. img (np.ndarray): The input image to draw detections on.
  74. box (np.ndarray): Detected bounding box in the format [x1, y1, width, height].
  75. score (np.float32): Corresponding detection score.
  76. class_id (int): Class ID for the detected object.
  77. Returns:
  78. None
  79. """
  80. x1, y1, w, h = box
  81. color = self.color_palette[class_id]
  82. cv2.rectangle(img, (int(x1), int(y1)), (int(x1 + w), int(y1 + h)), color, 2)
  83. label = f"{self.classes[class_id]}: {score:.2f}"
  84. (label_width, label_height), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
  85. label_x = x1
  86. label_y = y1 - 10 if y1 - 10 > label_height else y1 + 10
  87. cv2.rectangle(
  88. img,
  89. (int(label_x), int(label_y - label_height)),
  90. (int(label_x + label_width), int(label_y + label_height)),
  91. color,
  92. cv2.FILLED,
  93. )
  94. cv2.putText(img, label, (int(label_x), int(label_y)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)
  95. def preprocess(self, img: np.ndarray) -> Tuple[np.ndarray, Tuple[float, float]]:
  96. """
  97. Preprocesses the input image before performing inference.
  98. Args:
  99. img (np.ndarray): The input image to be preprocessed.
  100. Returns:
  101. Tuple[np.ndarray, Tuple[float, float]]: A tuple containing:
  102. - The preprocessed image (np.ndarray).
  103. - A tuple of two float values representing the padding applied (top/bottom, left/right).
  104. """
  105. img, pad = self.letterbox(img, (self.in_width, self.in_height))
  106. img = img[..., ::-1][None] # N,H,W,C for TFLite
  107. img = np.ascontiguousarray(img)
  108. img = img.astype(np.float32)
  109. return img / 255, pad
  110. def postprocess(self, img: np.ndarray, outputs: np.ndarray, pad: Tuple[float, float]) -> np.ndarray:
  111. """
  112. Performs post-processing on the model's output to extract bounding boxes, scores, and class IDs.
  113. Args:
  114. img (numpy.ndarray): The input image.
  115. outputs (numpy.ndarray): The output of the model.
  116. pad (Tuple[float, float]): Padding used by letterbox.
  117. Returns:
  118. numpy.ndarray: The input image with detections drawn on it.
  119. """
  120. outputs[:, 0] -= pad[1]
  121. outputs[:, 1] -= pad[0]
  122. outputs[:, :4] *= max(img.shape)
  123. outputs = outputs.transpose(0, 2, 1)
  124. outputs[..., 0] -= outputs[..., 2] / 2
  125. outputs[..., 1] -= outputs[..., 3] / 2
  126. for out in outputs:
  127. scores = out[:, 4:].max(-1)
  128. keep = scores > self.conf
  129. boxes = out[keep, :4]
  130. scores = scores[keep]
  131. class_ids = out[keep, 4:].argmax(-1)
  132. indices = cv2.dnn.NMSBoxes(boxes, scores, self.conf, self.iou).flatten()
  133. [self.draw_detections(img, boxes[i], scores[i], class_ids[i]) for i in indices]
  134. return img
  135. def detect(self, img_path: str) -> np.ndarray:
  136. """
  137. Performs inference using a TFLite model and returns the output image with drawn detections.
  138. Args:
  139. img_path (str): The path to the input image file.
  140. Returns:
  141. np.ndarray: The output image with drawn detections.
  142. """
  143. img = cv2.imread(img_path)
  144. x, pad = self.preprocess(img)
  145. if self.int8:
  146. x = (x / self.in_scale + self.in_zero_point).astype(np.int8)
  147. self.model.set_tensor(self.in_index, x)
  148. self.model.invoke()
  149. y = self.model.get_tensor(self.out_index)
  150. if self.int8:
  151. y = (y.astype(np.float32) - self.out_zero_point) * self.out_scale
  152. return self.postprocess(img, y, pad)
  153. if __name__ == "__main__":
  154. parser = argparse.ArgumentParser()
  155. parser.add_argument(
  156. "--model",
  157. type=str,
  158. default="yolov8n_saved_model/yolov8n_full_integer_quant.tflite",
  159. help="Path to TFLite model.",
  160. )
  161. parser.add_argument("--img", type=str, default=str(ASSETS / "bus.jpg"), help="Path to input image")
  162. parser.add_argument("--conf", type=float, default=0.25, help="Confidence threshold")
  163. parser.add_argument("--iou", type=float, default=0.45, help="NMS IoU threshold")
  164. parser.add_argument("--metadata", type=str, default="yolov8n_saved_model/metadata.yaml", help="Metadata yaml")
  165. args = parser.parse_args()
  166. detector = YOLOv8TFLite(args.model, args.conf, args.iou, args.metadata)
  167. result = detector.detect(str(ASSETS / "bus.jpg"))
  168. cv2.imshow("Output", result)
  169. cv2.waitKey(0)