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

#18534 Create .dockerignore

Merged
Glenn Jocher merged 1 commits into Ultralytics:main from ultralytics:dockerignore
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
  1. # Ultralytics YOLO ๐Ÿš€, AGPL-3.0 license
  2. import io
  3. from typing import Any
  4. import cv2
  5. from ultralytics import YOLO
  6. from ultralytics.utils import LOGGER
  7. from ultralytics.utils.checks import check_requirements
  8. from ultralytics.utils.downloads import GITHUB_ASSETS_STEMS
  9. class Inference:
  10. """
  11. A class to perform object detection, image classification, image segmentation and pose estimation inference using
  12. Streamlit and Ultralytics YOLO models. It provides the functionalities such as loading models, configuring settings,
  13. uploading video files, and performing real-time inference.
  14. Attributes:
  15. st (module): Streamlit module for UI creation.
  16. temp_dict (dict): Temporary dictionary to store the model path.
  17. model_path (str): Path to the loaded model.
  18. model (YOLO): The YOLO model instance.
  19. source (str): Selected video source.
  20. enable_trk (str): Enable tracking option.
  21. conf (float): Confidence threshold.
  22. iou (float): IoU threshold for non-max suppression.
  23. vid_file_name (str): Name of the uploaded video file.
  24. selected_ind (list): List of selected class indices.
  25. Methods:
  26. web_ui: Sets up the Streamlit web interface with custom HTML elements.
  27. sidebar: Configures the Streamlit sidebar for model and inference settings.
  28. source_upload: Handles video file uploads through the Streamlit interface.
  29. configure: Configures the model and loads selected classes for inference.
  30. inference: Performs real-time object detection inference.
  31. Examples:
  32. >>> inf = solutions.Inference(model="path/to/model.pt") # Model is not necessary argument.
  33. >>> inf.inference()
  34. """
  35. def __init__(self, **kwargs: Any):
  36. """
  37. Initializes the Inference class, checking Streamlit requirements and setting up the model path.
  38. Args:
  39. **kwargs (Any): Additional keyword arguments for model configuration.
  40. """
  41. check_requirements("streamlit>=1.29.0") # scope imports for faster ultralytics package load speeds
  42. import streamlit as st
  43. self.st = st # Reference to the Streamlit class instance
  44. self.source = None # Placeholder for video or webcam source details
  45. self.enable_trk = False # Flag to toggle object tracking
  46. self.conf = 0.25 # Confidence threshold for detection
  47. self.iou = 0.45 # Intersection-over-Union (IoU) threshold for non-maximum suppression
  48. self.org_frame = None # Container for the original frame to be displayed
  49. self.ann_frame = None # Container for the annotated frame to be displayed
  50. self.vid_file_name = None # Holds the name of the video file
  51. self.selected_ind = [] # List of selected classes for detection or tracking
  52. self.model = None # Container for the loaded model instance
  53. self.temp_dict = {"model": None} # Temporary dict to store the model path
  54. self.temp_dict.update(kwargs)
  55. self.model_path = None # Store model file name with path
  56. if self.temp_dict["model"] is not None:
  57. self.model_path = self.temp_dict["model"]
  58. LOGGER.info(f"Ultralytics Solutions: โœ… {self.temp_dict}")
  59. def web_ui(self):
  60. """Sets up the Streamlit web interface with custom HTML elements."""
  61. menu_style_cfg = """<style>MainMenu {visibility: hidden;}</style>""" # Hide main menu style
  62. # Main title of streamlit application
  63. main_title_cfg = """<div><h1 style="color:#FF64DA; text-align:center; font-size:40px; margin-top:-50px;
  64. font-family: 'Archivo', sans-serif; margin-bottom:20px;">Ultralytics YOLO Streamlit Application</h1></div>"""
  65. # Subtitle of streamlit application
  66. sub_title_cfg = """<div><h4 style="color:#042AFF; text-align:center; font-family: 'Archivo', sans-serif;
  67. margin-top:-15px; margin-bottom:50px;">Experience real-time object detection on your webcam with the power
  68. of Ultralytics YOLO! ๐Ÿš€</h4></div>"""
  69. # Set html page configuration and append custom HTML
  70. self.st.set_page_config(page_title="Ultralytics Streamlit App", layout="wide")
  71. self.st.markdown(menu_style_cfg, unsafe_allow_html=True)
  72. self.st.markdown(main_title_cfg, unsafe_allow_html=True)
  73. self.st.markdown(sub_title_cfg, unsafe_allow_html=True)
  74. def sidebar(self):
  75. """Configures the Streamlit sidebar for model and inference settings."""
  76. with self.st.sidebar: # Add Ultralytics LOGO
  77. logo = "https://raw.githubusercontent.com/ultralytics/assets/main/logo/Ultralytics_Logotype_Original.svg"
  78. self.st.image(logo, width=250)
  79. self.st.sidebar.title("User Configuration") # Add elements to vertical setting menu
  80. self.source = self.st.sidebar.selectbox(
  81. "Video",
  82. ("webcam", "video"),
  83. ) # Add source selection dropdown
  84. self.enable_trk = self.st.sidebar.radio("Enable Tracking", ("Yes", "No")) # Enable object tracking
  85. self.conf = float(
  86. self.st.sidebar.slider("Confidence Threshold", 0.0, 1.0, self.conf, 0.01)
  87. ) # Slider for confidence
  88. self.iou = float(self.st.sidebar.slider("IoU Threshold", 0.0, 1.0, self.iou, 0.01)) # Slider for NMS threshold
  89. col1, col2 = self.st.columns(2)
  90. self.org_frame = col1.empty()
  91. self.ann_frame = col2.empty()
  92. def source_upload(self):
  93. """Handles video file uploads through the Streamlit interface."""
  94. self.vid_file_name = ""
  95. if self.source == "video":
  96. vid_file = self.st.sidebar.file_uploader("Upload Video File", type=["mp4", "mov", "avi", "mkv"])
  97. if vid_file is not None:
  98. g = io.BytesIO(vid_file.read()) # BytesIO Object
  99. with open("ultralytics.mp4", "wb") as out: # Open temporary file as bytes
  100. out.write(g.read()) # Read bytes into file
  101. self.vid_file_name = "ultralytics.mp4"
  102. elif self.source == "webcam":
  103. self.vid_file_name = 0
  104. def configure(self):
  105. """Configures the model and loads selected classes for inference."""
  106. # Add dropdown menu for model selection
  107. available_models = [x.replace("yolo", "YOLO") for x in GITHUB_ASSETS_STEMS if x.startswith("yolo11")]
  108. if self.model_path: # If user provided the custom model, insert model without suffix as *.pt is added later
  109. available_models.insert(0, self.model_path.split(".pt")[0])
  110. selected_model = self.st.sidebar.selectbox("Model", available_models)
  111. with self.st.spinner("Model is downloading..."):
  112. self.model = YOLO(f"{selected_model.lower()}.pt") # Load the YOLO model
  113. class_names = list(self.model.names.values()) # Convert dictionary to list of class names
  114. self.st.success("Model loaded successfully!")
  115. # Multiselect box with class names and get indices of selected classes
  116. selected_classes = self.st.sidebar.multiselect("Classes", class_names, default=class_names[:3])
  117. self.selected_ind = [class_names.index(option) for option in selected_classes]
  118. if not isinstance(self.selected_ind, list): # Ensure selected_options is a list
  119. self.selected_ind = list(self.selected_ind)
  120. def inference(self):
  121. """Performs real-time object detection inference."""
  122. self.web_ui() # Initialize the web interface
  123. self.sidebar() # Create the sidebar
  124. self.source_upload() # Upload the video source
  125. self.configure() # Configure the app
  126. if self.st.sidebar.button("Start"):
  127. stop_button = self.st.button("Stop") # Button to stop the inference
  128. cap = cv2.VideoCapture(self.vid_file_name) # Capture the video
  129. if not cap.isOpened():
  130. self.st.error("Could not open webcam.")
  131. while cap.isOpened():
  132. success, frame = cap.read()
  133. if not success:
  134. self.st.warning("Failed to read frame from webcam. Please verify the webcam is connected properly.")
  135. break
  136. # Store model predictions
  137. if self.enable_trk == "Yes":
  138. results = self.model.track(
  139. frame, conf=self.conf, iou=self.iou, classes=self.selected_ind, persist=True
  140. )
  141. else:
  142. results = self.model(frame, conf=self.conf, iou=self.iou, classes=self.selected_ind)
  143. annotated_frame = results[0].plot() # Add annotations on frame
  144. if stop_button:
  145. cap.release() # Release the capture
  146. self.st.stop() # Stop streamlit app
  147. self.org_frame.image(frame, channels="BGR") # Display original frame
  148. self.ann_frame.image(annotated_frame, channels="BGR") # Display processed frame
  149. cap.release() # Release the capture
  150. cv2.destroyAllWindows() # Destroy window
  151. if __name__ == "__main__":
  152. import sys # Import the sys module for accessing command-line arguments
  153. model = None # Initialize the model variable as None
  154. # Check if a model name is provided as a command-line argument
  155. args = len(sys.argv)
  156. if args > 1:
  157. model = sys.argv[1] # Assign the first argument as the model name
  158. # Create an instance of the Inference class and run inference
  159. Inference(model=model).inference()
Discard
Tip!

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