A class to perform object detection, image classification, image segmentation and pose estimation inference.
This class provides functionalities for loading models, configuring settings, uploading video files, and performing
real-time inference using Streamlit and Ultralytics YOLO models.
Attributes:
Name
Type
Description
st
module
Streamlit module for UI creation.
temp_dict
dict
Temporary dictionary to store the model path and other configuration.
def__init__(self,**kwargs:Any):""" Initialize the Inference class, checking Streamlit requirements and setting up the model path. Args: **kwargs (Any): Additional keyword arguments for model configuration. """check_requirements("streamlit>=1.29.0")# scope imports for faster ultralytics package load speedsimportstreamlitasstself.st=st# Reference to the Streamlit moduleself.source=None# Video source selection (webcam or video file)self.enable_trk=False# Flag to toggle object trackingself.conf=0.25# Confidence threshold for detectionself.iou=0.45# Intersection-over-Union (IoU) threshold for non-maximum suppressionself.org_frame=None# Container for the original frame displayself.ann_frame=None# Container for the annotated frame displayself.vid_file_name=None# Video file name or webcam indexself.selected_ind=[]# List of selected class indices for detectionself.model=None# YOLO model instanceself.temp_dict={"model":None,**kwargs}self.model_path=None# Model file pathifself.temp_dict["model"]isnotNone:self.model_path=self.temp_dict["model"]LOGGER.info(f"Ultralytics Solutions: ✅ {self.temp_dict}")
configure
configure()
Configure the model and load selected classes for inference.
Source code in ultralytics/solutions/streamlit_inference.py
defconfigure(self):"""Configure the model and load selected classes for inference."""# Add dropdown menu for model selectionavailable_models=[x.replace("yolo","YOLO")forxinGITHUB_ASSETS_STEMSifx.startswith("yolo11")]ifself.model_path:# If user provided the custom model, insert model without suffix as *.pt is added lateravailable_models.insert(0,self.model_path.split(".pt")[0])selected_model=self.st.sidebar.selectbox("Model",available_models)withself.st.spinner("Model is downloading..."):self.model=YOLO(f"{selected_model.lower()}.pt")# Load the YOLO modelclass_names=list(self.model.names.values())# Convert dictionary to list of class namesself.st.success("Model loaded successfully!")# Multiselect box with class names and get indices of selected classesselected_classes=self.st.sidebar.multiselect("Classes",class_names,default=class_names[:3])self.selected_ind=[class_names.index(option)foroptioninselected_classes]ifnotisinstance(self.selected_ind,list):# Ensure selected_options is a listself.selected_ind=list(self.selected_ind)
inference
inference()
Perform real-time object detection inference on video or webcam feed.
Source code in ultralytics/solutions/streamlit_inference.py
definference(self):"""Perform real-time object detection inference on video or webcam feed."""self.web_ui()# Initialize the web interfaceself.sidebar()# Create the sidebarself.source_upload()# Upload the video sourceself.configure()# Configure the appifself.st.sidebar.button("Start"):stop_button=self.st.button("Stop")# Button to stop the inferencecap=cv2.VideoCapture(self.vid_file_name)# Capture the videoifnotcap.isOpened():self.st.error("Could not open webcam or video source.")returnwhilecap.isOpened():success,frame=cap.read()ifnotsuccess:self.st.warning("Failed to read frame from webcam. Please verify the webcam is connected properly.")break# Process frame with modelifself.enable_trk=="Yes":results=self.model.track(frame,conf=self.conf,iou=self.iou,classes=self.selected_ind,persist=True)else:results=self.model(frame,conf=self.conf,iou=self.iou,classes=self.selected_ind)annotated_frame=results[0].plot()# Add annotations on frameifstop_button:cap.release()# Release the captureself.st.stop()# Stop streamlit appself.org_frame.image(frame,channels="BGR")# Display original frameself.ann_frame.image(annotated_frame,channels="BGR")# Display processed framecap.release()# Release the capturecv2.destroyAllWindows()# Destroy all OpenCV windows
sidebar
sidebar()
Configure the Streamlit sidebar for model and inference settings.
Source code in ultralytics/solutions/streamlit_inference.py
defsidebar(self):"""Configure the Streamlit sidebar for model and inference settings."""withself.st.sidebar:# Add Ultralytics LOGOlogo="https://raw.githubusercontent.com/ultralytics/assets/main/logo/Ultralytics_Logotype_Original.svg"self.st.image(logo,width=250)self.st.sidebar.title("User Configuration")# Add elements to vertical setting menuself.source=self.st.sidebar.selectbox("Video",("webcam","video"),)# Add source selection dropdownself.enable_trk=self.st.sidebar.radio("Enable Tracking",("Yes","No"))# Enable object trackingself.conf=float(self.st.sidebar.slider("Confidence Threshold",0.0,1.0,self.conf,0.01))# Slider for confidenceself.iou=float(self.st.sidebar.slider("IoU Threshold",0.0,1.0,self.iou,0.01))# Slider for NMS thresholdcol1,col2=self.st.columns(2)# Create two columns for displaying framesself.org_frame=col1.empty()# Container for original frameself.ann_frame=col2.empty()# Container for annotated frame
source_upload
source_upload()
Handle video file uploads through the Streamlit interface.
Source code in ultralytics/solutions/streamlit_inference.py
defsource_upload(self):"""Handle video file uploads through the Streamlit interface."""self.vid_file_name=""ifself.source=="video":vid_file=self.st.sidebar.file_uploader("Upload Video File",type=["mp4","mov","avi","mkv"])ifvid_fileisnotNone:g=io.BytesIO(vid_file.read())# BytesIO Objectwithopen("ultralytics.mp4","wb")asout:# Open temporary file as bytesout.write(g.read())# Read bytes into fileself.vid_file_name="ultralytics.mp4"elifself.source=="webcam":self.vid_file_name=0# Use webcam index 0
web_ui
web_ui()
Sets up the Streamlit web interface with custom HTML elements.
Source code in ultralytics/solutions/streamlit_inference.py
defweb_ui(self):"""Sets up the Streamlit web interface with custom HTML elements."""menu_style_cfg="""<style>MainMenu {visibility: hidden;}</style>"""# Hide main menu style# Main title of streamlit applicationmain_title_cfg="""<div><h1 style="color:#FF64DA; text-align:center; font-size:40px; margin-top:-50px; font-family: 'Archivo', sans-serif; margin-bottom:20px;">Ultralytics YOLO Streamlit Application</h1></div>"""# Subtitle of streamlit applicationsub_title_cfg="""<div><h4 style="color:#042AFF; text-align:center; font-family: 'Archivo', sans-serif; margin-top:-15px; margin-bottom:50px;">Experience real-time object detection on your webcam with the power of Ultralytics YOLO! 🚀</h4></div>"""# Set html page configuration and append custom HTMLself.st.set_page_config(page_title="Ultralytics Streamlit App",layout="wide")self.st.markdown(menu_style_cfg,unsafe_allow_html=True)self.st.markdown(main_title_cfg,unsafe_allow_html=True)self.st.markdown(sub_title_cfg,unsafe_allow_html=True)