Inferenza in tempo reale con un'applicazione Streamlit e Ultralytics YOLO26
Introduzione#
Streamlit semplifica la creazione e la distribuzione di applicazioni web interattive. La sua combinazione con Ultralytics YOLO26 consente di eseguire il rilevamento degli oggetti e l'analisi in tempo reale direttamente nel browser. La velocità e la precisione di YOLO26 lo rendono adatto ai flussi video in diretta per applicazioni come la sicurezza e la vendita al dettaglio.
Guarda: Come creare un'app di inferenza dal vivo con Ultralytics YOLO26 e Streamlit | Rilevamento e segmentazione 🚀
| Acquacoltura | Allevamento degli animali |
|---|---|
![]() | ![]() |
| Rilevamento dei pesci con Ultralytics YOLO26 | Rilevamento degli animali con Ultralytics YOLO26 |
Vantaggi dell'inferenza in tempo reale#
- Rilevamento degli oggetti in tempo reale: Streamlit, insieme a YOLO26, consente di rilevare gli oggetti in tempo reale direttamente dal flusso della webcam. In questo modo puoi ottenere analisi e informazioni immediate, una soluzione ideale per le applicazioni che richiedono un riscontro immediato.
- Distribuzione intuitiva: l'interfaccia interattiva di Streamlit semplifica la distribuzione e l'uso dell'applicazione, senza richiedere conoscenze tecniche approfondite. Gli utenti possono avviare l'inferenza in tempo reale con un semplice clic, migliorandone l'accessibilità e la facilità d'uso.
- Uso efficiente delle risorse: gli algoritmi ottimizzati di YOLO26 garantiscono un'elaborazione ad alta velocità con risorse computazionali minime. Questa efficienza consente un'inferenza fluida e affidabile dalla webcam anche su hardware standard, rendendo la visione artificiale avanzata accessibile a un pubblico più ampio.
Codice dell'applicazione Streamlit#
Prima di iniziare a creare l'applicazione, assicurati di aver installato il pacchetto Python Ultralytics.
pip install ultralyticsyolo solutions inference
yolo solutions inference model="path/to/model.pt"
yolo solutions help # list the available solution commands and argumentsQuesti comandi avviano l'interfaccia Streamlit predefinita inclusa in Ultralytics.
Verrà avviata l'applicazione Streamlit nel browser web predefinito. Vedrai il titolo principale, il sottotitolo e la barra laterale con le opzioni di configurazione. Seleziona il modello YOLO26 che preferisci, imposta le soglie NMS e fai clic sul pulsante "Start" per avviare il rilevamento degli oggetti in tempo reale.
Come funziona#
Dietro le quinte, l'applicazione Streamlit usa il modulo solutions di Ultralytics per creare un'interfaccia interattiva. Quando avvii l'inferenza, l'applicazione:
- Acquisisce fotogrammi dalla webcam, da un file video caricato o da immagini caricate
- Elabora ogni fotogramma con il modello YOLO26
- Applica il rilevamento degli oggetti con le soglie di confidenza e IoU specificate
- Visualizza in tempo reale sia i fotogrammi originali sia quelli annotati
- Abilita facoltativamente il tracciamento degli oggetti, se selezionato
L'applicazione offre un'interfaccia semplice e intuitiva con controlli per regolare i parametri del modello e avviare o interrompere l'inferenza in qualsiasi momento.
Conclusione#
Seguendo questa guida, hai creato un'applicazione di rilevamento degli oggetti in tempo reale con Streamlit e Ultralytics YOLO26. L'applicazione esegue YOLO26 sulla webcam, su un video o su un'immagine tramite un'interfaccia semplice, e puoi interrompere il flusso in qualsiasi momento.
Per ulteriori miglioramenti, puoi valutare l'aggiunta di altre funzionalità, come la registrazione del flusso video, il salvataggio dei fotogrammi annotati o l'integrazione con altre librerie di computer vision.
Domande frequenti#
Configurare un'applicazione per il rilevamento degli oggetti in tempo reale con Streamlit e Ultralytics YOLO26 è semplice. Per prima cosa, assicurati di aver installato il pacchetto Python Ultralytics con:
pip install ultralyticsPoi puoi creare una semplice applicazione Streamlit per eseguire l'inferenza dal vivo:
Applicazione Streamlitfrom ultralytics import solutions inf = solutions.Inference( model="yolo26n.pt", # puoi usare qualsiasi modello supportato da Ultralytics, ad esempio YOLO26, oppure un modello addestrato su misura ) inf.inference() # Assicurati di eseguire il file con il comando `streamlit run path/to/file.py`Per maggiori dettagli sulla configurazione pratica, consulta la sezione Codice dell'applicazione Streamlit della documentazione.
Usare Ultralytics YOLO26 con Streamlit per il rilevamento degli oggetti in tempo reale offre diversi vantaggi:
- Rilevamento in tempo reale: ottieni un rilevamento degli oggetti in tempo reale e ad alta precisione direttamente dai flussi della webcam.
- Interfaccia intuitiva: l'interfaccia intuitiva di Streamlit semplifica l'uso e la distribuzione senza richiedere competenze tecniche approfondite.
- Efficienza nell'uso delle risorse: gli algoritmi ottimizzati di YOLO26 garantiscono un'elaborazione ad alta velocità con risorse computazionali minime.
Scopri di più su questi vantaggi nella sezione Vantaggi dell'inferenza dal vivo.
Dopo aver scritto il codice dell'applicazione Streamlit integrando Ultralytics YOLO26, puoi distribuirla eseguendo:
streamlit run path/to/file.pyQuesto comando avvia l'applicazione nel browser web predefinito, consentendoti di selezionare i modelli YOLO26, impostare le soglie di confidenza e IoU e avviare il rilevamento degli oggetti in tempo reale con un semplice clic.
Il rilevamento degli oggetti in tempo reale con Streamlit e Ultralytics YOLO26 può essere applicato in diversi settori:
- Sicurezza: monitoraggio in tempo reale degli accessi non autorizzati e dei sistemi di allarme di sicurezza.
- Vendita al dettaglio: conteggio dei clienti, gestione degli scaffali e tracciamento dell'inventario.
- Fauna selvatica e agricoltura: monitoraggio degli animali e delle condizioni delle colture per le attività di conservazione.
Per altri casi d'uso ed esempi approfonditi, esplora Ultralytics Solutions.
Ultralytics YOLO26 offre diversi miglioramenti rispetto ai modelli precedenti, come YOLOv5 e i rilevatori della famiglia R-CNN:
- Maggiore velocità e precisione: prestazioni migliorate per le applicazioni in tempo reale.
- Facilità d'uso: interfacce e distribuzione semplificate.
- Efficienza nell'uso delle risorse: ottimizzato per offrire maggiore velocità con requisiti computazionali minimi.
Commenti26
Fai una domanda, condividi i tuoi risultati o aiuta qualcun altro.
j3dd4h
the manual execution using rknn model (yolo predict model='./best_rknn_model' source='ppe.jpg') is working but got an error when running under Streamlit.
TypeError: model='best_rknn_model/best-rk3588.rknn' is not a supported model format. Ultralytics supports: ('PyTorch', 'TorchScript', 'ONNX', 'OpenVINO', 'TensorRT', 'CoreML', 'TensorFlow SavedModel', 'TensorFlow GraphDef', 'TensorFlow Lite', 'TensorFlow Edge TPU', 'TensorFlow.js', 'PaddlePaddle', 'MNN', 'NCNN', 'IMX', 'RKNN') See https://docs.ultralytics.com/modes/predict for help.
1RizwanMunawar
@j3dd4h Hi, thanks for sharing the details. We currently don't support the rknn model, but you can adjust this check in code to make the application work for rknn models. We will add support for this soon.
j3dd4h
Ok, got it
RizwanMunawar
@j3dd4h opened the Pull request here: https://github.com/ultralytics/ultralytics/pull/22212
NNQHuong
AttributeError: module 'torch' has no attribute '__version__' Traceback: File "C:\Users\myname\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\streamlit\runtime\scriptrunner\exec_code.py", line 88, in exec_func_with_error_handling result = func() ^^^^^^ File "C:\Users\myname\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 579, in code_to_exec exec(code, module.__dict__) File "C:\WasteSegregation\app.py", line 1, in <module> from ultralytics import solutions File "C:\Users\myname\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\ultralytics\__init__.py", line 11, in <module> from ultralytics.models import NAS, RTDETR, SAM, YOLO, FastSAM, YOLOWorld File "C:\Users\myname\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\ultralytics\models\__init__.py", line 3, in <module> from .fastsam import FastSAM File "C:\Users\myname\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\ultralytics\models\fastsam\__init__.py", line 3, in <module> from .model import FastSAM File "C:\Users\myname\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\ultralytics\models\fastsam\model.py", line 5, in <module> from ultralytics.engine.model import Model File "C:\Users\myname\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\ultralytics\engine\model.py", line 11, in <module> from ultralytics.cfg import TASK2DATA, get_cfg, get_save_dir File "C:\Users\myname\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\ultralytics\cfg\__init__.py", line 12, in <module> from ultralytics.utils import ( File "C:\Users\myname\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\ultralytics\utils\__init__.py", line 51, in <module> TORCH_VERSION = torch.__version__ ^^^^^^^^^^^^^^^^^This is the error I encountered when usingfrom ultralytics import solutionssolutions.inference(model =r'C:path\to\my\model.pt')method (VSCode), can you please explain it to me? For further information, I've tried using the method for CLI and it works, but not with VSCode. I wonder if there's any method for CLI that allows me to use my custom trained model? It's YOLO11n-cls version. Thank you for reading this!1
Glenn JocherUltralytics@NNQHuong the error you're encountering suggests a possible issue with your PyTorch installation. Please verify that PyTorch is properly installed and compatible with your Python version by running:
import torch print(torch.__version__)If the error persists, ensure you're using the latest version of PyTorch and Ultralytics with:
pip install --upgrade torch ultralyticsRegarding your CLI query, you can use your custom-trained YOLO11 model by specifying the model path directly, like so:
yolo predict model=path/to/your/model.pt source=your_inputFor detailed examples, check the documentation here. Let me know if additional assistance is required!
2RizwanMunawar
Hi @NNQHuong, thank you for sharing the error log! It appears that the issue might be related to your PyTorch version. You may need to upgrade or downgrade it to ensure everything works correctly.
However, if this still doesn't resolve the issue, please share your code here for further testing.
Thanks, Ultralytics Team!
1NNQHuong
Thanks for your infomative reply, it worked smoothly! I'm kind of new to this field anyway, about 6 months , I bet you can see it in my words haha, so thanks for your patience too!
1
Tech-Watt
Is it posible to use different camera index ?. It picks up the default computer webcam and there's no means of changing it.
Glenn JocherUltralytics(modificato)The
Inferenceclass has nosourceargument: selecting "webcam" in the sidebar always opens camera index0(self.vid_file_name = 0inultralytics/solutions/streamlit_inference.py). To use a different camera, make it your system's default camera or change that index in the file:inf = solutions.Inference(model="yolo26n.pt") inf.inference()Run it with
streamlit run <file-name.py>.
Vectorvin
streamlit 这个解决方案可以使用tensorRT格式或者onnx格式吗?似乎程序被写死了
Glenn JocherUltralytics(modificato)@Vectorvin 您好!Streamlit 方案现在也支持导出的模型格式:除了
.pt,还可以把.onnx、.torchscript、.mlpackage、.engine(TensorRT)、OpenVINO 或 RKNN 模型路径传给solutions.Inference(model="yolo26n.engine")。导出步骤请参考导出文档。需要企业级部署支持请访问ultralytics.com/license。
sathyanarayanaRP
how does the streamlit gets is input , is it possible to push frames or is it possible to integrate machine vision cameras that does not support RTSP protocals. i need comprehensive knowledge how does it work as a streaming device
Glenn JocherUltralytics@sathyanarayanaRP streamlit can receive input directly from a webcam or video file. For cameras that don't support RTSP, you can use USB or other compatible connections. The Streamlit app processes frames in real-time, allowing for seamless integration with various camera types. For more details, please refer to the Streamlit documentation.
Cheikh-Ahmedand
hey!
Once I run the app my Laptop camera turns on, instead of My webcam. How to use my external webcam instead of my LAPTOP camera?
Best Regards!
Glenn JocherUltralytics(modificato)@Cheikh-Ahmedand the Streamlit app has no
sourceargument: choosing "webcam" in the sidebar always opens camera index0(self.vid_file_name = 0inultralytics/solutions/streamlit_inference.py). To use your external webcam, make it the system's default camera, or change that index to1(or the index of your webcam) in the file.Run the app with
yolo solutions inference, or withstreamlit run <file-name.py>for your own script.Cheikh-Ahmedand
Hey ! Thanks lot for your response, but the code couldn't work with streamlit code. I pasted the following code on my Laptop anconda PowerShell Prompt:
yolo streamlit-predict solutions.inference(source=1)
Still, my Webcam can't run, but my Laptop 's Camera.
Also, I tried the below code in jupyter notebook, but the problem still persists.
from ultralytics import solutions
solutions.inference() solutions.inference(source=1)
Make sure to run the file using command
streamlit run <file-name.py>Any help either from the Respectful Staff or others would be appreciated!!!
Glenn JocherUltralytics(modificato)@Cheikh-Ahmedand the Streamlit app has no
sourceargument: choosing "webcam" in the sidebar always opens camera index0(self.vid_file_name = 0inultralytics/solutions/streamlit_inference.py). To use an external webcam, set it as your system's default camera or change that index in the file. Run the app withyolo solutions inference, orstreamlit run <file-name.py>for your own script. If issues persist, please check your system's camera settings.
AdadAlShabab
Can you please provide the stramlit .py file that we need to run?
Glenn JocherUltralytics(modificato)@AdadAlShabab you can use the following code to run the Streamlit application for live inference:
from ultralytics import solutions inf = solutions.Inference(model="yolo26n.pt") inf.inference()Run the file with the command
streamlit run <file-name.py>. For more details, please refer to the Streamlit Live Inference Guide.
ghost
Thank you for your quick and kind response and the problem is sorted. But there is another issue while switching model to different task like pose,seg or cls and getting error of open cv not having func()
Glenn JocherUltralytics@Charan2128 i'm glad to hear the initial issue is resolved. Regarding the error with OpenCV when switching tasks (pose, seg, cls), please ensure you have the latest versions of both the Ultralytics package and OpenCV. You can update them using:
pip install --upgrade ultralytics opencv-pythonIf the issue persists, please provide more details about the error message and the specific function that is causing the problem. This will help us diagnose and address the issue more effectively. For further guidance, you can also refer to our Streamlit Live Inference Guide.
ghost
That was a Quick Replay and Quick fix ,Thanks for your kind support on my issues. The problem is fixed now.
Glenn JocherUltralytics@Charan2128 i'm glad to hear the initial issue is resolved. For the new issue with switching tasks and encountering OpenCV errors, please ensure you have the latest versions of both the Ultralytics package and OpenCV installed. You can update them using
pip install --upgrade ultralytics opencv-python. If the problem persists, please provide the specific error message and function causing the issue so we can assist you further. For more detailed guidance, you can refer to our Streamlit Live Inference Guide.
ghost
AttributeError: module 'ultralytics.solutions' has no attribute 'inference' Traceback: File "C:\Users\DELL\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\scriptrunner\exec_code.py", line 75, in exec_func_with_error_handling result = func() ^^^^^^ File "C:\Users\DELL\AppData\Local\Programs\Python\Python312\Lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 574, in code_to_exec exec(code, module.dict) File "D:\YOLO\infer.py", line 3, in solutions.inference() ^^^^^^^^^^^^^^^^^^^ This is the error im getting while running this and i have installed necessary packages.
Paula DerrengerUltralytics(modificato)@Charan2128 it looks like you're encountering an
AttributeErrorbecausesolutions.inferenceis not an attribute of theultralytics.solutionsmodule. Please ensure you are using the latest version of the Ultralytics package by runningpip install --upgrade ultralytics. Then launch the Streamlit app directly from the CLI withyolo solutions inference, or from Python withsolutions.Inference(model="yolo26n.pt").inference()run viastreamlit run <file-name.py>. For more details, you can refer to our Streamlit Live Inference Guide.

