The robot finds people and things with its camera. To follow a person who moves, it has to run a neural network on every camera frame, about 14 times a second, and only the Jetson's GPU is fast enough for that. In this chapter you install NVIDIA's GPU libraries without disturbing the ROS 2 install from chapter 6, build the detector the robot uses, and run it by hand on one frame so you can see what it reports.
The whole chapter takes about three hours. Around 30 minutes of that is waiting for downloads and engine builds. Nothing here drives the wheels. The arm moves once, near the end, to tuck the camera level.
A neural network is mostly multiplying large tables of numbers. A CPU does that a few numbers at a time. A GPU does thousands at once. The Orin NX has its GPU on the same chip as the CPU, and the two share the same 16 GB of memory. Memory the GPU takes is memory the robot's other programs lose, so keep an eye on it.
CUDA is NVIDIA's way for programs to run code on the GPU. It comes as libraries plus a compiler called nvcc. cuDNN is a CUDA library of ready-made neural network building blocks. PyTorch uses both.
Running a trained network on new input is called inference. TensorRT is NVIDIA's inference optimiser. You give it a trained network as an ONNX file, a standard network format, and it measures which way of computing each layer is fastest on this particular GPU. Then it saves the result as an engine file. The engines here use fp16, 16-bit numbers instead of 32-bit. That halves the memory traffic and gives nearly the same answers. An engine is tied to the GPU and the TensorRT version it was built with, so you build it on the robot, never on your PC.
An ordinary object detector knows a fixed list of things it was trained on. An open-vocabulary detector takes the names as text when it runs. You write "a person" or "a guitar", and it scores every candidate box in the image against every phrase. The phrases are called prompts. The robot uses Google's OWL-ViT model through NVIDIA's NanoOWL, which runs the image half of OWL-ViT as a TensorRT engine and keeps the text half in PyTorch. The image is resized to 768x768 and cut into square patches. The patch32 model cuts 32-pixel squares, 576 of them, and is faster. The patch16 model cuts 16-pixel squares, 2304 of them, and sees finer detail but is slower. OWLv2 is a newer, heavier model of the same family. It runs in plain PyTorch here and is better at small things. Scores run from 0 to 1, but real hits are often only 0.15 to 0.6, so each prompt gets its own threshold.
A detector reports many overlapping boxes for one object. Non-maximum suppression, NMS for short, keeps the best-scoring box and drops every other box with the same label that overlaps it too much. The overlap is measured as IoU, intersection over union: the area two boxes share divided by the area they cover together. 1.0 means the boxes are identical, 0 means they don't touch.
Chapter 6 must be done, with ROS 2 Humble installed and all the nvidia-l4t-* packages held. apt-mark showhold listed 45 of them on my robot before this chapter, and 46 after it. Chapter 7 must be done too, with rosorin-camera publishing /aurora/rgb/image_raw. You only need the camera for the detection at the end.
The camera odometry in chapter 9 and nvblox in chapter 10 run on the CUDA 12.6 libraries this chapter installs, which is why vision comes before them. On my robot I did this chapter later than you will: the install, steps 1 to 9, between chapters 9 and 10, and the first detection and the speed tests after chapter 10 was installed. Nothing in this chapter uses those two, but I haven't run it in this order.
You need several GB of free disk: about 1.8 GB of model weights and 0.36 GB of engines, plus the CUDA libraries and the Python environment. Make a fresh backup set as in chapter 5 first.
Two rules for this whole chapter. Don't install the nvidia-jetpack meta-package; the next section shows why. And never run apt autoremove. It removes initramfs-tools, which the Jetson needs to boot. apt will print "Use 'apt autoremove' to remove them." several times during this chapter. Ignore it.
The install script and the vision code live in the repo on your laptop. Copy them over:
cd ~/CCode/rosorin-pro
ssh rosorin 'mkdir -p ~/setup ~/vision'
scp scripts/install_vision.sh scripts/rollback_vision.sh rosorin:setup/
scp vision/*.py vision/README.md rosorin:vision/
Besides the detector code, this puts ~/vision/mind_pause.py on the robot. Programs in chapters 10 and 11 import it.
NVIDIA's usual instruction is sudo apt install nvidia-jetpack. On this robot it would undo earlier chapters. Look before you believe me. apt-get -s only simulates an install and changes nothing:
apt-get -s install nvidia-jetpack 2>/dev/null | grep -E "^Inst" > /tmp/jp_sim.txt
wc -l < /tmp/jp_sim.txt
grep "^Inst nvidia-l4t" /tmp/jp_sim.txt | head
grep -E "^Inst [^ ]+ \[[0-9]" /tmp/jp_sim.txt | head -5
The second grep lists the nvidia-l4t-* packages it would touch. The third lists upgrades only. apt writes an upgrade as Inst package [old version] (new version ...), and a new install has no [old version]. On my robot it printed this:
122
Inst nvidia-l4t-cudadebuggingsupport (12.6-34622040.0 L4T Jetson r36.4:stable [arm64])
Inst nvidia-l4t-jetson-multimedia-api (36.4.7-20250918154033 L4T Jetson r36.4:stable [arm64])
Inst nvidia-l4t-dla-compiler (36.4.7-20250918154033 L4T Jetson r36.4:stable [arm64])
Inst nvidia-l4t-gstreamer (36.4.7-20250918154033 L4T Jetson r36.4:stable [arm64])
Inst libopencv-dev [4.5.4+dfsg-9ubuntu4] (4.8.
That's 122 packages, three of NVIDIA's board packages at 36.4.7 on a 36.4.3 robot, and an OpenCV upgrade. ROS 2 Humble is built against the system's OpenCV 4.5.4. The meta-package replaces it, removes 19 packages along the way, and moves the board packages you held in chapter 6. So the robot installs only the pieces vision needs, from the NVIDIA apt repository the stock system already lists.
Simulate first. You want to see 0 upgraded and 0 to remove, and no nvidia-l4t or OpenCV line:
P="cuda-libraries-12-6 cuda-cudart-dev-12-6 cuda-nvcc-12-6 cuda-cupti-12-6 libcudnn9-cuda-12 tensorrt-libs libnvinfer-bin python3-libnvinfer libnvinfer-dev libnvonnxparsers-dev libnvinfer-plugin-dev python3-venv python3-pip"
apt-get -s install $P > /tmp/min_sim.txt 2>&1
grep -iE "upgraded|remove" /tmp/min_sim.txt | head -3
grep "^Remv" /tmp/min_sim.txt | head
grep -E "^Inst (nvidia-l4t|libopencv)" /tmp/min_sim.txt
grep -E "^Inst [^ ]+ \[[0-9]" /tmp/min_sim.txt
On my robot the first grep printed one line and the other three printed nothing:
0 upgraded, 44 newly installed, 0 to remove and 48 not upgraded.
Your counts may differ. The 0 upgraded and 0 to remove must not. If they look right, install:
sudo apt-get install -y cuda-libraries-12-6 cuda-cudart-dev-12-6 cuda-nvcc-12-6 cuda-cupti-12-6 libcudnn9-cuda-12 \
tensorrt-libs libnvinfer-bin python3-libnvinfer libnvinfer-dev libnvonnxparsers-dev libnvinfer-plugin-dev \
python3-venv python3-pip
Here is what you just installed. cuda-libraries-12-6 is the CUDA 12.6 runtime, in /usr/local/cuda-12.6/lib64. cuda-cudart-dev-12-6 holds the headers for building code against CUDA, and cuda-nvcc-12-6 is the compiler. cuda-cupti-12-6 is NVIDIA's profiling library; PyTorch refuses to import without it. libcudnn9-cuda-12 is cuDNN 9. tensorrt-libs is the TensorRT 10.3 runtime. libnvinfer-bin gives you trtexec, the program NanoOWL calls to build its engines. python3-libnvinfer lets Python 3.10 import tensorrt. The three -dev packages are TensorRT's headers, its ONNX reader and its plugins. The last two give you Python virtual environments and pip.
Check that the key files arrived:
ls /usr/local/cuda-12.6/lib64/libcudart.so.12 /usr/local/cuda-12.6/lib64/libcupti.so.12 /usr/src/tensorrt/bin/trtexec
All three paths should print, with no No such file or directory. If you try python3 -c "import tensorrt" now, it fails with ImportError: libnvdla_compiler.so: cannot open shared object file. That's expected. The next step fixes it. If apt itself reports an error, stop and read it. Never answer it with apt autoremove or apt --fix-broken install without simulating first.
The Orin also has DLA blocks, small deep-learning accelerators next to the GPU. The engines in this guide don't use them, but TensorRT's Python module loads the DLA compiler library when you import it, and that library comes in a separate package. Look at the versions on offer:
apt-cache policy nvidia-l4t-dla-compiler | head -12; dpkg -l nvidia-l4t-core | tail -1 | awk '{print $2,$3}'
On my robot:
nvidia-l4t-dla-compiler:
Installed: (none)
Candidate: 36.4.7-20250918154033
Version table:
36.4.7-20250918154033 600
600 https://repo.download.nvidia.com/jetson/common r36.4/main arm64 Packages
36.4.4-20250616085344 600
600 https://repo.download.nvidia.com/jetson/common r36.4/main arm64 Packages
36.4.3-20250107174145 600
600 https://repo.download.nvidia.com/jetson/common r36.4/main arm64 Packages
36.4.0-20240912212859 600
600 https://repo.download.nvidia.com/jetson/common r36.4/main arm64 Packages
nvidia-l4t-core 36.4.3-20250107174145
apt would pick 36.4.7, but the robot's core is 36.4.3. Install the version that matches exactly, and hold it so a later apt upgrade can't move it. Then refresh the linker's cache:
sudo apt-get install -y nvidia-l4t-dla-compiler=36.4.3-20250107174145 && sudo apt-mark hold nvidia-l4t-dla-compiler
sudo ldconfig
python3 -c "import tensorrt; print('tensorrt', tensorrt.__version__)"
apt should say nvidia-l4t-dla-compiler set on hold. and the last line should print tensorrt 10.3.0. The ldconfig matters. The first time I did this without it, the library file was on disk but the linker didn't know about it yet, and the import failed with the same libnvdla_compiler.so error.
The vision code gets its own Python environment, a venv, so nothing pip installs can replace a system package that ROS 2 depends on. It's created with --system-site-packages, so it can still see the system's tensorrt module and the system OpenCV that ROS 2 uses:
IDX=https://pypi.jetson-ai-lab.io/jp6/cu126/+simple
mkdir -p ~/vision/src ~/vision/engines && cd ~/vision
[ -d venv ] || python3 -m venv --system-site-packages venv
. venv/bin/activate
pip install --upgrade pip setuptools wheel
You may see a red ERROR: pip's dependency resolver ... colcon-core 0.21.3 requires setuptools<80 just above Successfully installed .... It's harmless. colcon runs on the system Python, which this doesn't touch. Check the environment:
head -3 ~/vision/venv/pyvenv.cfg
home = /usr/bin
include-system-site-packages = true
version = 3.10.12
The PyTorch wheels on PyPI for this ARM board run on the CPU only. NVIDIA's Jetson AI Lab publishes GPU wheels for JetPack 6 and CUDA 12.6. The last line below installs everything from that index and nowhere else. The first two lines repeat step 4's setup, in case you're in a new shell:
cd ~/vision && . venv/bin/activate
IDX=https://pypi.jetson-ai-lab.io/jp6/cu126/+simple
pip install --index-url $IDX "torch==2.8.0" "torchvision==0.23.0" "numpy<2" "transformers==4.46.3" "onnx<1.18" pillow "matplotlib<3.9"
Every pin has a reason. torch 2.8.0 and torchvision 0.23.0 are a matched pair, and that pair is what I tested. numpy<2 lets the venv keep the system's numpy 1.21.5, the one OpenCV and ROS 2 came with. transformers 4.46.3 is Hugging Face's model library, which NanoOWL uses for the text half and OWLv2 uses for everything. NanoOWL's engine builder exports to ONNX first, so it needs onnx. Pillow and matplotlib are already satisfied by the system copies.
Use --index-url alone. When I added PyPI as an extra index, pip quietly took the CPU wheel instead. Now check that PyTorch sees the GPU:
cd ~/vision && . venv/bin/activate
python - <<'PY'
import torch, torchvision
print('torch', torch.__version__, 'cuda', torch.cuda.is_available(), torch.version.cuda, 'tv', torchvision.__version__, torch.cuda.get_device_name(0))
from torchvision.ops import roi_align
x = torch.rand(1, 3, 64, 64, device='cuda'); print('roi_align', roi_align(x, [torch.tensor([[0, 0, 32, 32.]], device='cuda')], output_size=(8, 8)).shape)
PY
torch 2.8.0 cuda True 12.6 tv 0.23.0 Orin
roi_align torch.Size([1, 3, 8, 8])
cuda True means torch sees the GPU. roi_align is one of torchvision's compiled GPU operations. If it runs, torchvision matches torch. If you see torch 2.8.0+cpu cuda False, pip took the CPU wheel: run pip uninstall -y torch torchvision and install again with --no-cache-dir.
Both come from NVIDIA's GitHub at the commits I tested:
cd ~/vision && . venv/bin/activate
cd ~/vision/src
[ -d torch2trt ] || git clone https://github.com/NVIDIA-AI-IOT/torch2trt.git
[ -d nanoowl ] || git clone https://github.com/NVIDIA-AI-IOT/nanoowl.git
(cd torch2trt && git checkout -q 4e820ae && pip install --no-build-isolation --no-deps .)
(cd nanoowl && git checkout -q fb553de && pip install --no-build-isolation --no-deps .)
torch2trt loads a TensorRT engine as if it were a PyTorch module. NanoOWL uses it to run its image engine. NanoOWL itself is the OWL-ViT predictor and the engine builder. --no-build-isolation builds with the packages already in the venv, instead of a temporary environment that would fetch its own torch from PyPI. --no-deps stops pip from "fixing" dependencies by pulling in other versions of torch or numpy. Don't use an editable install (pip install -e .). When I tried it, pip complained about a missing build_editable hook and Python couldn't find nanoowl.owl_predictor afterwards.
Check the imports from outside ~/vision/src, so Python loads the installed packages and not the source folders:
cd /tmp && ~/vision/venv/bin/python -c "import transformers, torch2trt, nanoowl; from nanoowl.owl_predictor import OwlPredictor; print('imports ok', transformers.__version__)"
It should print imports ok 4.46.3.
This confirms torch sees the GPU, then builds one engine per patch size. Each build downloads the OWL-ViT weights from Hugging Face, exports the image half to an ONNX file in /tmp, and runs trtexec on it with fp16 at a fixed input of 768x768:
cd ~/vision && . venv/bin/activate
python -c "import torch; assert torch.cuda.is_available(); print('torch', torch.__version__, 'cuda ok')"
for P in 16 32; do
[ -s engines/owl_image_encoder_patch$P.engine ] || \
python -m nanoowl.build_image_encoder_engine engines/owl_image_encoder_patch$P.engine --model_name google/owlvit-base-patch$P
done
echo VISION_INSTALLED
Each build took three to four minutes on my robot. The [ -s ... ] || part skips an engine that already exists, so the loop is safe to run again. If your SSH session might drop, run it under nohup with the output going to a log. Warnings about normalization layers and ONNX opset 17 showed up on my robot too, and they didn't stop the build.
Near the end of each build you'll see a line starting &&&& PASSED TensorRT.trtexec [TensorRT v100300] with the trtexec call NanoOWL made, ending in --fp16 --shapes=image:1x3x768x768. Then list the engines:
ls -la ~/vision/engines/*.engine
On my robot they were 181,223,740 bytes for patch16 and 183,576,780 bytes for patch32. An earlier build on the same robot gave 181,804,636 and 183,555,548 bytes, so yours will differ a little.
The GPU takes its memory from the shared 16 GB. I never measured how much a build needs at its peak. On this first pass nothing else uses the GPU. If you rebuild the engines later, after a TensorRT change, first stop every other program that uses the GPU.
When transformers loads a model for the first time, it downloads the weights into ~/.cache/huggingface/hub/ and reads them from there afterwards. Step 7's builds fetched both OWL-ViT models. NanoOWL needs them at run time too, for the text half. Check:
du -sh ~/.cache/huggingface/hub/models--*
585M /home/burgerbarn/.cache/huggingface/hub/models--google--owlvit-base-patch16
587M /home/burgerbarn/.cache/huggingface/hub/models--google--owlvit-base-patch32
A third folder, models--google--owlv2-base-patch16-ensemble, about 593 MB, appears the first time you run OWLv2 later in this chapter. The first load of each model needs internet.
Recognising a face uses facenet-pytorch, a face detector plus a network that turns a face into a fingerprint of numbers. It's installed without its dependencies, so pip leaves the Jetson's GPU torch alone. The first and last lines check torch before and after:
cd ~/vision && . venv/bin/activate
python -c "import torch; print('before torch', torch.__version__, torch.cuda.is_available())"
pip install --no-deps facenet-pytorch==2.6.0
python -c "import torch; print('after torch', torch.__version__, torch.cuda.is_available()); from facenet_pytorch import MTCNN, InceptionResnetV1; print('facenet ok')"
before torch 2.8.0 True
Successfully installed facenet-pytorch-2.6.0
after torch 2.8.0 True
facenet ok
The first time a face program runs, it downloads its weights, 107 MB, to ~/.cache/torch/checkpoints/.
The install commands of steps 2 to 7 are the lines of scripts/install_vision.sh, in order, and step 1 copied that file to ~/setup/. Instead of typing the steps, you can run it in one piece. On my robot, on a freshly installed system, this took 11 minutes 43 seconds and ended with VISION_INSTALLED and both engines:
nohup bash ~/setup/install_vision.sh > ~/setup/install_vision.log 2>&1 &
It stops at the first line that fails. Every step is safe to repeat, so fix the problem and run it again. Step 9, facenet, is not in the script. Run it by hand afterwards. Then do the checks from steps 2 to 8 anyway, because the log is long and a check is quicker than reading it.
Two small programs from step 1 do this by hand. The first, ~/vision/grab.py, runs in the system Python with ROS 2, not in the venv. It subscribes to the colour and depth images, keeps the first message of each, and saves them:
"""Save one frame of /aurora/rgb/image_raw (and depth) to ~/vision/frame_rgb.png / frame_depth.npy."""
import numpy as np, rclpy, cv2
from rclpy.node import Node
from sensor_msgs.msg import Image
got = {}
class G(Node):
def __init__(self):
super().__init__('grab')
for k, t in (('rgb', '/aurora/rgb/image_raw'), ('depth', '/aurora/depth/image_raw')):
self.create_subscription(Image, t, lambda m, k=k: got.setdefault(k, m), 5)
rclpy.init(); n = G()
while len(got) < 2: rclpy.spin_once(n, timeout_sec=1)
m = got['rgb']; print('rgb', m.width, m.height, m.encoding, m.header.frame_id)
a = np.frombuffer(m.data, np.uint8).reshape(m.height, m.width, -1)
cv2.imwrite('frame_rgb.png', cv2.cvtColor(a, cv2.COLOR_RGB2BGR) if m.encoding == 'rgb8' else a)
d = got['depth']; print('depth', d.width, d.height, d.encoding, d.header.frame_id)
np.save('frame_depth.npy', np.frombuffer(d.data, np.uint16).reshape(d.height, d.width))
setdefault keeps the first message and ignores the rest. The loop has no time limit, so you run it under timeout. A ROS image message is a flat buffer of bytes plus width, height and encoding, and np.frombuffer(...).reshape(...) turns it into an image array. OpenCV writes images in blue-green-red order. The camera publishes bgr8, so the array is written as it is. Depth is 16 bits per pixel, in millimetres.
The camera rides on the arm, so where it points depends on the arm's pose. In the drive pose from chapter 7 it looks 30 degrees down at the floor. Once my arm was still in the drive pose when I grabbed a frame. The frame showed only the rug, and every detection came back empty. Tuck the arm first, and check where the camera points. The arm moves here, so keep clear of it:
source /opt/ros/humble/setup.bash
timeout 30 ros2 service call /rosorin_board_driver/arm/tuck std_srvs/srv/Trigger | grep -o '"tucked": [a-z]*'
timeout 6 ros2 run tf2_ros tf2_echo base_link camera_link 2>/dev/null | grep -m1 "RPY (degree)"
On my robot that printed "tucked": true and RPY [0.295, -3.358, 0.498]. The middle number is the pitch. You want it between about -3 and -7 degrees, camera level. The drive pose reads about +30. The last number is the yaw, and it should be near 0. The tuck leaves the arm's base joint where it is. If the yaw is far off, centre that joint with the block at the start of chapter 9's floor tests, which moves to chapter 7's drive pose with drive_pan set to 500, and tuck again. Mine was already near 0, so I didn't need that here. Then grab the frame:
source /opt/ros/humble/setup.bash
cd ~/vision && timeout 20 python3 grab.py
rgb 640 400 bgr8 rgb_camera_link
depth 640 400 mono16 depth_camera_link
Now ~/vision/frame_rgb.png and ~/vision/frame_depth.npy exist. Copy the picture to your laptop and look at it:
scp rosorin:vision/frame_rgb.png .
If grab.py prints nothing and timeout ends it after 20 seconds, no frames are arriving. Check the camera with timeout 8 ros2 topic hz /aurora/rgb/image_raw, which should report about 14 frames a second. Once on my robot the camera service said it was active but published nothing, and sudo systemctl restart rosorin-camera brought the frames back.
The second program, ~/vision/detect.py, needs no ROS. It scores your prompts on the image, prints each hit with its score, box and the median depth inside the box, and saves a copy of the image with the boxes drawn:
"""Open-vocabulary detection on the robot (NanoOWL = OWL-ViT with a TensorRT image encoder, NVIDIA-AI-IOT, Apache-2.0).
Run in ~/vision/venv. Usage:
python detect.py frame_rgb.png [--depth frame_depth.npy] [--prompts "a microphone,a television,a speaker"] [--th 0.1]
Writes <image>_det.png (boxes) and prints label, score, box and median depth inside the box (metres; depth is
the Aurora depth image at the same 640x400 size, assumed roughly aligned with RGB - first cut)."""
import argparse, os, time
import cv2
import numpy as np
import PIL.Image
from nanoowl.owl_predictor import OwlPredictor
HERE = os.path.dirname(os.path.abspath(__file__))
PROMPTS = 'a microphone,a television,a speaker'
ap = argparse.ArgumentParser()
ap.add_argument('image')
ap.add_argument('--depth')
ap.add_argument('--prompts', default=PROMPTS)
ap.add_argument('--th', type=float, default=0.1)
ap.add_argument('--model', default='16', choices=['16', '32'], help='OWL-ViT base patch size (16 = finer, slower)')
a = ap.parse_args()
t = time.time()
pred = OwlPredictor(f'google/owlvit-base-patch{a.model}',
image_encoder_engine=os.path.join(HERE, 'engines', f'owl_image_encoder_patch{a.model}.engine'))
text = [p.strip() for p in a.prompts.split(',') if p.strip()]
enc = pred.encode_text(text)
print(f'load {time.time() - t:.1f}s')
img = PIL.Image.open(a.image).convert('RGB')
for i in range(3): # first call warms up
t = time.time()
out = pred.predict(image=img, text=text, text_encodings=enc, threshold=a.th, pad_square=False)
dt = time.time() - t
print(f'predict {dt * 1000:.0f} ms')
depth = np.load(a.depth) if a.depth else None
vis = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
for lab, sc, box in zip(out.labels.tolist(), out.scores.tolist(), out.boxes.tolist()):
x0, y0, x1, y1 = [int(round(v)) for v in box]
d = ''
if depth is not None:
cx0, cx1 = x0 + (x1 - x0) // 4, x1 - (x1 - x0) // 4
cy0, cy1 = y0 + (y1 - y0) // 4, y1 - (y1 - y0) // 4
roi = depth[max(0, cy0):cy1, max(0, cx0):cx1]
v = roi[roi > 0]
d = f' depth {np.median(v) / 1000:.2f} m ({v.size / max(1, roi.size):.0%} valid)' if v.size else ' depth n/a'
print(f'{text[lab]:14} {sc:.2f} box ({x0},{y0})-({x1},{y1}){d}')
cv2.rectangle(vis, (x0, y0), (x1, y1), (0, 200, 255), 2)
cv2.putText(vis, f'{text[lab]} {sc:.2f}', (x0, max(12, y0 - 4)), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 200, 255), 1)
cv2.imwrite(os.path.splitext(a.image)[0] + '_det.png', vis)
Read it top to bottom. OwlPredictor takes the Hugging Face model name, for the text half and the box maths, and the path of the image engine. encode_text turns the prompts into vectors once, and they're reused for every image. Prediction runs three times and reports the time of the last run, because the first call of a GPU program is slow while it warms up. pad_square=False stretches the 640x400 frame to the square input instead of padding it. For depth, it takes the middle half of each box, so the object's edges and the background behind it are left out. It keeps the pixels that have a depth reading and reports their median in metres, and the share of pixels that had one.
Run it on your frame with both engines, then copy the result to your laptop:
cd ~/vision && . venv/bin/activate
python detect.py frame_rgb.png --depth frame_depth.npy --model 32
python detect.py frame_rgb.png --depth frame_depth.npy --model 16
scp rosorin:vision/frame_rgb_det.png .
My frame came from the tucked arm in a dim room, facing a TV and two speakers. Change the prompts with --prompts to match things in your own room. Patch32 printed this:
load 3.1s
predict 28 ms
a speaker 0.14 box (289,47)-(328,91) depth 3.01 m (100% valid)
a speaker 0.15 box (279,110)-(330,159) depth n/a
a television 0.54 box (378,138)-(527,240) depth n/a
And patch16, on the same frame:
load 3.5s
predict 115 ms
a speaker 0.21 box (278,113)-(326,159) depth n/a
a television 0.53 box (384,142)-(519,235) depth n/a
What counts is a load of a few seconds, a predict of tens of milliseconds for patch32 and around 100 for patch16, and boxes on things you can see in frame_rgb_det.png. On a later run, in the same room in the evening, patch32 took 30 ms and found nothing above 0.1, while patch16 took 74 ms and found both speakers at 0.21 and 0.20. In a dim frame, patch32 can miss what patch16 finds.
In that output, the first a speaker at 0.14, with a depth of 3.01 m, was really the lampshade above the speaker. Adding "a lamp" to the prompts gave it its own label. That's the idea behind the decoys you'll meet below. The TV and the speakers have depth n/a. The depth camera gets no reading from dark or shiny surfaces, so placing those things in 3D needs another source, such as the LiDAR along the same bearing. And the wording of a prompt changes the score. On the same frame, "a tv" scored 0.43 where "a television" scored 0.54. Try your own wordings:
python detect.py frame_rgb.png --depth frame_depth.npy --model 32 --prompts "a tv,a speaker cabinet,a mic,a lampshade,a guitar"
If you only get the load and predict lines and no boxes, nothing scored at or above the threshold of 0.1. A dark scene and a broken install look the same here. Grab a frame of a well-lit object that matches a prompt, or run with --th 0.02 to see low-scoring boxes and confirm the box and depth code runs. A FileNotFoundError for an .engine file means step 7 didn't finish for that patch size. Two TensorRT warnings, Using default stream in enqueueV3() and Using an engine plan file across different models of devices, are harmless. Both appeared in the runs above.
~/vision/bench_live.py runs a detector on the live camera stream for 20 seconds and reports frames per second, latency, GPU load and board power. Run it with the camera on and the robot standing still:
source /opt/ros/humble/setup.bash
cd ~/vision && . venv/bin/activate
for m in 32 16; do python bench_live.py --model $m --seconds 20 2>&1 | grep -v Warn | tail -3; done
Without navigation running, my robot printed this:
NanoOWL patch32, 5 prompts: 283 frames in 20 s = 14.2 fps (camera-limited if ~= camera rate) | latency ms p50 49 p95 52
GPU busy 53% (max 99%) | CPU avg 19% | RAM 3697 MB | board power 8.5 W
seen: {'a person': 0.28, 'a face': 0.27, 'a cat': 0.14}
NanoOWL patch16, 5 prompts: 232 frames in 20 s = 11.6 fps (camera-limited if ~= camera rate) | latency ms p50 69 p95 77
GPU busy 73% (max 99%) | CPU avg 16% | RAM 3591 MB | board power 21.9 W
seen: {'a person': 0.18}
The camera publishes about 14 frames a second, so patch32 keeps up with every frame using about half the GPU. Later, with the camera odometry and navigation of chapters 9 and 10 running at the same time, patch32 still did 14.3 fps at 42 ms median latency, and patch16 dropped to 10.4 fps at 80 ms.
OWLv2 is the slow, careful one. This times it with the robot's detector factory, described in the next section, on the frame you saved. The first call loads the model, and downloads it on a new robot. The second call is timed:
source /opt/ros/humble/setup.bash
cd ~/vision && . venv/bin/activate && python -c "
import time, PIL.Image, sys; sys.argv=['x']
from scan import make_detector
t = ['a microphone', 'a television', 'a speaker', 'a lamp']
d = make_detector('owlv2', '16', t)
img = PIL.Image.open('frame_rgb.png').convert('RGB')
d(img, 0.15); s = time.time(); r = d(img, 0.15); print('ms', round((time.time()-s)*1000))
for x in r: print(x[0], round(x[1], 2), [int(v) for v in x[2]])
" 2>&1 | grep -vE "arn|^ "
On the same scene as the NanoOWL run above, it printed:
ms 946
a television 0.62 [411, 113, 529, 194]
a speaker 0.6 [299, 81, 339, 129]
a speaker 0.57 [87, 55, 136, 106]
a speaker 0.36 [562, 168, 580, 209]
a lamp 0.34 [305, 12, 340, 83]
a microphone 0.17 [190, 50, 205, 68]
OWLv2 found both speakers and a small microphone that NanoOWL missed, at about 30 times the cost. On a later run it took 1125 ms and found both speakers at 0.69 and 0.67 and the lamp at 0.47, but not the microphone. Loading it takes about 13 seconds.
Everything on the robot that detects objects gets its detector from one function, make_detector() in ~/vision/scan.py. It returns a function detect(image, threshold) that gives back a list of (label, score, [x0, y0, x1, y1]), best first. Its signature:
def make_detector(kind, model, text, iou=0.3, per_label=3, decoys=()):
kind is 'owlv2' or 'nanoowl'. model is the patch size, '16' or '32', and only matters for NanoOWL. text is the list of prompts. iou=0.3 is the NMS overlap limit, per_label=3 the most boxes kept for each label, and decoys the labels that exist only to catch look-alikes.
The OWLv2 branch loads the model in fp16 on the GPU. It decodes the boxes itself instead of calling the library's post-processing, so each box keeps its class embedding, a fingerprint of what's in the box that later code can learn from. OWLv2 pads the image to a square from the top-left, so boxes are scaled by the longer side:
if kind == 'owlv2':
from transformers import Owlv2ForObjectDetection, Owlv2Processor
name = 'google/owlv2-base-patch16-ensemble'
proc = Owlv2Processor.from_pretrained(name)
net = Owlv2ForObjectDetection.from_pretrained(name, torch_dtype=torch.float16).cuda().eval()
def raw(img, th):
inp = proc(text=[text], images=img, return_tensors='pt').to('cuda')
inp['pixel_values'] = inp['pixel_values'].half()
with torch.no_grad():
out = net(**inp)
s = max(img.size) # OWLv2 pads to a square (top-left)
# same maths as proc.post_process_object_detection (sigmoid of the best query logit, cxcywh -> xyxy
# scaled to the padded square), done here so each box keeps its class embedding ("fingerprint")
scores, labels = torch.sigmoid(out.logits[0].float()).max(-1)
keep = scores > th
b = out.pred_boxes[0][keep].float()
boxes = torch.stack([b[:, 0] - b[:, 2] / 2, b[:, 1] - b[:, 3] / 2,
b[:, 0] + b[:, 2] / 2, b[:, 1] + b[:, 3] / 2], 1) * s
emb = torch.nn.functional.normalize(out.class_embeds[0][keep].float(), dim=-1)
return labels[keep], scores[keep], boxes, emb
The NanoOWL branch is the same OwlPredictor call as in detect.py. The encoded prompts live in a small dict, st, so new words can replace them later:
else:
from nanoowl.owl_predictor import OwlPredictor
pred = OwlPredictor(f'google/owlvit-base-patch{model}',
image_encoder_engine=os.path.join(HERE, 'engines', f'owl_image_encoder_patch{model}.engine'))
st = {'enc': pred.encode_text(text)}
def raw(img, th):
o = pred.predict(image=img, text=text, text_encodings=st['enc'], threshold=th, pad_square=False)
return o.labels, o.scores.float(), o.boxes.float(), None
Both branches share detect(). For each label it runs NMS and keeps the best three boxes. Then comes the decoy rule. A target box is dropped when a decoy box overlaps it by an IoU of 0.5 or more and scores at least as high. So a lampshade that scores as "a speaker" is removed when "a lamp" scores the same box higher:
def detect(img, th, with_embeds=False):
"""with_embeds: 4-tuples (label, score, box, embedding) - owlv2 only (embedding None for nanoowl)."""
labels, scores, boxes, emb = raw(img, th)
out = []
for li in set(labels.tolist()):
idx = torch.nonzero(labels == li).squeeze(1)
keep = nms(boxes[idx].cpu(), scores[idx].cpu(), iou)[:per_label]
out += [(text[li], float(scores[idx[k]]), boxes[idx[k]].tolist(),
emb[idx[k]].cpu() if emb is not None else None) for k in keep]
# a target box that mostly overlaps a stronger decoy box (lamp, tower fan) is that decoy, not the target
dec = [d for d in out if d[0] in decoys]
if dec:
db = torch.tensor([d[2] for d in dec])
out = [d for d in out if d[0] in decoys or not any(
s >= d[1] and v >= 0.5 for s, v in zip((x[1] for x in dec), box_iou(torch.tensor([d[2]]), db)[0].tolist()))]
out = sorted(out, key=lambda d: -d[1])
return out if with_embeds else [d[:3] for d in out]
The factory also attaches detect.add_labels(new), which teaches new words while the detector is running. It adds them to the same prompt list and, for NanoOWL, encodes the prompts again once.
Why two detectors? NanoOWL patch32 keeps up with the camera at half the GPU, which is what following a person needs. OWLv2 is about 30 times slower but finds small things NanoOWL misses, which is what a careful look at a still scene needs. Both come from the same factory, so a program switches between them with one argument.
The robot's standing prompts and their thresholds are in ~/vision/attention.py:
PROMPTS = ['a face', 'a person', 'a hand']
TH = {'a face': 0.2, 'a person': 0.25, 'a hand': 0.22}
OBJECTS = ['a cup', 'a phone', 'a bag', 'a box', 'a cable', 'a shoe', 'a guitar', 'a laptop']
TH.update({o: 0.2 for o in OBJECTS})
The robot's own loop, vision/mind.py, builds one NanoOWL patch32 detector with all of these words. It calls the detector with a low raw threshold of 0.12, then keeps each hit only if it reaches that label's own threshold. Words taught later get 0.2. Chapter 13 describes that loop, but it has no tested install step for it.
The person threshold works well. On 96 frames I labelled by hand, the detector found a person in 54 of the 57 frames that had one, including 22 of 24 where the person was only partly in view, seen from behind or lying down. It raised no false alarm in the 39 frames without anyone.
The hand threshold of 0.22 was typed in, not measured, and it hides most hands. On 48 labelled frames it found 4 of 14 visible hands with no false alarms. At 0.18 it found 9 of 14 with 2 false alarms out of 15, and at 0.12, 13 of 14 with 8 false alarms. No threshold separates hands from everything else, and OWLv2 did worse while taking over a second per frame.
Small objects are mostly a matter of size, not threshold. At the distance the robot usually keeps from a person, about 1.2 m, a cup someone holds up is only 25 to 30 pixels wide, and it's rarely detected.
The repo has a rollback script, scripts/rollback_vision.sh, that is meant to remove everything this chapter installed. I have never run it, and you shouldn't run it as it is: its last real line is sudo apt-get autoremove -y, which can remove initramfs-tools and leave the robot unable to boot. There is no tested way back from this chapter: the backup sets from chapter 5 have never been written back onto the robot.
You're ready for the next chapter when python3 -c "import tensorrt; print(tensorrt.__version__)" prints 10.3.0, apt-mark showhold | grep dla prints nvidia-l4t-dla-compiler and apt-mark showhold | grep -c nvidia-l4t prints 46, the venv's torch is 2.8.0 with torch.cuda.is_available() True, ~/vision/engines/ holds two engines of about 182 MB each, detect.py on your own frame draws boxes on things you can see with patch32 in tens of milliseconds, and you've made a fresh backup as in chapter 5.