ultralytics 8.3.53__py3-none-any.whl → 8.3.54__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tests/test_solutions.py CHANGED
@@ -82,4 +82,4 @@ def test_instance_segmentation():
82
82
  @pytest.mark.slow
83
83
  def test_streamlit_predict():
84
84
  """Test streamlit predict live inference solution."""
85
- solutions.inference()
85
+ solutions.Inference().inference()
ultralytics/__init__.py CHANGED
@@ -1,6 +1,6 @@
1
1
  # Ultralytics YOLO 🚀, AGPL-3.0 license
2
2
 
3
- __version__ = "8.3.53"
3
+ __version__ = "8.3.54"
4
4
 
5
5
  import os
6
6
 
@@ -42,6 +42,7 @@ SOLUTION_MAP = {
42
42
  "workout": ("AIGym", "monitor"),
43
43
  "analytics": ("Analytics", "process_data"),
44
44
  "trackzone": ("TrackZone", "trackzone"),
45
+ "inference": ("Inference", "inference"),
45
46
  "help": None,
46
47
  }
47
48
 
@@ -97,7 +98,10 @@ SOLUTIONS_HELP_MSG = f"""
97
98
  yolo solutions analytics analytics_type="pie"
98
99
 
99
100
  6. Track objects within specific zones
100
- yolo solutions trackzone source="path/to/video/file.mp4" region=[(150, 150), (1130, 150), (1130, 570), (150, 570)]
101
+ yolo solutions trackzone source="path/to/video/file.mp4" region=[(150, 150), (1130, 150), (1130, 570), (150, 570)]
102
+
103
+ 7. Streamlit real-time webcam inference GUI
104
+ yolo streamlit-predict
101
105
  """
102
106
  CLI_HELP_MSG = f"""
103
107
  Arguments received: {str(['yolo'] + ARGV[1:])}. Ultralytics 'yolo' commands use the following syntax:
@@ -121,13 +125,10 @@ CLI_HELP_MSG = f"""
121
125
  4. Export a YOLO11n classification model to ONNX format at image size 224 by 128 (no TASK required)
122
126
  yolo export model=yolo11n-cls.pt format=onnx imgsz=224,128
123
127
 
124
- 5. Streamlit real-time webcam inference GUI
125
- yolo streamlit-predict
126
-
127
- 6. Ultralytics solutions usage
128
+ 5. Ultralytics solutions usage
128
129
  yolo solutions count or in {list(SOLUTION_MAP.keys())[1:-1]} source="path/to/video/file.mp4"
129
130
 
130
- 7. Run special commands:
131
+ 6. Run special commands:
131
132
  yolo help
132
133
  yolo checks
133
134
  yolo version
@@ -636,6 +637,9 @@ def handle_yolo_solutions(args: List[str]) -> None:
636
637
  Run analytics with custom configuration:
637
638
  >>> handle_yolo_solutions(["analytics", "conf=0.25", "source=path/to/video/file.mp4"])
638
639
 
640
+ Run inference with custom configuration, requires Streamlit version 1.29.0 or higher.
641
+ >>> handle_yolo_solutions(["inference", "model=yolo11n.pt"])
642
+
639
643
  Notes:
640
644
  - Default configurations are merged from DEFAULT_SOL_DICT and DEFAULT_CFG_DICT
641
645
  - Arguments can be provided in the format 'key=value' or as boolean flags
@@ -645,7 +649,9 @@ def handle_yolo_solutions(args: List[str]) -> None:
645
649
  - For 'analytics' solution, frame numbers are tracked for generating analytical graphs
646
650
  - Video processing can be interrupted by pressing 'q'
647
651
  - Processes video frames sequentially and saves output in .avi format
648
- - If no source is specified, downloads and uses a default sample video
652
+ - If no source is specified, downloads and uses a default sample video\
653
+ - The inference solution will be launched using the 'streamlit run' command.
654
+ - The Streamlit app file is located in the Ultralytics package directory.
649
655
  """
650
656
  full_args_dict = {**DEFAULT_SOL_DICT, **DEFAULT_CFG_DICT} # arguments dictionary
651
657
  overrides = {}
@@ -678,60 +684,56 @@ def handle_yolo_solutions(args: List[str]) -> None:
678
684
  if args and args[0] == "help": # Add check for return if user call `yolo solutions help`
679
685
  return
680
686
 
681
- cls, method = SOLUTION_MAP[s_n] # solution class name, method name and default source
682
-
683
- from ultralytics import solutions # import ultralytics solutions
684
-
685
- solution = getattr(solutions, cls)(IS_CLI=True, **overrides) # get solution class i.e ObjectCounter
686
- process = getattr(solution, method) # get specific function of class for processing i.e, count from ObjectCounter
687
-
688
- cap = cv2.VideoCapture(solution.CFG["source"]) # read the video file
689
-
690
- # extract width, height and fps of the video file, create save directory and initialize video writer
691
- import os # for directory creation
692
- from pathlib import Path
693
-
694
- from ultralytics.utils.files import increment_path # for output directory path update
687
+ if s_n == "inference":
688
+ checks.check_requirements("streamlit>=1.29.0")
689
+ LOGGER.info("💡 Loading Ultralytics live inference app...")
690
+ subprocess.run(
691
+ [ # Run subprocess with Streamlit custom argument
692
+ "streamlit",
693
+ "run",
694
+ str(ROOT / "solutions/streamlit_inference.py"),
695
+ "--server.headless",
696
+ "true",
697
+ overrides["model"],
698
+ ]
699
+ )
700
+ else:
701
+ cls, method = SOLUTION_MAP[s_n] # solution class name, method name and default source
695
702
 
696
- w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
697
- if s_n == "analytics": # analytical graphs follow fixed shape for output i.e w=1920, h=1080
698
- w, h = 1920, 1080
699
- save_dir = increment_path(Path("runs") / "solutions" / "exp", exist_ok=False)
700
- save_dir.mkdir(parents=True, exist_ok=True) # create the output directory
701
- vw = cv2.VideoWriter(os.path.join(save_dir, "solution.avi"), cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
703
+ from ultralytics import solutions # import ultralytics solutions
702
704
 
703
- try: # Process video frames
704
- f_n = 0 # frame number, required for analytical graphs
705
- while cap.isOpened():
706
- success, frame = cap.read()
707
- if not success:
708
- break
709
- frame = process(frame, f_n := f_n + 1) if s_n == "analytics" else process(frame)
710
- vw.write(frame)
711
- if cv2.waitKey(1) & 0xFF == ord("q"):
712
- break
713
- finally:
714
- cap.release()
705
+ solution = getattr(solutions, cls)(IS_CLI=True, **overrides) # get solution class i.e ObjectCounter
706
+ process = getattr(
707
+ solution, method
708
+ ) # get specific function of class for processing i.e, count from ObjectCounter
715
709
 
710
+ cap = cv2.VideoCapture(solution.CFG["source"]) # read the video file
716
711
 
717
- def handle_streamlit_inference():
718
- """
719
- Open the Ultralytics Live Inference Streamlit app for real-time object detection.
712
+ # extract width, height and fps of the video file, create save directory and initialize video writer
713
+ import os # for directory creation
714
+ from pathlib import Path
720
715
 
721
- This function initializes and runs a Streamlit application designed for performing live object detection using
722
- Ultralytics models. It checks for the required Streamlit package and launches the app.
716
+ from ultralytics.utils.files import increment_path # for output directory path update
723
717
 
724
- Examples:
725
- >>> handle_streamlit_inference()
718
+ w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
719
+ if s_n == "analytics": # analytical graphs follow fixed shape for output i.e w=1920, h=1080
720
+ w, h = 1920, 1080
721
+ save_dir = increment_path(Path("runs") / "solutions" / "exp", exist_ok=False)
722
+ save_dir.mkdir(parents=True, exist_ok=True) # create the output directory
723
+ vw = cv2.VideoWriter(os.path.join(save_dir, "solution.avi"), cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
726
724
 
727
- Notes:
728
- - Requires Streamlit version 1.29.0 or higher.
729
- - The app is launched using the 'streamlit run' command.
730
- - The Streamlit app file is located in the Ultralytics package directory.
731
- """
732
- checks.check_requirements("streamlit>=1.29.0")
733
- LOGGER.info("💡 Loading Ultralytics Live Inference app...")
734
- subprocess.run(["streamlit", "run", ROOT / "solutions/streamlit_inference.py", "--server.headless", "true"])
725
+ try: # Process video frames
726
+ f_n = 0 # frame number, required for analytical graphs
727
+ while cap.isOpened():
728
+ success, frame = cap.read()
729
+ if not success:
730
+ break
731
+ frame = process(frame, f_n := f_n + 1) if s_n == "analytics" else process(frame)
732
+ vw.write(frame)
733
+ if cv2.waitKey(1) & 0xFF == ord("q"):
734
+ break
735
+ finally:
736
+ cap.release()
735
737
 
736
738
 
737
739
  def parse_key_value_pair(pair: str = "key=value"):
@@ -853,7 +855,6 @@ def entrypoint(debug=""):
853
855
  "login": lambda: handle_yolo_hub(args),
854
856
  "logout": lambda: handle_yolo_hub(args),
855
857
  "copy-cfg": copy_default_cfg,
856
- "streamlit-predict": lambda: handle_streamlit_inference(),
857
858
  "solutions": lambda: handle_yolo_solutions(args[1:]),
858
859
  }
859
860
  full_args_dict = {**DEFAULT_CFG_DICT, **{k: None for k in TASKS}, **{k: None for k in MODES}, **special}
@@ -102,19 +102,19 @@ def export_formats():
102
102
  """Ultralytics YOLO export formats."""
103
103
  x = [
104
104
  ["PyTorch", "-", ".pt", True, True, []],
105
- ["TorchScript", "torchscript", ".torchscript", True, True, ["optimize", "batch"]],
106
- ["ONNX", "onnx", ".onnx", True, True, ["half", "dynamic", "simplify", "opset", "batch"]],
107
- ["OpenVINO", "openvino", "_openvino_model", True, False, ["half", "int8", "batch"]],
108
- ["TensorRT", "engine", ".engine", False, True, ["half", "dynamic", "simplify", "int8", "batch"]],
109
- ["CoreML", "coreml", ".mlpackage", True, False, ["half", "int8", "nms", "batch"]],
110
- ["TensorFlow SavedModel", "saved_model", "_saved_model", True, True, ["keras", "int8", "batch"]],
105
+ ["TorchScript", "torchscript", ".torchscript", True, True, ["batch", "optimize"]],
106
+ ["ONNX", "onnx", ".onnx", True, True, ["batch", "dynamic", "half", "opset", "simplify"]],
107
+ ["OpenVINO", "openvino", "_openvino_model", True, False, ["batch", "dynamic", "half", "int8"]],
108
+ ["TensorRT", "engine", ".engine", False, True, ["batch", "dynamic", "half", "int8", "simplify"]],
109
+ ["CoreML", "coreml", ".mlpackage", True, False, ["batch", "half", "int8", "nms"]],
110
+ ["TensorFlow SavedModel", "saved_model", "_saved_model", True, True, ["batch", "int8", "keras"]],
111
111
  ["TensorFlow GraphDef", "pb", ".pb", True, True, ["batch"]],
112
- ["TensorFlow Lite", "tflite", ".tflite", True, False, ["half", "int8", "batch"]],
112
+ ["TensorFlow Lite", "tflite", ".tflite", True, False, ["batch", "half", "int8"]],
113
113
  ["TensorFlow Edge TPU", "edgetpu", "_edgetpu.tflite", True, False, []],
114
- ["TensorFlow.js", "tfjs", "_web_model", True, False, ["half", "int8", "batch"]],
114
+ ["TensorFlow.js", "tfjs", "_web_model", True, False, ["batch", "half", "int8"]],
115
115
  ["PaddlePaddle", "paddle", "_paddle_model", True, True, ["batch"]],
116
- ["MNN", "mnn", ".mnn", True, True, ["batch", "int8", "half"]],
117
- ["NCNN", "ncnn", "_ncnn_model", True, True, ["half", "batch"]],
116
+ ["MNN", "mnn", ".mnn", True, True, ["batch", "half", "int8"]],
117
+ ["NCNN", "ncnn", "_ncnn_model", True, True, ["batch", "half"]],
118
118
  ["IMX", "imx", "_imx_model", True, True, ["int8"]],
119
119
  ]
120
120
  return dict(zip(["Format", "Argument", "Suffix", "CPU", "GPU", "Arguments"], zip(*x)))
@@ -10,7 +10,7 @@ from .queue_management import QueueManager
10
10
  from .region_counter import RegionCounter
11
11
  from .security_alarm import SecurityAlarm
12
12
  from .speed_estimation import SpeedEstimator
13
- from .streamlit_inference import inference
13
+ from .streamlit_inference import Inference
14
14
  from .trackzone import TrackZone
15
15
 
16
16
  __all__ = (
@@ -23,7 +23,7 @@ __all__ = (
23
23
  "QueueManager",
24
24
  "SpeedEstimator",
25
25
  "Analytics",
26
- "inference",
26
+ "Inference",
27
27
  "RegionCounter",
28
28
  "TrackZone",
29
29
  "SecurityAlarm",
@@ -5,7 +5,9 @@ import json
5
5
  import cv2
6
6
  import numpy as np
7
7
 
8
- from ultralytics.solutions.solutions import LOGGER, BaseSolution, check_requirements
8
+ from ultralytics.solutions.solutions import BaseSolution
9
+ from ultralytics.utils import LOGGER
10
+ from ultralytics.utils.checks import check_requirements
9
11
  from ultralytics.utils.plotting import Annotator
10
12
 
11
13
 
@@ -1,6 +1,7 @@
1
1
  # Ultralytics YOLO 🚀, AGPL-3.0 license
2
2
 
3
- from ultralytics.solutions.solutions import LOGGER, BaseSolution
3
+ from ultralytics.solutions.solutions import BaseSolution
4
+ from ultralytics.utils import LOGGER
4
5
  from ultralytics.utils.plotting import Annotator, colors
5
6
 
6
7
 
@@ -4,145 +4,188 @@ import io
4
4
  import time
5
5
 
6
6
  import cv2
7
- import torch
8
7
 
8
+ from ultralytics import YOLO
9
+ from ultralytics.utils import LOGGER
9
10
  from ultralytics.utils.checks import check_requirements
10
11
  from ultralytics.utils.downloads import GITHUB_ASSETS_STEMS
11
12
 
12
13
 
13
- def inference(model=None):
14
- """Performs real-time object detection on video input using YOLO in a Streamlit web application."""
15
- check_requirements("streamlit>=1.29.0") # scope imports for faster ultralytics package load speeds
16
- import streamlit as st
17
-
18
- from ultralytics import YOLO
19
-
20
- # Hide main menu style
21
- menu_style_cfg = """<style>MainMenu {visibility: hidden;}</style>"""
22
-
23
- # Main title of streamlit application
24
- main_title_cfg = """<div><h1 style="color:#FF64DA; text-align:center; font-size:40px;
25
- font-family: 'Archivo', sans-serif; margin-top:-50px;margin-bottom:20px;">
26
- Ultralytics YOLO Streamlit Application
27
- </h1></div>"""
28
-
29
- # Subtitle of streamlit application
30
- sub_title_cfg = """<div><h4 style="color:#042AFF; text-align:center;
31
- font-family: 'Archivo', sans-serif; margin-top:-15px; margin-bottom:50px;">
32
- Experience real-time object detection on your webcam with the power of Ultralytics YOLO! 🚀</h4>
33
- </div>"""
34
-
35
- # Set html page configuration
36
- st.set_page_config(page_title="Ultralytics Streamlit App", layout="wide", initial_sidebar_state="auto")
37
-
38
- # Append the custom HTML
39
- st.markdown(menu_style_cfg, unsafe_allow_html=True)
40
- st.markdown(main_title_cfg, unsafe_allow_html=True)
41
- st.markdown(sub_title_cfg, unsafe_allow_html=True)
42
-
43
- # Add ultralytics logo in sidebar
44
- with st.sidebar:
45
- logo = "https://raw.githubusercontent.com/ultralytics/assets/main/logo/Ultralytics_Logotype_Original.svg"
46
- st.image(logo, width=250)
14
+ class Inference:
15
+ """
16
+ A class to perform object detection, image classification, image segmentation and pose estimation inference using
17
+ Streamlit and Ultralytics YOLO models. It provides the functionalities such as loading models, configuring settings,
18
+ uploading video files, and performing real-time inference.
19
+
20
+ Attributes:
21
+ st (module): Streamlit module for UI creation.
22
+ temp_dict (dict): Temporary dictionary to store the model path.
23
+ model_path (str): Path to the loaded model.
24
+ model (YOLO): The YOLO model instance.
25
+ source (str): Selected video source.
26
+ enable_trk (str): Enable tracking option.
27
+ conf (float): Confidence threshold.
28
+ iou (float): IoU threshold for non-max suppression.
29
+ vid_file_name (str): Name of the uploaded video file.
30
+ selected_ind (list): List of selected class indices.
31
+
32
+ Methods:
33
+ web_ui: Sets up the Streamlit web interface with custom HTML elements.
34
+ sidebar: Configures the Streamlit sidebar for model and inference settings.
35
+ source_upload: Handles video file uploads through the Streamlit interface.
36
+ configure: Configures the model and loads selected classes for inference.
37
+ inference: Performs real-time object detection inference.
38
+
39
+ Examples:
40
+ >>> inf = solutions.Inference(model="path/to/model/file.pt") # Model is not necessary argument.
41
+ >>> inf.inference()
42
+ """
43
+
44
+ def __init__(self, **kwargs):
45
+ """
46
+ Initializes the Inference class, checking Streamlit requirements and setting up the model path.
47
+
48
+ Args:
49
+ **kwargs (Dict): Additional keyword arguments for model configuration.
50
+ """
51
+ check_requirements("streamlit>=1.29.0") # scope imports for faster ultralytics package load speeds
52
+ import streamlit as st
53
+
54
+ self.st = st
55
+
56
+ self.temp_dict = {"model": None} # Temporary dict to store the model path
57
+ self.temp_dict.update(kwargs)
58
+
59
+ self.model_path = None # Store model file name with path
60
+ if self.temp_dict["model"] is not None:
61
+ self.model_path = self.temp_dict["model"]
62
+
63
+ LOGGER.info(f"Ultralytics Solutions: ✅ {self.temp_dict}")
64
+
65
+ def web_ui(self):
66
+ """Sets up the Streamlit web interface with custom HTML elements."""
67
+ menu_style_cfg = """<style>MainMenu {visibility: hidden;}</style>""" # Hide main menu style
68
+
69
+ # Main title of streamlit application
70
+ main_title_cfg = """<div><h1 style="color:#FF64DA; text-align:center; font-size:40px; margin-top:-50px;
71
+ font-family: 'Archivo', sans-serif; margin-bottom:20px;">Ultralytics YOLO Streamlit Application</h1></div>"""
72
+
73
+ # Subtitle of streamlit application
74
+ sub_title_cfg = """<div><h4 style="color:#042AFF; text-align:center; font-family: 'Archivo', sans-serif;
75
+ margin-top:-15px; margin-bottom:50px;">Experience real-time object detection on your webcam with the power
76
+ of Ultralytics YOLO! 🚀</h4></div>"""
77
+
78
+ # Set html page configuration and append custom HTML
79
+ self.st.set_page_config(page_title="Ultralytics Streamlit App", layout="wide", initial_sidebar_state="auto")
80
+ self.st.markdown(menu_style_cfg, unsafe_allow_html=True)
81
+ self.st.markdown(main_title_cfg, unsafe_allow_html=True)
82
+ self.st.markdown(sub_title_cfg, unsafe_allow_html=True)
83
+
84
+ def sidebar(self):
85
+ """Configures the Streamlit sidebar for model and inference settings."""
86
+ with self.st.sidebar: # Add Ultralytics LOGO
87
+ logo = "https://raw.githubusercontent.com/ultralytics/assets/main/logo/Ultralytics_Logotype_Original.svg"
88
+ self.st.image(logo, width=250)
89
+
90
+ self.st.sidebar.title("User Configuration") # Add elements to vertical setting menu
91
+ self.source = self.st.sidebar.selectbox(
92
+ "Video",
93
+ ("webcam", "video"),
94
+ ) # Add source selection dropdown
95
+ self.enable_trk = self.st.sidebar.radio("Enable Tracking", ("Yes", "No")) # Enable object tracking
96
+ self.conf = float(self.st.sidebar.slider("Confidence Threshold", 0.0, 1.0, 0.25, 0.01)) # Slider for confidence
97
+ self.iou = float(self.st.sidebar.slider("IoU Threshold", 0.0, 1.0, 0.45, 0.01)) # Slider for NMS threshold
98
+
99
+ col1, col2 = self.st.columns(2)
100
+ self.org_frame = col1.empty()
101
+ self.ann_frame = col2.empty()
102
+ self.fps_display = self.st.sidebar.empty() # Placeholder for FPS display
103
+
104
+ def source_upload(self):
105
+ """Handles video file uploads through the Streamlit interface."""
106
+ self.vid_file_name = ""
107
+ if self.source == "video":
108
+ vid_file = self.st.sidebar.file_uploader("Upload Video File", type=["mp4", "mov", "avi", "mkv"])
109
+ if vid_file is not None:
110
+ g = io.BytesIO(vid_file.read()) # BytesIO Object
111
+ with open("ultralytics.mp4", "wb") as out: # Open temporary file as bytes
112
+ out.write(g.read()) # Read bytes into file
113
+ self.vid_file_name = "ultralytics.mp4"
114
+ elif self.source == "webcam":
115
+ self.vid_file_name = 0
116
+
117
+ def configure(self):
118
+ """Configures the model and loads selected classes for inference."""
119
+ # Add dropdown menu for model selection
120
+ available_models = [x.replace("yolo", "YOLO") for x in GITHUB_ASSETS_STEMS if x.startswith("yolo11")]
121
+ if self.model_path: # If user provided the custom model, insert model without suffix as *.pt is added later
122
+ available_models.insert(0, self.model_path.split(".pt")[0])
123
+ selected_model = self.st.sidebar.selectbox("Model", available_models)
124
+
125
+ with self.st.spinner("Model is downloading..."):
126
+ self.model = YOLO(f"{selected_model.lower()}.pt") # Load the YOLO model
127
+ class_names = list(self.model.names.values()) # Convert dictionary to list of class names
128
+ self.st.success("Model loaded successfully!")
129
+
130
+ # Multiselect box with class names and get indices of selected classes
131
+ selected_classes = self.st.sidebar.multiselect("Classes", class_names, default=class_names[:3])
132
+ self.selected_ind = [class_names.index(option) for option in selected_classes]
133
+
134
+ if not isinstance(self.selected_ind, list): # Ensure selected_options is a list
135
+ self.selected_ind = list(self.selected_ind)
136
+
137
+ def inference(self):
138
+ """Performs real-time object detection inference."""
139
+ self.web_ui() # Initialize the web interface
140
+ self.sidebar() # Create the sidebar
141
+ self.source_upload() # Upload the video source
142
+ self.configure() # Configure the app
143
+
144
+ if self.st.sidebar.button("Start"):
145
+ stop_button = self.st.button("Stop") # Button to stop the inference
146
+ cap = cv2.VideoCapture(self.vid_file_name) # Capture the video
147
+ if not cap.isOpened():
148
+ self.st.error("Could not open webcam.")
149
+ while cap.isOpened():
150
+ success, frame = cap.read()
151
+ if not success:
152
+ st.warning("Failed to read frame from webcam. Please make sure the webcam is connected properly.")
153
+ break
154
+
155
+ prev_time = time.time() # Store initial time for FPS calculation
156
+
157
+ # Store model predictions
158
+ if self.enable_trk == "Yes":
159
+ results = self.model.track(
160
+ frame, conf=self.conf, iou=self.iou, classes=self.selected_ind, persist=True
161
+ )
162
+ else:
163
+ results = self.model(frame, conf=self.conf, iou=self.iou, classes=self.selected_ind)
164
+ annotated_frame = results[0].plot() # Add annotations on frame
165
+
166
+ fps = 1 / (time.time() - prev_time) # Calculate model FPS
167
+
168
+ if stop_button:
169
+ cap.release() # Release the capture
170
+ self.st.stop() # Stop streamlit app
171
+
172
+ self.fps_display.metric("FPS", f"{fps:.2f}") # Display FPS in sidebar
173
+ self.org_frame.image(frame, channels="BGR") # Display original frame
174
+ self.ann_frame.image(annotated_frame, channels="BGR") # Display processed frame
175
+
176
+ cap.release() # Release the capture
177
+ cv2.destroyAllWindows() # Destroy window
47
178
 
48
- # Add elements to vertical setting menu
49
- st.sidebar.title("User Configuration")
50
179
 
51
- # Add video source selection dropdown
52
- source = st.sidebar.selectbox(
53
- "Video",
54
- ("webcam", "video"),
55
- )
56
-
57
- vid_file_name = ""
58
- if source == "video":
59
- vid_file = st.sidebar.file_uploader("Upload Video File", type=["mp4", "mov", "avi", "mkv"])
60
- if vid_file is not None:
61
- g = io.BytesIO(vid_file.read()) # BytesIO Object
62
- vid_location = "ultralytics.mp4"
63
- with open(vid_location, "wb") as out: # Open temporary file as bytes
64
- out.write(g.read()) # Read bytes into file
65
- vid_file_name = "ultralytics.mp4"
66
- elif source == "webcam":
67
- vid_file_name = 0
68
-
69
- # Add dropdown menu for model selection
70
- available_models = [x.replace("yolo", "YOLO") for x in GITHUB_ASSETS_STEMS if x.startswith("yolo11")]
71
- if model:
72
- available_models.insert(0, model.split(".pt")[0]) # insert model without suffix as *.pt is added later
73
-
74
- selected_model = st.sidebar.selectbox("Model", available_models)
75
- with st.spinner("Model is downloading..."):
76
- model = YOLO(f"{selected_model.lower()}.pt") # Load the YOLO model
77
- class_names = list(model.names.values()) # Convert dictionary to list of class names
78
- st.success("Model loaded successfully!")
79
-
80
- # Multiselect box with class names and get indices of selected classes
81
- selected_classes = st.sidebar.multiselect("Classes", class_names, default=class_names[:3])
82
- selected_ind = [class_names.index(option) for option in selected_classes]
83
-
84
- if not isinstance(selected_ind, list): # Ensure selected_options is a list
85
- selected_ind = list(selected_ind)
86
-
87
- enable_trk = st.sidebar.radio("Enable Tracking", ("Yes", "No"))
88
- conf = float(st.sidebar.slider("Confidence Threshold", 0.0, 1.0, 0.25, 0.01))
89
- iou = float(st.sidebar.slider("IoU Threshold", 0.0, 1.0, 0.45, 0.01))
90
-
91
- col1, col2 = st.columns(2)
92
- org_frame = col1.empty()
93
- ann_frame = col2.empty()
94
-
95
- fps_display = st.sidebar.empty() # Placeholder for FPS display
96
-
97
- if st.sidebar.button("Start"):
98
- videocapture = cv2.VideoCapture(vid_file_name) # Capture the video
99
-
100
- if not videocapture.isOpened():
101
- st.error("Could not open webcam.")
102
-
103
- stop_button = st.button("Stop") # Button to stop the inference
104
-
105
- while videocapture.isOpened():
106
- success, frame = videocapture.read()
107
- if not success:
108
- st.warning("Failed to read frame from webcam. Please make sure the webcam is connected properly.")
109
- break
110
-
111
- prev_time = time.time() # Store initial time for FPS calculation
112
-
113
- # Store model predictions
114
- if enable_trk == "Yes":
115
- results = model.track(frame, conf=conf, iou=iou, classes=selected_ind, persist=True)
116
- else:
117
- results = model(frame, conf=conf, iou=iou, classes=selected_ind)
118
- annotated_frame = results[0].plot() # Add annotations on frame
119
-
120
- # Calculate model FPS
121
- curr_time = time.time()
122
- fps = 1 / (curr_time - prev_time)
123
-
124
- # display frame
125
- org_frame.image(frame, channels="BGR")
126
- ann_frame.image(annotated_frame, channels="BGR")
127
-
128
- if stop_button:
129
- videocapture.release() # Release the capture
130
- torch.cuda.empty_cache() # Clear CUDA memory
131
- st.stop() # Stop streamlit app
132
-
133
- # Display FPS in sidebar
134
- fps_display.metric("FPS", f"{fps:.2f}")
135
-
136
- # Release the capture
137
- videocapture.release()
138
-
139
- # Clear CUDA memory
140
- torch.cuda.empty_cache()
180
+ if __name__ == "__main__":
181
+ import sys # Import the sys module for accessing command-line arguments
141
182
 
142
- # Destroy window
143
- cv2.destroyAllWindows()
183
+ model = None # Initialize the model variable as None
144
184
 
185
+ # Check if a model name is provided as a command-line argument
186
+ args = len(sys.argv)
187
+ if args > 1:
188
+ model = args # Assign the first argument as the model name
145
189
 
146
- # Main function call
147
- if __name__ == "__main__":
148
- inference()
190
+ # Create an instance of the Inference class and run inference
191
+ Inference(model=model).inference()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ultralytics
3
- Version: 8.3.53
3
+ Version: 8.3.54
4
4
  Summary: Ultralytics YOLO 🚀 for SOTA object detection, multi-object tracking, instance segmentation, pose estimation and image classification.
5
5
  Author-email: Glenn Jocher <glenn.jocher@ultralytics.com>, Jing Qiu <jing.qiu@ultralytics.com>
6
6
  Maintainer-email: Ultralytics <hello@ultralytics.com>
@@ -143,7 +143,7 @@ See below for a quickstart install and usage examples, and see our [Docs](https:
143
143
  <details open>
144
144
  <summary>Install</summary>
145
145
 
146
- Pip install the ultralytics package including all [requirements](https://github.com/ultralytics/ultralytics/blob/main/pyproject.toml) in a [**Python>=3.8**](https://www.python.org/) environment with [**PyTorch>=1.8**](https://pytorch.org/get-started/locally/).
146
+ Pip install the Ultralytics package including all [requirements](https://github.com/ultralytics/ultralytics/blob/main/pyproject.toml) in a [**Python>=3.8**](https://www.python.org/) environment with [**PyTorch>=1.8**](https://pytorch.org/get-started/locally/).
147
147
 
148
148
  [![PyPI - Version](https://img.shields.io/pypi/v/ultralytics?logo=pypi&logoColor=white)](https://pypi.org/project/ultralytics/) [![Ultralytics Downloads](https://static.pepy.tech/badge/ultralytics)](https://www.pepy.tech/projects/ultralytics) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/ultralytics?logo=python&logoColor=gold)](https://pypi.org/project/ultralytics/)
149
149
 
@@ -6,11 +6,11 @@ tests/test_engine.py,sha256=dcEcJsMQh61rDSNv7l4TIAgybLpzjVwerv9JZC_KCM8,4934
6
6
  tests/test_exports.py,sha256=1MvhcQ2qHdbJImHII-bFarcaIcm-kPlEK-OdFLxnj7o,8769
7
7
  tests/test_integrations.py,sha256=f5-QCUk1SU_-qn4mBCZwS3GN3tXEBIIXo4z2EhExbHw,6126
8
8
  tests/test_python.py,sha256=IfHAXqilpYxWNmIE6rAWWUSeIYS6SBO9AkXGHDGZTvA,23182
9
- tests/test_solutions.py,sha256=HlDe-XOgBX0k1cLhRTAhhawMHk6p-5dg5xl2AIRjfdk,3790
10
- ultralytics/__init__.py,sha256=kIIMpFWlMtP3bD2_KHobrs6DR7u8pD2YM-ZRZh7XiYw,681
9
+ tests/test_solutions.py,sha256=VShscutH1qk1sNIEsl_7bw-C_RMdbDgx-8BkIKr2qyw,3802
10
+ ultralytics/__init__.py,sha256=Vkgg4u34EmMW2oxDXs3Q6gqtjW4Tth3-wHXMyYdGfeM,681
11
11
  ultralytics/assets/bus.jpg,sha256=wCAZxJecGR63Od3ZRERe9Aja1Weayrb9Ug751DS_vGM,137419
12
12
  ultralytics/assets/zidane.jpg,sha256=Ftc4aeMmen1O0A3o6GCDO9FlfBslLpTAw0gnetx7bts,50427
13
- ultralytics/cfg/__init__.py,sha256=etGrRb8t9r6R-n-00qFAmOZHXNriXEUe0zvEzCPi5oc,38921
13
+ ultralytics/cfg/__init__.py,sha256=Tnd5809b0wmMOjVwyEc_4ZhlEGZEsLwMTHFcsBKBLB4,39009
14
14
  ultralytics/cfg/default.yaml,sha256=FcXbvTXXvMpssk9fSwdlnVTtyqfmlYE9gAcHsf0OMf8,8347
15
15
  ultralytics/cfg/datasets/Argoverse.yaml,sha256=FyeuJT5CHq_9d4hlfAf0kpZlnbUMO0S--UJ1yIqcdKk,3134
16
16
  ultralytics/cfg/datasets/DOTAv1.5.yaml,sha256=QVfp_Qp-4rukuicaB4qx86NxSHM8Mrzym8l_fIDo8gw,1195
@@ -100,7 +100,7 @@ ultralytics/data/loaders.py,sha256=k1Vq7Rxv6tpsRsYuMdZeI3_f2BciAaZwhDQU8iHhVJM,2
100
100
  ultralytics/data/split_dota.py,sha256=eFafJ7Vg52wj6KDCHFJAf1tKzyPD5YaPB8kM4VX5Aeg,10688
101
101
  ultralytics/data/utils.py,sha256=bmWEIrdogj4kssZQSJdSbIF8QsJU00lo-EY-Mgcqv4M,31073
102
102
  ultralytics/engine/__init__.py,sha256=mHtJuK4hwF8cuV-VHDc7tp6u6D1gHz2Z7JI8grmQDTs,42
103
- ultralytics/engine/exporter.py,sha256=I7SP_ftvggxca37OioYysOsD1f0c8jAhHTiKVUtlGAA,68602
103
+ ultralytics/engine/exporter.py,sha256=kt8pICda-2M_ICse1EW3uVif63qo6dO4tyf4L3UljrM,68613
104
104
  ultralytics/engine/model.py,sha256=l5UiXGBa4ox9BXq0dc6eUsOvd85Q4KHUxGCwY2dfXQE,53113
105
105
  ultralytics/engine/predictor.py,sha256=o1RYMFH3_uVOMCIXXakpRYpNzoD-6Bdsxryt5fuBni0,17712
106
106
  ultralytics/engine/results.py,sha256=a1XFZRPwqgKDBOEAibHuT9nP2xefLiWVsMoBJbcr4iA,75058
@@ -179,19 +179,19 @@ ultralytics/nn/modules/conv.py,sha256=DPLZCRno_ZOjsuajAXIq-GbJdOh2jp1WayRXfDEd8z
179
179
  ultralytics/nn/modules/head.py,sha256=yZdDr71pWm-vB18XrNkbX35o3q4o4mhzrfJz6yVh9m4,27934
180
180
  ultralytics/nn/modules/transformer.py,sha256=tGiK8NmPfswwW1rbF21r5ILUkkZQ6Nk4s8j16vFBmps,18069
181
181
  ultralytics/nn/modules/utils.py,sha256=a88cKl2wz1nMVSEBiajtvaCbDBQIkESWOKTZ_WAJy90,3195
182
- ultralytics/solutions/__init__.py,sha256=zsW-vYzuKM6QGfpEPACcK4RYx-MmoDiW1GjyHCQ_a64,824
182
+ ultralytics/solutions/__init__.py,sha256=3f_4nENBQ0Mh6wiVl6KCzAOQeonVdh1xuc3v0njJ-JQ,824
183
183
  ultralytics/solutions/ai_gym.py,sha256=Jv8ERJqcSjQeFh78zCAH2XnXoTIngCK7X_7XOQ6cPzs,5255
184
184
  ultralytics/solutions/analytics.py,sha256=C57pIghXeKN8hul8QOV7W9YDMpfFfSfPTBb-lE9HeAc,11535
185
185
  ultralytics/solutions/distance_calculation.py,sha256=KN3CC-dm2dTQylj79IrifCJT8ZhE7hc2EweH3KK31mE,5461
186
186
  ultralytics/solutions/heatmap.py,sha256=JkqwYAkIIDOj4HL5fLmcxQO0yix6-X8tAceXON6-Yg0,5275
187
187
  ultralytics/solutions/object_counter.py,sha256=MuxQG4a22458WwciAB96m5AxVXwH98AIWAaf_kPali4,9613
188
- ultralytics/solutions/parking_management.py,sha256=Hh28FTuP_TaO7x5RadYm-JSVJuEu1M2SSgHqgdYYtr8,11198
188
+ ultralytics/solutions/parking_management.py,sha256=m1wRDyLWoW3dNr0z8e39UPVZRt6q55dr_L82-FD5h5A,11263
189
189
  ultralytics/solutions/queue_management.py,sha256=lIHBgdMSKmGGPrICY2HC01_Ofad-vu4AnaGAqH-DxMs,4931
190
190
  ultralytics/solutions/region_counter.py,sha256=w0c0Sz9XG6rwzr5nA6nb1zFW8IVkTQuatfZNBtOik68,4947
191
- ultralytics/solutions/security_alarm.py,sha256=NgOt5qcz9RrzUw9RDuXKyYxYfJM_XDZ0trizbJ1Y8v4,5588
191
+ ultralytics/solutions/security_alarm.py,sha256=1gXpapUdA5_Flq6bqEg13CP0wEHS2Y_dnW6CVCtDqQs,5617
192
192
  ultralytics/solutions/solutions.py,sha256=BqkMDAq9A8kqL4TkjHLkMYXrJAdZPK-VAdNSObS1kNQ,7502
193
193
  ultralytics/solutions/speed_estimation.py,sha256=A10DmuZlGkoZUyfHhZWcDRjj1-9GXiDhEjyBbAzfaDs,4936
194
- ultralytics/solutions/streamlit_inference.py,sha256=w4dnvSv2FOrpji9W1Ir86phka3OXc7jd_38-OCbQdZw,5701
194
+ ultralytics/solutions/streamlit_inference.py,sha256=idqs_M8IbhTgh563wuDI9lGek6R7S1ms56rcL9239X8,9117
195
195
  ultralytics/solutions/trackzone.py,sha256=jsSuvW3ExoQl5JyUF-5ZLQMou8h4qbkCGGGP831cHSY,2952
196
196
  ultralytics/trackers/__init__.py,sha256=j72IgH2dZHQArMPK4YwcV5ieIw94fYvlGdQjB9cOQKw,227
197
197
  ultralytics/trackers/basetrack.py,sha256=kPOeAX2ihvANtQJk-zUsN0C7JjhlJbx0UhjaCFk_ovQ,4423
@@ -231,9 +231,9 @@ ultralytics/utils/callbacks/neptune.py,sha256=IbGQfEltamUKXJt93uSLQFn8c2rYh3DMTg
231
231
  ultralytics/utils/callbacks/raytune.py,sha256=Ck_yFzg7UZXiDWrLHaltjQybzVWSFDfzpdrx9ZYTRfI,700
232
232
  ultralytics/utils/callbacks/tensorboard.py,sha256=SHlE58Fb-sg-uZKtgy-ybIO3SAIfK55aj8kTYGA0Cyg,4167
233
233
  ultralytics/utils/callbacks/wb.py,sha256=sizfTa-xI9k2pnDSP_Q9pHZEFwcl__gSFM0AcneuRpY,7058
234
- ultralytics-8.3.53.dist-info/LICENSE,sha256=DZak_2itbUtvHzD3E7GNUYSRK6jdOJ-GqncQ2weavLA,34523
235
- ultralytics-8.3.53.dist-info/METADATA,sha256=ZyhZIwrXh4Uuvibs25BhIC6ei4X9Kz-qtBBaciS4tZc,35332
236
- ultralytics-8.3.53.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
237
- ultralytics-8.3.53.dist-info/entry_points.txt,sha256=YM_wiKyTe9yRrsEfqvYolNO5ngwfoL4-NwgKzc8_7sI,93
238
- ultralytics-8.3.53.dist-info/top_level.txt,sha256=XP49TwiMw4QGsvTLSYiJhz1xF_k7ev5mQ8jJXaXi45Q,12
239
- ultralytics-8.3.53.dist-info/RECORD,,
234
+ ultralytics-8.3.54.dist-info/LICENSE,sha256=DZak_2itbUtvHzD3E7GNUYSRK6jdOJ-GqncQ2weavLA,34523
235
+ ultralytics-8.3.54.dist-info/METADATA,sha256=yrPbnbBywNWLmvWv7445QLjJ-FzZzWTw5goK-E0kwgo,35332
236
+ ultralytics-8.3.54.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
237
+ ultralytics-8.3.54.dist-info/entry_points.txt,sha256=YM_wiKyTe9yRrsEfqvYolNO5ngwfoL4-NwgKzc8_7sI,93
238
+ ultralytics-8.3.54.dist-info/top_level.txt,sha256=XP49TwiMw4QGsvTLSYiJhz1xF_k7ev5mQ8jJXaXi45Q,12
239
+ ultralytics-8.3.54.dist-info/RECORD,,