Guia de início rápido: Raspberry Pi com Ultralytics YOLO26
O Raspberry Pi é um computador pequeno e acessível que executa o Ultralytics YOLO26 para deteção de objetos em tempo real na periferia — sem necessidade de GPU. Este guia mostra-te como implementar o YOLO26 no Raspberry Pi 4 e 5: gravar o sistema operativo, instalar o Ultralytics, exportar para NCNN para obter a inferência mais rápida em ARM e executar previsões sobre um fluxo de vídeo em direto da câmara. Também inclui benchmarks de desempenho em oito formatos de exportação, para poderes escolher o melhor equilíbrio entre velocidade e precisão para o teu hardware.
Acesse diretamente a configuração do Ultralytics, a exportação para NCNN e execução de inferência, os benchmarks ou a inferência com câmera.
Assista: Atualizações e melhorias do Raspberry Pi 5.
Este guia foi testado com Raspberry Pi 4 e Raspberry Pi 5 executando a versão mais recente do Raspberry Pi OS Bookworm (Debian 12). Espera-se que este guia também funcione em dispositivos Raspberry Pi mais antigos, como o Raspberry Pi 3, desde que tenham o mesmo Raspberry Pi OS Bookworm instalado.
O que é Raspberry Pi?#
O Raspberry Pi é um computador de placa única, pequeno e acessível. Tornou-se popular para uma vasta gama de projetos e aplicações, desde a automação residencial para entusiastas até usos industriais. As placas Raspberry Pi podem executar vários sistemas operativos e oferecem pinos GPIO (entrada/saída de uso geral), que permitem integrar facilmente sensores, atuadores e outros componentes de hardware. Existem vários modelos com especificações diferentes, mas todos partilham a mesma filosofia de design: baixo custo, tamanho compacto e versatilidade.
Comparação das séries Raspberry Pi#
| Raspberry Pi 3 | Raspberry Pi 4 | Raspberry Pi 5 | |
|---|---|---|---|
| CPU | Broadcom BCM2837, SoC Cortex-A53 de 64 bits | Broadcom BCM2711, SoC Cortex-A72 de 64 bits | Broadcom BCM2712, SoC Cortex-A76 de 64 bits |
| Frequência máxima da CPU | 1.4GHz | 1.8GHz | 2.4GHz |
| GPU | VideoCore IV | VideoCore VI | VideoCore VII |
| Frequência máxima da GPU | 400MHz | 500MHz | 800MHz |
| Memória | 1GB LPDDR2 SDRAM | 1GB, 2GB, 4GB, 8GB LPDDR4-3200 SDRAM | 2GB, 4GB, 8GB, 16GB LPDDR4X-4267 SDRAM |
| PCIe | N/D | N/D | 1xPCIe 2.0 Interface |
| Consumo máximo de energia | 2.5A@5V | 3A@5V | 5A@5V (PD enabled) |
O que é o Raspberry Pi OS?#
O Raspberry Pi OS (anteriormente conhecido como Raspbian) é um sistema operacional semelhante ao Unix, baseado na distribuição Debian GNU/Linux, para a família Raspberry Pi de computadores compactos de placa única distribuídos pela Raspberry Pi Foundation. O Raspberry Pi OS é altamente otimizado para o Raspberry Pi com CPUs ARM e usa um ambiente de desktop leve que, por padrão, é executado no Wayland no Raspberry Pi 4 e 5. O Raspberry Pi OS está em desenvolvimento ativo, com ênfase na melhoria da estabilidade e do desempenho do maior número possível de pacotes Debian no Raspberry Pi.
Gravar o Raspberry Pi OS no Raspberry Pi#
A primeira coisa a fazer depois de obteres um Raspberry Pi é gravar o Raspberry Pi OS num cartão micro-SD, inseri-lo no dispositivo e iniciar o sistema operativo. Segue a documentação de introdução da Raspberry Pi detalhada para preparar o dispositivo para a primeira utilização.
Configurar o Ultralytics#
Você pode configurar o pacote Ultralytics no Raspberry Pi de duas maneiras para o seu próximo projeto de visão computacional:
Começar com Docker#
A maneira mais rápida de começar a usar o Ultralytics YOLO26 no Raspberry Pi é executá-lo com uma imagem Docker pré-compilada para Raspberry Pi.
Executa o comando abaixo para obter o contentor Docker e executá-lo no Raspberry Pi. Esta imagem baseia-se na imagem oficial de Python 3.13-slim, que executa Python 3.13 na versão mais recente do Debian.
t=ultralytics/ultralytics:latest-arm64
sudo docker pull $t && sudo docker run -it --ipc=host $tA imagem Docker já inclui o Ultralytics, então você pode ir direto para exportar seu modelo para NCNN.
Começar sem Docker#
Instalar o pacote Ultralytics#
Aqui vamos instalar o pacote Ultralytics no Raspberry Pi. As dependências de exportação para formatos como NCNN são instaladas automaticamente na primeira vez que você exporta um modelo PyTorch, então somente o pacote básico é necessário aqui.
-
Atualizar a lista de pacotes, instalar o pip e atualizá-lo para a versão mais recente
sudo apt update sudo apt install python3-pip -y pip install -U pip -
Instalar o pacote pip
ultralyticspip install ultralytics -
Reiniciar o dispositivo
sudo reboot
Usar NCNN no Raspberry Pi#
Entre todos os formatos de exportação de modelos compatíveis com o Ultralytics, o NCNN oferece o melhor desempenho de inferência em dispositivos Raspberry Pi, pois é altamente otimizado para plataformas móveis e embarcadas, como ARM. Converte o teu modelo YOLO26n PyTorch para NCNN e, em seguida, executa a inferência com o modelo exportado:
from ultralytics import YOLO
# Carregar um modelo YOLO26n PyTorch
model = YOLO("yolo26n.pt")
# Exportar o modelo para o formato NCNN
model.export(format="ncnn") # creates 'yolo26n_ncnn_model'
# Carregar o modelo NCNN exportado
ncnn_model = YOLO("yolo26n_ncnn_model")
# Executar inferência
results = ncnn_model("https://ultralytics.com/images/bus.jpg")Para mais detalhes sobre as opções de exportação compatíveis, consulte o guia de opções de implantação de modelos.
Melhorias de desempenho do YOLO26 em relação ao YOLO11#
O YOLO26 foi projetado especificamente para funcionar em dispositivos com recursos limitados, como o Raspberry Pi 5. Em comparação com o YOLO11n, o YOLO26n oferece um aumento de ~15% no FPS (6.79 → 7.79) e também uma mAP superior (40.1 contra 39.5), com tamanho de entrada 640 e modelos exportados para ONNX no Raspberry Pi 5. A tabela e o gráfico abaixo mostram essa comparação.
| Modelo | mAP50-95(B) | Tempo de inferência (ms/im) |
|---|---|---|
| YOLO26n | 40.1 | 128.42 |
| YOLO26s | 47.8 | 352.84 |
| YOLO26m | 52.5 | 993.78 |
| YOLO26l | 54.4 | 1259.46 |
| YOLO26x | 56.9 | 2636.26 |
Avaliado com Ultralytics 8.4.14.
Resultados de benchmark do YOLO26 no Raspberry Pi 5#
A equipa do Ultralytics executou benchmarks do YOLO26 em oito formatos de modelo diferentes, medindo velocidade e precisão: PyTorch, TorchScript, ONNX, OpenVINO, LiteRT, MNN, NCNN, ExecuTorch. Os benchmarks foram executados num Raspberry Pi 5, em precisão FP32 e com o tamanho de imagem de entrada padrão de 640.
Gráfico comparativo#
Apenas YOLO26n e YOLO26s estão incluídos, pois os modelos maiores são demasiado lentos para serem práticos no Raspberry Pi.
Tabela comparativa detalhada#
A tabela abaixo apresenta os resultados do benchmark de dois modelos (YOLO26n, YOLO26s) em oito formatos diferentes (PyTorch, TorchScript, ONNX, OpenVINO, LiteRT, MNN, NCNN, ExecuTorch), executados num Raspberry Pi 5, indicando o estado, o tamanho, a métrica mAP50-95(B) e o tempo de inferência de cada combinação.
| Formato | Status | Tamanho em disco (MB) | mAP50-95(B) | Tempo de inferência (ms/im) |
|---|---|---|---|---|
| PyTorch | ✅ | 5.3 | 0.4760 | 299.09 |
| TorchScript | ✅ | 9.8 | 0.4734 | 353.20 |
| ONNX | ✅ | 9.5 | 0.4734 | 125.99 |
| OpenVINO | ✅ | 9.6 | 0.4734 | 104.55 |
| LiteRT | ✅ | 9.8 | 0.4730 | 123.30 |
| MNN | ✅ | 9.4 | 0.4749 | 91.87 |
| NCNN | ✅ | 9.4 | 0.4784 | 67.03 |
| ExecuTorch | ✅ | 9.4 | 0.4772 | 144.83 |
Avaliado com Ultralytics 8.4.108
O tempo de inferência não inclui o pré/pós-processamento.
Reproduza nossos resultados#
Para reproduzir os benchmarks Ultralytics acima em todos os formatos de exportação, execute este código:
from ultralytics import YOLO
# Carregar um modelo YOLO26n PyTorch
model = YOLO("yolo26n.pt")
# Benchmarke a velocidade e a precisão do YOLO26n no conjunto de dados COCO128 para todos os formatos de exportação
results = model.benchmark(data="coco128.yaml", imgsz=640)Observe que os resultados do benchmark podem variar conforme a configuração exata de hardware e software de um sistema, bem como a carga de trabalho atual do sistema no momento da execução dos benchmarks. Para obter resultados mais confiáveis, use um conjunto de dados com um grande número de imagens, por exemplo, data='coco.yaml' (5000 imagens de validação).
A exportação format=litert (via litert-torch) só é compatível com Linux x86_64 e macOS, não com o próprio Raspberry Pi. Exporte o modelo .tflite em uma máquina Linux x86_64 ou em um Mac, copie-o para o Raspberry Pi e use o Pi para inferência.
Usar a câmera do Raspberry Pi#
Os projetos de visão computacional no Raspberry Pi muitas vezes precisam de fluxos de vídeo em tempo real para a inferência. O conector MIPI CSI integrado no Raspberry Pi permite ligar os módulos de câmara oficiais da Raspberry Pi. Neste guia, usámos um Raspberry Pi Camera Module 3 para captar os fluxos de vídeo e executar inferência com modelos YOLO26.
Saiba mais sobre os diferentes módulos de câmera oferecidos pela Raspberry Pi e também sobre como começar a usar os módulos de câmera Raspberry Pi.
O Raspberry Pi 5 usa conectores CSI menores que o Raspberry Pi 4 (22 pinos contra 15 pinos), então você precisará de um cabo adaptador de 15 para 22 pinos para conectar uma câmera Raspberry Pi.
Testar a câmera#
Executa o comando rpicam-hello a seguir depois de ligares a câmara ao Raspberry Pi. Deverás ver o fluxo de vídeo em direto da câmara durante cerca de 5 segundos.
rpicam-helloInferência com a câmera#
Há dois métodos para usar a câmera Raspberry Pi e executar inferências com modelos YOLO26.
Usa picamera2, que já vem instalado com o Raspberry Pi OS, para aceder à câmara e executar inferência com modelos YOLO26.
import cv2
from picamera2 import Picamera2
from ultralytics import YOLO
# Inicializar o Picamera2
picam2 = Picamera2()
picam2.preview_configuration.main.size = (1280, 720)
picam2.preview_configuration.main.format = "RGB888"
picam2.preview_configuration.align()
picam2.configure("preview")
picam2.start()
# Carrega o modelo YOLO26
model = YOLO("yolo26n.pt")
while True:
# Capturar quadro a quadro
frame = picam2.capture_array()
# Executar inferência do YOLO26 no quadro
results = model(frame)
# Visualiza os resultados no quadro
annotated_frame = results[0].plot()
# Exibir o quadro resultante
cv2.imshow("Camera", annotated_frame)
# Interrompe o loop se 'q' for pressionado
if cv2.waitKey(1) == ord("q"):
break
# Liberar recursos e fechar janelas
cv2.destroyAllWindows()Práticas recomendadas ao usar o Raspberry Pi#
Segue estas práticas recomendadas para obter o máximo desempenho do YOLO26 no Raspberry Pi.
-
Usar um SSD
Para funcionamento contínuo, 24 horas por dia e 7 dias por semana, usa um SSD para o sistema, pois um cartão SD pode desgastar-se ou falhar com gravações contínuas. Com o conector PCIe integrado no Raspberry Pi 5, podes ligar SSDs usando um adaptador, como o NVMe Base para Raspberry Pi 5.
-
Gravar sem interface gráfica
Ao gravar o Raspberry Pi OS, você pode optar por não instalar o ambiente de desktop (Raspberry Pi OS Lite). Isso pode economizar um pouco de RAM no dispositivo, deixando mais espaço para o processamento de visão computacional.
-
Fazer overclock no Raspberry Pi
Se quiser um pequeno aumento de desempenho ao executar modelos Ultralytics YOLO26 no Raspberry Pi 5, você pode aumentar a frequência da CPU de 2.4GHz para 3.0GHz e a da GPU de 800MHz para 1GHz. Se o sistema ficar instável ou travar, reduza os valores de overclock em incrementos de 100MHz. Garanta um resfriamento adequado, pois o overclock aumenta a geração de calor e pode causar limitação térmica.
a. Atualize o software
sudo apt update && sudo apt dist-upgradeb. Abra o arquivo de configuração para editá-lo
sudo nano /boot/firmware/config.txtc. Adicione as seguintes linhas ao final
arm_freq=3000 gpu_freq=1000 force_turbo=1d. Salve e saia pressionando CTRL + X, depois Y e, em seguida, ENTER
e. Reinicie o Raspberry Pi
Próximas etapas#
Você configurou o YOLO26 no Raspberry Pi com sucesso. Para avançar, explore o modo Predict para ver mais opções de inferência, o modo Export para conhecer outros formatos de implantação ou o guia NVIDIA Jetson se precisar de mais poder de processamento na borda. Para consultar a documentação completa, visite a documentação Ultralytics YOLO26.
Agradecimentos e citações#
Este guia foi criado inicialmente por Daan Eeltink para a Kashmir World Foundation, uma organização dedicada ao uso do YOLO na conservação de espécies ameaçadas de extinção. Reconhecemos seu trabalho pioneiro e seu foco educacional no campo das tecnologias de detecção de objetos.
Para mais informações sobre as atividades da Kashmir World Foundation, visite o site.
Perguntas frequentes#
Para configurar o Ultralytics YOLO26 em um Raspberry Pi sem Docker, siga estas etapas:
- Atualize a lista de pacotes e instale
pip:sudo apt update sudo apt install python3-pip -y pip install -U pip - Instale o pacote Ultralytics:
pip install ultralytics - Reinicie o dispositivo para aplicar as alterações:
sudo reboot
Para instruções detalhadas, consulte a seção Começar sem Docker.
- Atualize a lista de pacotes e instale
O NCNN é altamente otimizado para plataformas móveis e embarcadas, o que o torna uma ótima opção para executar YOLO26 em dispositivos Raspberry Pi. Seus kernels otimizados para ARM oferecem inferência mais rápida no Pi do que os outros formatos de exportação nos benchmarks acima.
Você pode converter um modelo PyTorch YOLO26 para o formato NCNN usando comandos Python ou CLI:
Exemplofrom ultralytics import YOLO # Carregar um modelo YOLO26n PyTorch model = YOLO("yolo26n.pt") # Exportar o modelo para o formato NCNN model.export(format="ncnn") # creates 'yolo26n_ncnn_model' # Carregar o modelo NCNN exportado ncnn_model = YOLO("yolo26n_ncnn_model") # Executar inferência results = ncnn_model("https://ultralytics.com/images/bus.jpg")Para mais detalhes, consulte a seção Usar NCNN no Raspberry Pi.
As principais diferenças incluem:
- CPU: o Raspberry Pi 4 usa o SoC Broadcom BCM2711 Cortex-A72 de 64 bits, enquanto o Raspberry Pi 5 usa o SoC Broadcom BCM2712 Cortex-A76 de 64 bits.
- Frequência máxima da CPU: o Raspberry Pi 4 tem frequência máxima de 1.8GHz, enquanto o Raspberry Pi 5 chega a 2.4GHz.
- Memória: O Raspberry Pi 4 oferece até 8 GB de SDRAM LPDDR4-3200, enquanto o Raspberry Pi 5 conta com SDRAM LPDDR4X-4267, disponível nas variantes de 2 GB, 4 GB, 8 GB e 16 GB.
Essas melhorias contribuem para melhores resultados de desempenho dos modelos YOLO26 no Raspberry Pi 5 em comparação com o Raspberry Pi 4. Consulta a tabela Comparação da série Raspberry Pi para mais detalhes.
Há dois métodos para configurar uma câmera Raspberry Pi para inferência com YOLO26:
-
Usando
picamera2:import cv2 from picamera2 import Picamera2 from ultralytics import YOLO picam2 = Picamera2() picam2.preview_configuration.main.size = (1280, 720) picam2.preview_configuration.main.format = "RGB888" picam2.preview_configuration.align() picam2.configure("preview") picam2.start() model = YOLO("yolo26n.pt") while True: frame = picam2.capture_array() results = model(frame) annotated_frame = results[0].plot() cv2.imshow("Camera", annotated_frame) if cv2.waitKey(1) == ord("q"): break cv2.destroyAllWindows() -
Usando um fluxo TCP:
rpicam-vid -n -t 0 --inline --listen -o tcp://127.0.0.1:8888from ultralytics import YOLO model = YOLO("yolo26n.pt") results = model("tcp://127.0.0.1:8888")
Para instruções detalhadas de configuração, consulta a secção Inferência com câmera.
-
Comentários134
Faz uma pergunta, partilha os teus resultados ou ajuda alguém.
smhty
Works great on Raspberry Pi 5. A tutorial for the AI kit that comes with Raspberry Pi 5 would be great as well: https://www.raspberrypi.com/products/ai-kit/
1
Glenn JocherUltralytics(editado)Hi there!
Thank you for your feedback and for sharing your positive experience on the Raspberry Pi 5! 😊
Creating a tutorial for the AI kit that comes with the Raspberry Pi 5 is a fantastic idea. In the meantime, you can refer to our comprehensive Quick Start Guide for Raspberry Pi with Ultralytics YOLO26, which provides detailed instructions on setting up and running YOLO on Raspberry Pi devices, including performance benchmarks.
For those interested in using the AI kit, the setup process should be quite similar. Here’s a quick overview to get you started:
-
Flash Raspberry Pi OS: Ensure you have the latest Raspberry Pi OS Bookworm (Debian 12) installed. Follow the Getting Started Documentation by Raspberry Pi to prepare your device.
-
Set Up Ultralytics:
- With Docker:
t=ultralytics/ultralytics:latest-arm64 && sudo docker pull $t && sudo docker run -it --ipc=host $t - Without Docker:
sudo apt update sudo apt install python3-pip -y pip install -U pip pip install ultralytics[export] sudo reboot
- With Docker:
-
Use NCNN for Best Performance: Convert your YOLO26 model to NCNN format for optimal performance on Raspberry Pi:
from ultralytics import YOLO # Load a YOLO26n PyTorch model model = YOLO("yolo26n.pt") # Export the model to NCNN format model.export(format="ncnn") # creates 'yolo26n_ncnn_model' # Load the exported NCNN model ncnn_model = YOLO("yolo26n_ncnn_model") # Run inference results = ncnn_model("https://ultralytics.com/images/bus.jpg") -
Using the Raspberry Pi Camera: For real-time video feeds, you can use the
picamera2library or set up a TCP stream:-
Using
picamera2:import cv2 from picamera2 import Picamera2 from ultralytics import YOLO picam2 = Picamera2() picam2.preview_configuration.main.size = (1280, 720) picam2.preview_configuration.main.format = "RGB888" picam2.preview_configuration.align() picam2.configure("preview") picam2.start() model = YOLO("yolo26n.pt") while True: frame = picam2.capture_array() results = model(frame) annotated_frame = results[0].plot() cv2.imshow("Camera", annotated_frame) if cv2.waitKey(1) == ord("q"): break cv2.destroyAllWindows() -
Using TCP Stream:
rpicam-vid -n -t 0 --inline --listen -o tcp://127.0.0.1:8888from ultralytics import YOLO model = YOLO("yolo26n.pt") results = model("tcp://127.0.0.1:8888")
-
We hope this helps you get started with the AI kit on your Raspberry Pi 5. For more detailed instructions and additional resources, please visit our Raspberry Pi Guide.
Happy coding! 🚀
-
wnelis
Today I've installed module ultralytics on a Raspberry Pi 4 with 4 [GiB] memory running Trixie. Some remarks about what I've learned: . Use the 64-bit variant of Raspberry OS; . Use an microSD card of at least 32 [GiB]; . Disable /tmp becoming a file system in memory (tmpfs):
sudo systemctl mask tmp.mount; . OpenCV is installed using apt, module ultralytics is installed in a virtual Python environment: 'python -m venv --system-site-packages `.It is found that YOLO runs into a hardware error: "Illegal instruction". This can be reproduced by using the Python script shown above to export the model in NCNN format. The output is:
Downloading https://github.com/ultralyti…: 100% ━━━━━━━━━━━━ 5.3MB 1.4MB/s 3.8s Ultralytics 8.4.191 🚀 Python-3.13.5 torch-2.14.1+cu130 CPU (aarch64) Illegal instruction
How can this issue be solved?
Paula DerrengerUltralytics@wnelis the most likely cause is a native PyTorch binary using instructions unsupported by the Pi 4’s CPU, rather than faulty hardware; similar crashes are documented in Ultralytics #19091 and upstream PyTorch, although your exact version is not confirmed affected. (github.com) Your log shows a CUDA build (
+cu130); first replace it with the matching official CPU-only packages inside your activated virtual environment, then retry the export: (pytorch.org)python -m pip install --force-reinstall torch==2.14.1 torchvision==0.29.1 --index-url https://download.pytorch.org/whl/cpuIf it still crashes, please share the text output of
yolo checksandpython -m pip show torch torchvisionfrom that same environment so we can identify package/path conflicts.
hm-zeroone(editado)
"We haven’t validated Orbit OS yet, but if it supports tflite or onnx runtimes you should be able to deploy an exported Ultralytics YOLO26 model there using Export mode and the deployment options guide; if you try it, please share the exact device, export format, and any text error logs here in Discussions so the Ultralytics team can take a look."
Hi @glenn-jocher,
I added a new feature to my Orbit OS app to test YOLO models directly on edge devices, in this case a Raspberry Pi. The app now allows adding new models, and by default includes YOLO v8, v11 and v26.
We also introduced a benchmark mode, where you can select an image and run all models to compare performance and results.
In the example shown in the image, YOLOv8 achieved the highest number of correct object detections by time.
This demo video shows the remote deployment, no SSH, no Docker, of the app in action on Raspberry Pi 5 vs Arduino UNO Q and a comparison (“VS”) between the RPi 5 and UNO Q running YOLO v8. https://youtu.be/aiFJmosYVAI?si=v3Jo_TbswU3n-sZU
Glenn JocherUltralyticsThanks for sharing the Orbit OS benchmark; for a fair cross-model comparison please include the exact export/runtime backend,
imgsz, confidence/IoU thresholds, and per-image latency/FPS, since on Raspberry Pi CPU deployments NCNN is usually the best baseline for YOLO26.hm-zeroone(editado)
Hey! Thanks for the feedback. All models were tested under the same conditions — TFlite runtime, same image, same thresholds (conf=0.50, IoU=0.45), same imgsz 640×640 with letterbox preprocessing.
Everything runs through the OrbitOS SDK which currently has TFLite and ONNX embedded. NCNN is something we'll look into adding in a future release.
Quick question — for RPi deployments, would you recommend INT8 or float16 as the default export format?
Orbit OS SDK 26.0.1 Inference example.
Orbit OS is multi-language — For now only Go SDK is available, Python, Java and C++ SDKs are coming soon.
model, _ := device.AIManager.UploadAndLoadModel( "yolo8n", "models/yolo26n_float16.tflite", aiv26.ModelBackend_TFLITE, aiv26.ExecutionMode_EXEC_HIGH_THREADS, ) resp, _ := model.Infer(ctx, tensor.Data, tensor.Shape, tensor.Dtype) fmt.Println(resp.GetOutputShape()) // [1 84 8400] fmt.Println(resp.GetLatencyUs()) // e.g. 528000
Glenn JocherUltralytics(editado)For plain Raspberry Pi CPU deployment with
LiteRT(.tflite), I’d usually default toINT8for the best speed and memory savings, and usefloat16only if quantization hurts accuracy too much or your runtime performs better with FP kernels; if you benchmark both, the LiteRT export guide is the right reference, while our Raspberry Pi guide showsNCNNas the strongest baseline once you add that backend.1
safdarhamid64-cpu
when i write in raspberry pi terminal : from ultralytics import yolo error msg illegal instruction pops up , i have trained model and even i have first created environment and installed pip install ultralytics but still i am not able to run model yolo11n on my Raspberry Pi 4 , Guide me plzz
Glenn JocherUltralyticsThat
Illegal instructionon Raspberry Pi usually means an incompatible binary wheel (most oftentorch/numpypulled for the wrong arch/OS), and also note the correct import isfrom ultralytics import YOLO(capitalized), notyolo; please paste the text output ofyolo checksplus the full traceback here in this discussion, and confirmuname -m+ whether you’re on Raspberry Pi OS Bookworm 64-bit as in the Raspberry Pi YOLO26 guide; as a quick way to rule out env issues you can also try our ARM64 Docker flow from that guide:```bash t=ultralytics/ultralytics:latest-arm64 sudo docker pull $t && sudo docker run -it --ipc=host $t python -c "from ultralytics import YOLO; YOLO('yolo11n.pt')"
inuropix
Hi.. I get an error when implement botsort with reid is True and the model is ncnn(exported from yolo26n-cls.pt)
Here’s the full traceback from the error:
self.tracks = self.model.track( ^^^^^^^^^^^^^^^^^ File "/home/sbr/people_counting/lib/python3.11/site-packages/ultralytics/engine/model.py", line 579, in track return self.predict(source=source, stream=stream, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/sbr/people_counting/lib/python3.11/site-packages/ultralytics/engine/model.py", line 536, in predict return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/sbr/people_counting/lib/python3.11/site-packages/ultralytics/engine/predictor.py", line 225, in __call__ return list(self.stream_inference(source, model, *args, **kwargs)) # merge list of Results into one ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/sbr/people_counting/lib/python3.11/site-packages/torch/utils/_contextlib.py", line 40, in generator_context response = gen.send(None) ^^^^^^^^^^^^^^ File "/home/sbr/people_counting/lib/python3.11/site-packages/ultralytics/engine/predictor.py", line 338, in stream_inference self.run_callbacks("on_predict_postprocess_end") File "/home/sbr/people_counting/lib/python3.11/site-packages/ultralytics/engine/predictor.py", line 509, in run_callbacks callback(self) File "/home/sbr/people_counting/lib/python3.11/site-packages/ultralytics/trackers/track.py", line 93, in on_predict_postprocess_end tracks = tracker.update(det, result.orig_img, getattr(result, "feats", None)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/sbr/people_counting/lib/python3.11/site-packages/ultralytics/trackers/byte_tracker.py", line 361, in update dists = self.get_dists(unconfirmed, detections) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/sbr/people_counting/lib/python3.11/site-packages/ultralytics/trackers/bot_sort.py", line 220, in get_dists emb_dists = matching.embedding_distance(tracks, detections) / 2.0 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/sbr/people_counting/lib/python3.11/site-packages/ultralytics/trackers/utils/matching.py", line 128, in embedding_distance cost_matrix = np.maximum(0.0, cdist(track_features, det_features, metric)) # Normalized features ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/sbr/people_counting/lib/python3.11/site-packages/scipy/spatial/distance.py", line 2903, in cdist raise ValueError('XA must be a 2-dimensional array.') ValueError: XA must be a 2-dimensional array.Any idea?
Glenn JocherUltralyticsThat traceback usually means BoT-SORT didn’t get valid (2D) ReID embeddings; also note that
.track()should run with a Detect/Seg/Pose model, whileyolo26n-clsis only meant to be the ReID feature extractor configured insidebotsort.yaml(viawith_reid/model). (docs.ultralytics.com)yolo track model=yolo26n.pt source=path/to/video.mp4 tracker="botsort.yaml"# in a copy of botsort.yaml with_reid: True model: yolo26n-cls.pt # first confirm this works before swapping to an exported backendIf you just need stable tracking on Raspberry Pi, try
tracker="bytetrack.yaml"(no ReID); if you still hit this, please paste yourbotsort.yamland the output ofyolo checksso we can reproduce from the same environment. (docs.ultralytics.com)
hananabuzainab
I can't install ultralytics on rasspbery pi 5...with python 3.11 version,why??
I used: pip install ultralytics
How can i fix this problem ??
Glenn JocherUltralyticsCan you paste the full
pip install ultralyticserror text (as text, not a screenshot) and the output ofpython3 -Vhere so we can pinpoint what’s failing? On Raspberry Pi 5 this is most often a Python/pip mismatch or non-Bookworm/32-bit setup—please also confirm you’re on Raspberry Pi OS Bookworm 64-bit as in the Raspberry Pi with Ultralytics YOLO26 guide.python3 -V python3 -m pip install -U pip setuptools wheel python3 -m venv .venv source .venv/bin/activate python -m pip install -U pip python -m pip install ultralytics
avasanjesh
Hi,
I want to use python version of raspberry pi 32 bit OS. can you please tell me if i can export yolo detection model in 32 bit raspberry pi?
Edward-YS
Hello,I'm wondering if there is Benchmarking Results of Two Different Models (YOLO8n, YOLO8s) Across Ten Formats: PyTorch, TF, ONNX, OpenVINO, TF SavedModel, TF GraphDef, TF Lite, PaddlePaddle, MNN, NCNN.
zyt2011
Installing a single Hailo-5 is sufficient.
发件人: Beautifulboy111 @.> 发送时间: 2025年4月22日 14:24 收件人: ultralytics/ultralytics @.> 抄送: zyt2011 @.>; Mention @.> 主题: Re: [ultralytics/ultralytics] zh/guides/raspberry-pi/ (Discussion #19489)
Why does my Raspberry Pi 5 have a high inference latency of 150ms when using NCNN for video recognition, even after overclocking? How can I reduce the inference time?
― Reply to this email directly, view it on GitHubhttps://github.com/orgs/ultralytics/discussions/19489#discussioncomment-12906311, or unsubscribehttps://github.com/notifications/unsubscribe-auth/BJ7DFR53TAD7QVJNO3TTXJL22XOAJAVCNFSM6AAAAABYEEJCHCVHI2DSMVQWIX3LMV43URDJONRXK43TNFXW4Q3PNVWWK3TUHMYTEOJQGYZTCMI. You are receiving this because you were mentioned.Message ID: @.***>
Glenn JocherUltralytics(editado)@Beautifulboy111 150ms inference latency with NCNN on Raspberry Pi 5 is higher than expected. Here are some steps to reduce it:
-
Use a smaller YOLO26 model - our benchmarks show YOLO26n is significantly faster than YOLO26s with NCNN on Pi 5 (67ms vs 173ms)
-
Reduce input resolution - try 320x320 instead of 640x640, which can cut inference time by up to 70%
-
Optimize memory allocation by running without GUI (Raspberry Pi OS Lite)
-
Ensure you're using proper cooling for sustained performance when overclocked
-
Consider processing at lower FPS if your application allows it
Regarding @zyt2011's suggestion, while accelerators like Hailo can boost performance, they're a separate investment. I'd recommend optimizing your current setup first using the techniques in our Raspberry Pi guide.
What's your specific use case? This would help us provide more targeted optimization advice.
-
Beautifulboy111
Why does my Raspberry Pi 5 have a high inference latency of 150ms when using NCNN for video recognition, even after overclocking? How can I reduce the inference time?