Ultralytics/YOLO26
33
1# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license2 3import tempfile4from pathlib import Path5 6import cv27import gradio as gr8import numpy as np9import PIL.Image as Image10from ultralytics import YOLO11 12MODEL_CHOICES = [13 "yolo26n",14 "yolo26s",15 "yolo26m",16 "yolo26n-seg",17 "yolo26s-seg",18 "yolo26m-seg",19 "yolo26n-sem",20 "yolo26s-sem",21 "yolo26m-sem",22 "yolo26n-pose",23 "yolo26s-pose",24 "yolo26m-pose",25 "yolo26n-obb",26 "yolo26s-obb",27 "yolo26m-obb",28 "yolo26n-cls",29 "yolo26s-cls",30 "yolo26m-cls",31]32 33IMAGE_SIZE_CHOICES = [320, 640, 1024]34CUSTOM_CSS = (Path(__file__).parent / "ultralytics.css").read_text()35 36 37def predict_image(img, conf_threshold, iou_threshold, model_name, show_labels, show_conf, imgsz):38 """Predicts objects in an image using a Ultralytics YOLO model with adjustable confidence and IOU thresholds."""39 model = YOLO(model_name)40 results = model.predict(41 source=img,42 conf=conf_threshold,43 iou=iou_threshold,44 imgsz=imgsz,45 verbose=False,46 )47 48 for r in results:49 im_array = r.plot(labels=show_labels, conf=show_conf)50 im = Image.fromarray(im_array[..., ::-1])51 52 return im53 54 55def predict_video(video_path, conf_threshold, iou_threshold, model_name, show_labels, show_conf, imgsz):56 """Predicts objects in a video using a Ultralytics YOLO model and returns the annotated video."""57 if video_path is None:58 return None59 60 model = YOLO(model_name)61 62 # Open the video63 cap = cv2.VideoCapture(video_path)64 if not cap.isOpened():65 return None66 67 # Get video properties68 fps = int(cap.get(cv2.CAP_PROP_FPS))69 width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))70 height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))71 72 # Create temporary output file73 temp_output = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)74 output_path = temp_output.name75 temp_output.close()76 77 # Initialize video writer78 fourcc = cv2.VideoWriter_fourcc(*"mp4v")79 out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))80 81 while True:82 ret, frame = cap.read()83 if not ret:84 break85 86 # Run inference on the frame87 results = model.predict(88 source=frame,89 conf=conf_threshold,90 iou=iou_threshold,91 imgsz=imgsz,92 verbose=False,93 )94 95 # Get the annotated frame96 annotated_frame = results[0].plot(labels=show_labels, conf=show_conf)97 out.write(annotated_frame)98 99 cap.release()100 out.release()101 102 return output_path103 104 105# Cache model for streaming performance106_model_cache = {}107 108 109def get_model(model_name):110 """Get or create a cached model instance."""111 if model_name not in _model_cache:112 _model_cache[model_name] = YOLO(model_name)113 return _model_cache[model_name]114 115 116def predict_webcam(frame, conf_threshold, iou_threshold, model_name, show_labels, show_conf, imgsz):117 """Predicts objects in a webcam frame using a Ultralytics YOLO model (optimized for streaming)."""118 if frame is None:119 return None120 121 # Use cached model for better streaming performance122 model = get_model(model_name)123 124 if isinstance(frame, np.ndarray):125 # Gradio webcam sends RGB, but Ultralytics YOLO expects BGR for OpenCV operations126 # Convert RGB to BGR for YOLO127 frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)128 129 # Run inference130 results = model.predict(131 source=frame_bgr,132 conf=conf_threshold,133 iou=iou_threshold,134 imgsz=imgsz,135 verbose=False,136 )137 138 # YOLO's plot() returns BGR, convert back to RGB for Gradio display139 annotated_frame = results[0].plot(labels=show_labels, conf=show_conf)140 # Convert BGR to RGB for Gradio141 return cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB)142 143 return None144 145 146# Create the Gradio app with tabs147with gr.Blocks(title="Ultralytics YOLO26 Inference 🚀") as demo:148 gr.Markdown(149 """150<div align="center">151 <p>152 <a href="https://platform.ultralytics.com/?utm_source=huggingface&utm_medium=referral&utm_campaign=yolo26&utm_content=banner" target="_blank">153 <img width="50%" src="https://raw.githubusercontent.com/ultralytics/assets/main/yolov8/banner-yolov8.png" alt="Ultralytics YOLO banner"></a>154 </p>155 <p style="margin: 3px 0;">156 <a href="https://docs.ultralytics.com/zh/">中文</a> | <a href="https://docs.ultralytics.com/ko/">한국어</a> | <a href="https://docs.ultralytics.com/ja/">日本語</a> | <a href="https://docs.ultralytics.com/ru/">Русский</a> | <a href="https://docs.ultralytics.com/de/">Deutsch</a> | <a href="https://docs.ultralytics.com/fr/">Français</a> | <a href="https://docs.ultralytics.com/es">Español</a> | <a href="https://docs.ultralytics.com/pt/">Português</a> | <a href="https://docs.ultralytics.com/tr/">Türkçe</a> | <a href="https://docs.ultralytics.com/vi/">Tiếng Việt</a> | <a href="https://docs.ultralytics.com/ar/">العربية</a>157 </p>158 159 <div style="display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: 3px; margin-top: 3px;">160 <a href="https://github.com/ultralytics/ultralytics/actions/workflows/ci.yml"><img src="https://github.com/ultralytics/ultralytics/actions/workflows/ci.yml/badge.svg" alt="Ultralytics CI"></a>161 <a href="https://pepy.tech/projects/ultralytics"><img src="https://static.pepy.tech/badge/ultralytics" alt="Ultralytics Downloads"></a>162 <a href="https://arxiv.org/abs/2511.09554"><img src="https://img.shields.io/badge/arXiv-2511.09554-b31b1b.svg" alt="Ultralytics YOLO Citation"></a>163 <a href="https://discord.com/invite/ultralytics"><img alt="Ultralytics Discord" src="https://img.shields.io/discord/1089800235347353640?logo=discord&logoColor=white&label=Discord&color=blue"></a>164 <a href="https://community.ultralytics.com/"><img alt="Ultralytics Forums" src="https://img.shields.io/discourse/users?server=https%3A%2F%2Fcommunity.ultralytics.com&logo=discourse&label=Forums&color=blue"></a>165 <a href="https://www.reddit.com/r/ultralytics/"><img alt="Ultralytics Reddit" src="https://img.shields.io/reddit/subreddit-subscribers/ultralytics?style=flat&logo=reddit&logoColor=white&label=Reddit&color=blue"></a>166 </div>167 <div style="display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: 3px; margin-top: 3px;">168 <a href="https://console.paperspace.com/github/ultralytics/ultralytics"><img src="https://assets.paperspace.io/img/gradient-badge.svg" alt="Run Ultralytics on Gradient"></a>169 <a href="https://colab.research.google.com/github/ultralytics/ultralytics/blob/main/examples/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open Ultralytics In Colab"></a>170 <a href="https://www.kaggle.com/models/ultralytics/yolo26"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open Ultralytics In Kaggle"></a>171 <a href="https://mybinder.org/v2/gh/ultralytics/ultralytics/HEAD?labpath=examples%2Ftutorial.ipynb"><img src="https://mybinder.org/badge_logo.svg" alt="Open Ultralytics In Binder"></a>172 </div>173</div>174 175[Ultralytics](https://www.ultralytics.com/?utm_source=huggingface&utm_medium=referral&utm_campaign=yolo26&utm_content=contextual) [YOLO26](https://platform.ultralytics.com/ultralytics/yolo26?utm_source=huggingface&utm_medium=referral&utm_campaign=yolo26&utm_content=contextual_model_link) is the latest evolution in the YOLO series of real-time object detectors, engineered from the ground up for edge and low-power devices. It introduces a streamlined design that removes unnecessary complexity while integrating targeted innovations to deliver faster, lighter, and more accessible deployment.176"""177 )178 179 with gr.Tabs():180 # Image Tab181 with gr.TabItem("📷 Image"):182 with gr.Row():183 with gr.Column():184 img_input = gr.Image(type="pil", label="Upload Image")185 img_conf = gr.Slider(minimum=0, maximum=1, value=0.25, label="Confidence threshold")186 img_iou = gr.Slider(minimum=0, maximum=1, value=0.7, label="IoU threshold")187 img_model = gr.Radio(choices=MODEL_CHOICES, label="Model Name", value="yolo26n")188 img_labels = gr.Checkbox(value=True, label="Show Labels")189 img_conf_show = gr.Checkbox(value=True, label="Show Confidence")190 img_size = gr.Radio(choices=IMAGE_SIZE_CHOICES, label="Image Size", value=640)191 img_btn = gr.Button("Detect Objects", variant="primary")192 with gr.Column():193 img_output = gr.Image(type="pil", label="Result")194 195 img_btn.click(196 predict_image,197 inputs=[img_input, img_conf, img_iou, img_model, img_labels, img_conf_show, img_size],198 outputs=img_output,199 )200 201 gr.Examples(202 examples=[203 ["https://ultralytics.com/images/bus.jpg", 0.25, 0.7, "yolo26n", True, True, 640],204 ["https://ultralytics.com/images/zidane.jpg", 0.25, 0.7, "yolo26n-seg", True, True, 640],205 ["https://ultralytics.com/images/boats.jpg", 0.25, 0.7, "yolo26n-obb", True, True, 1024],206 ],207 inputs=[img_input, img_conf, img_iou, img_model, img_labels, img_conf_show, img_size],208 )209 210 # Video Tab211 with gr.TabItem("🎬 Video"):212 with gr.Row():213 with gr.Column():214 vid_input = gr.Video(label="Upload Video")215 vid_conf = gr.Slider(minimum=0, maximum=1, value=0.25, label="Confidence threshold")216 vid_iou = gr.Slider(minimum=0, maximum=1, value=0.7, label="IoU threshold")217 vid_model = gr.Radio(choices=MODEL_CHOICES, label="Model Name", value="yolo26n")218 vid_labels = gr.Checkbox(value=True, label="Show Labels")219 vid_conf_show = gr.Checkbox(value=True, label="Show Confidence")220 vid_size = gr.Radio(choices=IMAGE_SIZE_CHOICES, label="Image Size", value=640)221 vid_btn = gr.Button("Process Video", variant="primary")222 with gr.Column():223 vid_output = gr.Video(label="Result")224 225 vid_btn.click(226 predict_video,227 inputs=[vid_input, vid_conf, vid_iou, vid_model, vid_labels, vid_conf_show, vid_size],228 outputs=vid_output,229 )230 231 # Webcam Tab - Real-time streaming232 with gr.TabItem("📹 Webcam"):233 gr.Markdown("### Real-time Webcam Detection")234 gr.Markdown("Enable streaming for live detection as you move!")235 with gr.Row():236 with gr.Column():237 webcam_conf = gr.Slider(minimum=0, maximum=1, value=0.25, label="Confidence threshold")238 webcam_iou = gr.Slider(minimum=0, maximum=1, value=0.7, label="IoU threshold")239 webcam_model = gr.Radio(choices=MODEL_CHOICES, label="Model Name", value="yolo26n")240 webcam_labels = gr.Checkbox(value=True, label="Show Labels")241 webcam_conf_show = gr.Checkbox(value=True, label="Show Confidence")242 webcam_size = gr.Radio(choices=IMAGE_SIZE_CHOICES, label="Image Size", value=640)243 with gr.Column():244 # Streaming webcam input with real-time output245 webcam_input = gr.Image(246 sources=["webcam"],247 type="numpy",248 label="Webcam (streaming)",249 streaming=True,250 )251 webcam_output = gr.Image(type="numpy", label="Detection Result")252 253 # Stream event for real-time detection254 webcam_input.stream(255 predict_webcam,256 inputs=[257 webcam_input,258 webcam_conf,259 webcam_iou,260 webcam_model,261 webcam_labels,262 webcam_conf_show,263 webcam_size,264 ],265 outputs=webcam_output,266 )267 268demo.launch(css=CUSTOM_CSS, ssr_mode=False)269 