Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

yolov8_sahi.py 4.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
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import argparse
  3. from pathlib import Path
  4. import cv2
  5. from sahi import AutoDetectionModel
  6. from sahi.predict import get_sliced_prediction
  7. from sahi.utils.yolov8 import download_yolov8s_model
  8. from ultralytics.utils.files import increment_path
  9. from ultralytics.utils.plotting import Annotator, colors
  10. class SAHIInference:
  11. """Runs YOLOv8 and SAHI for object detection on video with options to view, save, and track results."""
  12. def __init__(self):
  13. """Initializes the SAHIInference class for performing sliced inference using SAHI with YOLOv8 models."""
  14. self.detection_model = None
  15. def load_model(self, weights):
  16. """Loads a YOLOv8 model with specified weights for object detection using SAHI."""
  17. yolov8_model_path = f"models/{weights}"
  18. download_yolov8s_model(yolov8_model_path)
  19. self.detection_model = AutoDetectionModel.from_pretrained(
  20. model_type="yolov8", model_path=yolov8_model_path, confidence_threshold=0.3, device="cpu"
  21. )
  22. def inference(
  23. self, weights="yolov8n.pt", source="test.mp4", view_img=False, save_img=False, exist_ok=False, track=False
  24. ):
  25. """
  26. Run object detection on a video using YOLOv8 and SAHI.
  27. Args:
  28. weights (str): Model weights path.
  29. source (str): Video file path.
  30. view_img (bool): Show results.
  31. save_img (bool): Save results.
  32. exist_ok (bool): Overwrite existing files.
  33. track (bool): Enable object tracking with SAHI
  34. """
  35. # Video setup
  36. cap = cv2.VideoCapture(source)
  37. assert cap.isOpened(), "Error reading video file"
  38. frame_width, frame_height = int(cap.get(3)), int(cap.get(4))
  39. # Output setup
  40. save_dir = increment_path(Path("ultralytics_results_with_sahi") / "exp", exist_ok)
  41. save_dir.mkdir(parents=True, exist_ok=True)
  42. video_writer = cv2.VideoWriter(
  43. str(save_dir / f"{Path(source).stem}.mp4"),
  44. cv2.VideoWriter_fourcc(*"mp4v"),
  45. int(cap.get(5)),
  46. (frame_width, frame_height),
  47. )
  48. # Load model
  49. self.load_model(weights)
  50. while cap.isOpened():
  51. success, frame = cap.read()
  52. if not success:
  53. break
  54. annotator = Annotator(frame) # Initialize annotator for plotting detection and tracking results
  55. results = get_sliced_prediction(
  56. frame,
  57. self.detection_model,
  58. slice_height=512,
  59. slice_width=512,
  60. overlap_height_ratio=0.2,
  61. overlap_width_ratio=0.2,
  62. )
  63. detection_data = [
  64. (det.category.name, det.category.id, (det.bbox.minx, det.bbox.miny, det.bbox.maxx, det.bbox.maxy))
  65. for det in results.object_prediction_list
  66. ]
  67. for det in detection_data:
  68. annotator.box_label(det[2], label=str(det[0]), color=colors(int(det[1]), True))
  69. if view_img:
  70. cv2.imshow(Path(source).stem, frame)
  71. if save_img:
  72. video_writer.write(frame)
  73. if cv2.waitKey(1) & 0xFF == ord("q"):
  74. break
  75. video_writer.release()
  76. cap.release()
  77. cv2.destroyAllWindows()
  78. def parse_opt(self):
  79. """Parse command line arguments."""
  80. parser = argparse.ArgumentParser()
  81. parser.add_argument("--weights", type=str, default="yolov8n.pt", help="initial weights path")
  82. parser.add_argument("--source", type=str, required=True, help="video file path")
  83. parser.add_argument("--view-img", action="store_true", help="show results")
  84. parser.add_argument("--save-img", action="store_true", help="save results")
  85. parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
  86. return parser.parse_args()
  87. if __name__ == "__main__":
  88. inference = SAHIInference()
  89. inference.inference(**vars(inference.parse_opt()))
Tip!

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

Comments

Loading...