Real-time image and data processing, and sensor interfacing
UAT 462 Edge Artificial Intelligence for UAS
Lesson
By the end of this module you will be able to
- Compute camera bandwidth and main-memory traffic per frame, and explain avoiding repeated copies (zero-copy)
- Separate latency from throughput, and use Little's law to find the number of frames in the system
- Simulate the queue of a processing pipeline and choose a frame-dropping policy that bounds latency
- Compute the time a transaction occupies on I2C, SPI and UART and the share of the bus used, to choose a bus for each sensor
- Estimate the offset between two clocks with a two-way time exchange, and turn a time error into a position error
- Turn a detection into a ground position, find the frame rate and speed that stop in time for an obstacle, and design confirmation before pausing a mission
- Explain what visual odometry and SLAM compute and why they run on board, and check the compute budget, latency and drift of a VIO pipeline on an embedded board
Why this matters
A real-time system does not mean the fastest one; it means one that answers by its deadline, predictably. The case study’s deadlines are: patrol mode detects at 1 fps or more, evidence mode at 10 fps or more with p95 at most 100 ms (R2). A model that is fast on average but slow now and then makes the image used for a decision too old. And the data flowing into the processing pipeline comes from two directions: images from the camera, and numbers from sensors (position, attitude, height) that must be read in time and in step with the images, or geotagged images will be off by tens of centimetres.
From the camera into memory
A camera connects to the on-board computer in several ways. MIPI CSI-2 is a camera interface that connects directly to the processor. The current specification is version 4.2, running over the D-PHY, C-PHY and A-PHY physical layers (MIPI Alliance). USB serves cameras that follow the USB video standard, for which the USB-IF lists SuperSpeed rates of 5, 10 and 20 Gbit/s. These are nominal maximum rates and real data transfer is lower, so allow for efficiency. Raw image data uses bandwidth by , where is bytes per pixel (NV12 uses 1.5).
Link bandwidth is not the only issue. One frame passes through memory several times: the camera writes it into a buffer, the resize step reads the full image and writes the model input, and the model reads that input. If every stage first copies the data into its own buffer, the reads and writes double. Linux uses DMABUF to avoid the copies. The kernel documentation describes it as a generic way of sharing buffers between devices: the driver allocates buffers and exports them to the application as file descriptors, and only the descriptors are exchanged, not the data (V4L2 DMABUF). This is zero-copy.
Example 1 How many times does a frame pass through memory, and how much does zero-copy help?
Compare three camera modes (NV12): does the raw data fit a USB link (using the 5 Gbit/s the USB-IF states with an assumed 70% real efficiency), and how much main-memory read and write per frame results when buffers are shared, against copying twice (assumed DRAM 12 GB/s, CPU copy 4 GB/s)?
# camera bandwidth and main-memory traffic per frame: copying at every stage against sharing buffers (zero-copy)
USB_NOMINAL_GBPS, USB_EFFICIENCY = 5.0, 0.70 # USB 5 Gbit/s as stated by the USB-IF; real efficiency assumed 70 %
DRAM_GBPS, COPY_GBPS = 12.0, 4.0 # board DRAM bandwidth and CPU copy rate (assumed)
model_in = 640 * 640 * 3 # int8 model input after letterbox
print(f"usable USB payload about {USB_NOMINAL_GBPS * USB_EFFICIENCY:.1f} Gbit/s = {USB_NOMINAL_GBPS * USB_EFFICIENCY * 125:.0f} MB/s")
print(f"{'camera mode':18s} {'raw MB/s':>9s} {'fits USB':>8s} {'zero-copy MB/frame':>19s} {'copying MB/frame':>17s} {'copy CPU ms':>11s} {'DRAM share (copying)':>21s}")
for name, w, h, fps in (("1080p30 NV12", 1920, 1080, 30), ("4K30 NV12", 3840, 2160, 30), ("4K60 NV12", 3840, 2160, 60)):
frame = w * h * 3 // 2 # NV12 uses 1.5 bytes per pixel
raw = frame * fps / 1e6
zero = frame + (frame + model_in) + model_in # camera write, resize reads the frame and writes the model input, the model reads the input
copy = zero + 2 * frame + 2 * model_in # plus two copies, each one a read and a write
copy_ms = (frame + model_in) / (COPY_GBPS * 1e9) * 1e3
print(f"{name:18s} {raw:9.0f} {str(raw <= USB_NOMINAL_GBPS * USB_EFFICIENCY * 125):>8s} {zero / 1e6:19.1f} {copy / 1e6:17.1f} {copy_ms:11.2f} {copy * fps / (DRAM_GBPS * 1e9) * 100:20.1f} %")
usable USB payload about 3.5 Gbit/s = 438 MB/s
camera mode raw MB/s fits USB zero-copy MB/frame copying MB/frame copy CPU ms DRAM share (copying)
1080p30 NV12 93 True 8.7 17.4 1.08 4.3 %
4K30 NV12 373 True 27.3 54.7 3.42 13.7 %
4K60 NV12 746 False 27.3 54.7 3.42 27.3 %
At 1080p30 the raw data of 93 MB/s fits USB comfortably. Copying raises the read and write from 8.7 to 17.4 MB per frame, using 4.3% of DRAM and 1.08 ms of CPU time per frame, which is small and not the first thing to tune. At 4K30 it is 13.7% and 3.42 ms. At 4K60 the raw 746 MB/s exceeds the usable USB link, so compression or CSI is needed, and copying takes 27.3% of DRAM. The conclusion: zero-copy matters when resolution, frame rate or camera count is high, but at the case study’s 1080p30, measuring first will point to a bottleneck elsewhere (the DRAM and CPU figures in the example are assumed).
Latency and throughput
Latency is the time one frame takes from entry to result. Throughput is the number of frames finished per second. They answer different questions and are not always reciprocals. When stages overlap as a pipeline, throughput is set by the slowest stage while latency is the sum of all stages. Little’s law (1961) links the two with the number of frames in the system: , where is the rate at which frames pass and is the time a frame spends in the system.
Example 2 One frame at a time against a pipeline
Three stages per frame: pre-processing 6 ms, inference 28 ms, post-processing 4 ms (assumed). Compare finishing one frame before starting the next with a pipeline in which all stages overlap.
# latency against throughput: stages run one after another, against a pipeline whose stages overlap (stage times assumed)
stages = {"pre-process": 6.0, "inference": 28.0, "post-process": 4.0} # milliseconds per frame
latency = sum(stages.values())
sequential_fps = 1000 / latency # one frame finishes before the next starts
pipelined_fps = 1000 / max(stages.values()) # the slowest stage sets the throughput
print(f"latency of one frame {latency:.0f} ms in both designs")
print(f"sequential: {sequential_fps:.1f} fps, frames in flight (Little) {sequential_fps * latency / 1000:.2f}")
print(f"pipelined : {pipelined_fps:.1f} fps, frames in flight (Little) {pipelined_fps * latency / 1000:.2f}")
print("slowest stage:", max(stages, key=stages.get), "-> speeding up any other stage does not raise the pipelined throughput")
latency of one frame 38 ms in both designs
sequential: 26.3 fps, frames in flight (Little) 1.00
pipelined : 35.7 fps, frames in flight (Little) 1.36
slowest stage: inference -> speeding up any other stage does not raise the pipelined throughput
The latency of a single frame is 38 ms in both designs, but the throughput differs: one at a time gives 26.3 fps and the pipeline 35.7 fps, because the inference stage (28 ms) sets the pace, and in the pipeline there are on average 1.36 frames in the system by Little’s law. An important consequence: speeding up a stage other than the slowest does not raise the pipeline’s throughput, and the latency stays the same unless a stage’s time is reduced.
Queues, tail latency and dropping frames
Frames arrive at the camera’s pace (every 33.3 ms at 30 fps), but processing time is not constant. When the mean processing time exceeds the interval (load ), or there are occasional spikes, frames must wait. An unbounded queue makes latency grow and grow until the result is an image from several seconds ago, which is useless for real-time work. The way out is to bound the queue and drop frames. The “latest frame wins” policy (a queue of one, dropping the older frame) suits work that needs the present image.
A report must state the scenario and the percentile. MLPerf Inference is a model of stating the measurement conditions. It separates the single-stream, multistream, server and offline scenarios, and it sets a run duration of 600 seconds. In this course, jitter is measured as the gap between p99 and p50.
Example 3 Three queue policies when the model is slower than the camera
A 30 fps camera feeds one processor. The mean time per frame is about 38 ms (matching the one-at-a-time design of Example 2), more than the 33.3 ms interval, with occasional spikes (simulated). Compare an unbounded FIFO, a queue of two that drops the newest frame, and a queue of one that drops the oldest. Measure latency from capture to result, then check Little’s law by counting the frames in the system directly.
import numpy as np
# a 30 fps camera feeds one processor: mean time per frame exceeds 33.3 ms and there are occasional spikes (simulated)
rng = np.random.default_rng(12)
N, period = 3000, 1 / 30
arrival = np.arange(N) * period
service = 0.022 + rng.gamma(8, 0.0018, N) + np.where(rng.random(N) < 0.02, 0.08, 0.0)
print(f"mean service {service.mean() * 1e3:.1f} ms against frame period {period * 1e3:.1f} ms; load {service.mean() / period:.2f}")
def run(capacity, drop):
queue, free, done = [], 0.0, [] # done = (arrival time, finish time)
def serve_until(t):
nonlocal free
while queue and free <= t:
j = queue.pop(0)
free = max(free, arrival[j]) + service[j]
done.append((arrival[j], free))
for i in range(N):
serve_until(arrival[i])
if free <= arrival[i] and not queue:
free = arrival[i] + service[i]
done.append((arrival[i], free))
elif capacity is None or len(queue) < capacity:
queue.append(i)
elif drop == "oldest":
queue.pop(0)
queue.append(i) # drop the oldest frame, keep the new one
serve_until(float("inf"))
return np.array(done)
print(f"{'policy':28s} {'processed':>9s} {'dropped':>8s} {'p50 ms':>8s} {'p95 ms':>8s} {'p99 ms':>8s}")
for name, cap, drop in (("unbounded FIFO", None, None), ("queue of 2, drop newest", 2, "newest"), ("queue of 1, drop oldest", 1, "oldest")):
d = run(cap, drop)
lat = (d[:, 1] - d[:, 0]) * 1e3
print(f"{name:28s} {len(d):9d} {(1 - len(d) / N) * 100:7.1f}% {np.percentile(lat, 50):8.1f} {np.percentile(lat, 95):8.1f} {np.percentile(lat, 99):8.1f}")
d = run(1, "oldest")
rate = len(d) / (d[:, 1].max() - d[:, 0].min()) # Little: mean frames in the system = throughput x mean time in the system
mean_time = np.mean(d[:, 1] - d[:, 0])
grid = np.arange(d[:, 0].min(), d[:, 1].max(), 0.001) # count the frames in the system every 1 ms and average
counted = np.searchsorted(d[:, 0], grid, side="right") - np.searchsorted(d[:, 1], grid, side="right")
print(f"Little's law, queue of 1: throughput {rate:.1f} fps x mean time {mean_time * 1e3:.1f} ms = {rate * mean_time:.2f}; counted directly {counted.mean():.2f} frames")
mean service 37.9 ms against frame period 33.3 ms; load 1.14
policy processed dropped p50 ms p95 ms p99 ms
unbounded FIFO 3000 0.0% 6762.2 12992.1 13469.8
queue of 2, drop newest 2635 12.2% 92.1 159.3 186.4
queue of 1, drop oldest 2647 11.8% 52.5 71.4 129.3
Little's law, queue of 1: throughput 26.5 fps x mean time 53.6 ms = 1.42; counted directly 1.42 frames
The unbounded FIFO processes every frame, but the median latency is 6.8 seconds and p95 about 13.0 seconds, which is unusable. The queue of two that drops the newest drops 12.2%, and its p95 of 159 ms still exceeds the 100 ms of R2 because a queued frame waits for the one before it. The queue of one that drops the oldest drops 11.8% but has p50 52.5 ms and p95 71.4 ms, which meets the limit; p99 of 129 ms shows that spikes still need attention. Dropping 11.8% is the price of fresh images. Little’s law agrees: 26.5 fps times a mean time of 53.6 ms gives 1.42 frames, matching the direct count. Dropping frames in the detection pipeline must not lose evidence, so the team records video on a separate path, apart from the detection pipeline.
Batching
An accelerator usually has a fixed start-up cost per call. Grouping several images into a batch shares that cost, so throughput rises, but the first image of the batch must wait for the others, so latency rises.
Example 4 Which batch size suits which job?
The time of a batch of is 9 ms + 2.5 ms × (assumed). Look at throughput and latency when images arrive one by one from a 30 fps camera (the first frame of a batch must wait), against when the 12 crops of one frame are ready at once.
# batching: the time of a batch of b = a fixed cost + b x time per item (assumed)
T0, T1 = 9.0, 2.5 # ms: accelerator launch cost, and time per item
frame_gap = 1000 / 30 # ms between frames of a 30 fps camera
print(f"{'batch':>5s} {'time ms':>8s} {'throughput fps':>15s} {'live: oldest frame waits':>25s} {'live: worst latency ms':>23s} {'tiles ready at once: ms/tile':>29s}")
for b in (1, 2, 4, 8, 12):
t = T0 + T1 * b
wait = (b - 1) * frame_gap # the first frame of a batch waits for the others to arrive
print(f"{b:5d} {t:8.1f} {b / t * 1000:15.0f} {wait:22.1f} ms {wait + t:23.1f} {t / b:29.2f}")
batch time ms throughput fps live: oldest frame waits live: worst latency ms tiles ready at once: ms/tile
1 11.5 87 0.0 ms 11.5 11.50
2 14.0 143 33.3 ms 47.3 7.00
4 19.0 211 100.0 ms 119.0 4.75
8 29.0 276 233.3 ms 262.3 3.62
12 39.0 308 366.7 ms 405.7 3.25
A batch of 4 gives 211 fps, but from a live camera the first frame waits 100 ms and the worst latency is 119 ms, over the 100 ms limit of evidence mode. Batches of at most 2 (47.3 ms) pass. For work where all images are ready together, such as the 12 crops of one frame, a single batch takes 39.0 ms, or 3.25 ms per image, against 11.5 ms per image one at a time, about 3.5 times faster. So use batches for the crops of one frame (patrol mode) and batch size 1 for the live camera in evidence mode.
Sensor interfacing: the time budget of a bus
Sensors connect to the computer through I2C, SPI or UART. The protocols of each were covered in UAT 204 module 4; here we use them to compute a time budget and decide which sensor belongs on which bus. The time one transaction occupies a bus follows from these facts. I2C sends every byte with 9 clock periods (8 data bits plus an acknowledge bit), the first byte is the 7-bit device address with the read/write bit, and standard speeds are 100 kbit/s, 400 kbit/s and 1 Mbit/s (NXP, UM10204). Reading register bytes therefore takes about clock periods (address-write, register, address-read, the data, and about 3 more for start, repeated start and stop, which is an estimate). SPI uses 8 clock periods per byte plus chip-select set-up. An 8N1 UART uses 10 bits per byte, so it moves baud/10 bytes per second (Microchip, TB3216). The design rule used in this course (assumed) is that each bus is used at most 50%, to leave room for variation.
Example 5 Which bus should these sensors be on?
Compute the time per transaction and the share of the bus used for an assumed sensor set: a 1 kHz IMU on I2C at 400 kHz against SPI at 8 MHz; a barometer, magnetometer, laser altimeter and power monitor on I2C; and a GNSS receiver on UART at 115200, both plain messages and raw data.
# time one transaction occupies a bus, and the share of bus time used, from each bus's formulas
def i2c_us(n, f_hz): # address-write, register, address-read and n data bytes, 9 clocks per byte, plus start/stop
return (9 * (3 + n) + 3) / f_hz * 1e6
def spi_us(n, f_hz, setup_us=2.0): # command byte + n data bytes at 8 clocks each, plus chip-select setup
return 8 * (1 + n) / f_hz * 1e6 + setup_us
def uart_us(n, baud): # 8N1: 10 bits per byte
return 10 * n / baud * 1e6
sensors = [ # (name, bus, bytes per transaction, transactions per second, time per transaction in µs) all assumed
("IMU 1 kHz on I2C 400 kHz", "i2c", 14, 1000, i2c_us(14, 400e3)),
("IMU 1 kHz on SPI 8 MHz", "spi", 14, 1000, spi_us(14, 8e6)),
("barometer", "i2c", 6, 50, i2c_us(6, 400e3)),
("magnetometer", "i2c", 8, 100, i2c_us(8, 400e3)),
("laser altimeter", "i2c", 9, 100, i2c_us(9, 400e3)),
("power monitor", "i2c", 4, 20, i2c_us(4, 400e3)),
("GNSS 10 Hz, 120 B, UART 115200", "uart", 120, 10, uart_us(120, 115200)),
("GNSS raw 5 Hz, 1600 B, UART 115200", "uart", 1600, 5, uart_us(1600, 115200)),
("GNSS raw 5 Hz, 1600 B, UART 460800", "uart", 1600, 5, uart_us(1600, 460800))]
for name, bus, n, rate, us in sensors:
print(f"{name:36s} {us:9.1f} us per transaction x {rate:4d}/s = {us * rate / 1e4:6.2f} % of the {bus} bus")
i2c_total = sum(us * rate / 1e4 for name, bus, n, rate, us in sensors if bus == "i2c" and "SPI" not in name and "1 kHz" not in name)
print(f"I2C bus with baro, mag, altimeter, power monitor: {i2c_total:.2f} %; adding the 1 kHz IMU: {i2c_total + 1000 * i2c_us(14, 400e3) / 1e4:.2f} %")
IMU 1 kHz on I2C 400 kHz 390.0 us per transaction x 1000/s = 39.00 % of the i2c bus
IMU 1 kHz on SPI 8 MHz 17.0 us per transaction x 1000/s = 1.70 % of the spi bus
barometer 210.0 us per transaction x 50/s = 1.05 % of the i2c bus
magnetometer 255.0 us per transaction x 100/s = 2.55 % of the i2c bus
laser altimeter 277.5 us per transaction x 100/s = 2.77 % of the i2c bus
power monitor 165.0 us per transaction x 20/s = 0.33 % of the i2c bus
GNSS 10 Hz, 120 B, UART 115200 10416.7 us per transaction x 10/s = 10.42 % of the uart bus
GNSS raw 5 Hz, 1600 B, UART 115200 138888.9 us per transaction x 5/s = 69.44 % of the uart bus
GNSS raw 5 Hz, 1600 B, UART 460800 34722.2 us per transaction x 5/s = 17.36 % of the uart bus
I2C bus with baro, mag, altimeter, power monitor: 6.71 %; adding the 1 kHz IMU: 45.70 %
The 1 kHz IMU on I2C uses 39% of the bus alone, and with the other sensors’ 6.71% it reaches 45.70%, almost the 50% limit, with only five sensors. On SPI at 8 MHz it uses only 1.70%, so move the IMU to SPI and keep the slower sensors on I2C. Plain GNSS messages (120 bytes at 10 Hz) use only 10.42% of a 115200 UART, but with raw data enabled (1,600 bytes at 5 Hz) it jumps to 69.44%, over the limit; raising the baud rate to 460800 leaves 17.36%. These figures are lower bounds on bus time. They exclude Linux software time and the jitter of reads through a driver, which is why the flight controller (which has an RTOS) looks after real-time buses like the IMU and sends processed results to the on-board computer over UART, as in UAT 204.
Time and data synchronisation
A geotagged image needs to know when it was taken on the same clock that records position. The flight controller and the on-board computer have separate clocks. The Linux kernel stamps image buffers with the CLOCK_MONOTONIC clock and has flags that say when the stamp was taken: when the last pixel was received (EOF, End Of Frame) or when exposure began (SOE, Start Of Exposure). For capture streams the documentation says it is the time the first data byte was captured (V4L2 Buffers). The two can differ by the exposure time plus the sensor readout time.
The offset between two clocks can be estimated with a two-way exchange. MAVLink defines the TIMESYNC message: the requester sends its time in , the responder mirrors back together with its own time in , and the requester records the time at which it receives the reply. If the outbound delay equals the return delay, the offset is . The MAVLink documentation says the sequence is repeated many times and outlying estimates filtered out, because delays in both directions change with congestion and processing time. The plain SYSTEM_TIME message is for coarse log stamping; for precise time use TIMESYNC.
Example 6 Estimate the clock offset, and its effect on image position
The UART link between the on-board computer and the flight controller has a longer outbound delay than return delay (the outbound leg queues; simulated). The clocks truly differ by 2.5 seconds and drift 20 ppm. Compare three methods: one exchange, the mean of twenty, and the mean of the four with the shortest RTT. Repeat over 500 sets so the result is not luck, then turn the time error into ground distance at 8 m/s.
import numpy as np
# estimate the clock offset between the companion computer and the flight controller with a two-way exchange (TIMESYNC style) over a link with asymmetric delay (simulated)
rng = np.random.default_rng(31)
TRUE_OFFSET, DRIFT_PPM = 2.500000, 20.0 # seconds and ppm (assumed)
def block(n=20, gap=0.5):
"""n exchanges; returns estimated offsets, true offsets and RTTs"""
t = np.arange(n) * gap
up = 0.0008 + rng.exponential(0.0012, n) # the outbound leg is slower, it queues
down = 0.0008 + rng.exponential(0.0004, n)
true = TRUE_OFFSET + DRIFT_PPM * 1e-6 * t
ts1, tc1, t_rx = t, t + up + true, t + up + down # request sent, flight controller stamps, reply received
return tc1 - (ts1 + t_rx) / 2, true, t_rx - ts1
errors = {"one exchange": [], "mean of 20": [], "shortest-RTT 4 of 20": []}
for _ in range(500):
est, true, rtt = block()
best = np.argsort(rtt)[:4]
errors["one exchange"].append(abs(est[0] - true[0]))
errors["mean of 20"].append(abs(est.mean() - true.mean()))
errors["shortest-RTT 4 of 20"].append(abs(est[best].mean() - true[best].mean()))
for name, e in errors.items():
print(f"{name:22s} mean error {np.mean(e) * 1e3:5.2f} ms, 95th percentile {np.percentile(e, 95) * 1e3:5.2f} ms")
print(f"{DRIFT_PPM:.0f} ppm drift moves the offset by {DRIFT_PPM * 1e-6 * 300 * 1e3:.1f} ms in 5 minutes, so re-estimate it regularly")
# time error turned into position error of a geotagged image (8 m/s)
v = 8.0
for label, err_ms in (("good offset estimate", 1.0), ("software stamp after a queue", 50.0), ("end-of-frame stamp instead of start-of-exposure", 10 + 20)):
print(f"{label:48s} {err_ms:5.1f} ms -> {v * err_ms / 1e3 * 100:6.1f} cm")
one exchange mean error 0.52 ms, 95th percentile 1.61 ms
mean of 20 mean error 0.40 ms, 95th percentile 0.64 ms
shortest-RTT 4 of 20 mean error 0.06 ms, 95th percentile 0.17 ms
20 ppm drift moves the offset by 6.0 ms in 5 minutes, so re-estimate it regularly
good offset estimate 1.0 ms -> 0.8 cm
software stamp after a queue 50.0 ms -> 40.0 cm
end-of-frame stamp instead of start-of-exposure 30.0 ms -> 24.0 cm
One exchange is off by 0.52 ms on average. The mean of twenty is off by 0.40 ms, not much better, because the delay is asymmetric (1.2 ms outbound against 0.4 ms return on average), which produces a constant bias of ms that averaging cannot remove. Choosing the four exchanges with the shortest RTT, which are the ones that met no queue, cuts it to 0.06 ms (p95 0.17 ms) because both legs are near their base values. A drift of 20 ppm moves the offset by 6.0 ms in 5 minutes, so it must be re-estimated periodically. In position terms, a 1 ms error at 8 m/s is 0.8 cm, below the 3 cm GSD, but a software stamp that went through a queue is off by 50 ms, or 40.0 cm, and using the EOF time instead of SOE (assume 10 ms exposure and 20 ms readout) is off by 30 ms, or 24.0 cm, eight times the GSD of 3 cm.
From detections to perception, navigation and autonomous missions
A detector returns a box in pixels, but users need metres or commands, so the latency and frame rate measured so far must be turned into task requirements. They fall into three groups with different demands.
- Perception answers where a detected object is on the ground. The pinhole camera model turns a pixel into a ray in the camera frame , where are the focal lengths in pixels and is the image centre (OpenCV). The ray is then rotated by the camera attitude and intersected with flat ground a height below. Position and attitude must be the values at the time of exposure, which is why MAVLink has a CAMERA_IMAGE_CAPTURED message that stores the position, the height above ground and the camera attitude quaternion with each image.
- Navigation uses detections to avoid or steer in real time, so latency becomes distance. The detection range must be longer than the stopping distance , where is the frame period, the processing latency and the deceleration available. PX4’s collision prevention applies the same idea: it takes OBSTACLE_DISTANCE messages from a companion computer and limits the speed so the vehicle can stop before the distance set by CP_DIST, using a delay estimate CP_DELAY. The PX4 documentation says the companion-computer setup is untested, so treat it as an illustration of the principle, not a recipe.
- Autonomous missions use detections to change the state of the mission. A typical sequence is detect, confirm, pause the mission, report, resume. PX4 pauses a mission when you switch out of Mission mode to another mode such as Hold, and switching back resumes it. If the companion computer flies the vehicle itself in offboard mode, it must keep sending setpoints at 2 Hz or faster (see “Fallbacks and safety” in module 5).
Example 7 The ground position of a waste pile, and where the error comes from
The camera looks straight down, the image is 1,920 × 1,080 pixels, the focal length is 1,000 pixels, and the drone flies at 30 m and 8 m/s, which gives the case study’s 3 cm GSD (camera values assumed). The centre of the pile’s box is at pixel (1500, 300). The detector’s p95 latency is 100 ms (R2). The municipality wants a position the officer can find within a radius of 2 m (assumed).
import math
# Camera looking straight down, image 1920 x 1080, focal length 1000 px (assumed), flying at 30 m and 8 m/s, p95 latency 100 ms (R2)
FX = FY = 1000.0
CX, CY = 960.0, 540.0
H, V, LATENCY = 30.0, 8.0, 0.100
GSD = H / FX # metres per pixel at the point below the drone
def ground_xy(u, v, pitch_deg=0.0):
"""Pixel (u, v) -> ground distance from the point below the drone (ahead, right) in metres, flat ground assumed"""
rx, ry, rz = -(v - CY) / FY, (u - CX) / FX, 1.0 # ray in the body frame: x forward, y right, z down
p = math.radians(pitch_deg)
rx, rz = rx * math.cos(p) + rz * math.sin(p), -rx * math.sin(p) + rz * math.cos(p)
t = H / rz # intersect the ground H below
return t * rx, t * ry
u, v = 1500, 300 # centre of the pile's box
x0, y0 = ground_xy(u, v)
print(f"ground point {x0:.2f} m ahead, {y0:.2f} m right of the point below the drone")
terms = {
"box centre off by 10 px": 10 * GSD,
"pitch error 1 deg": math.hypot(*(a - b for a, b in zip(ground_xy(u, v, 1.0), (x0, y0)))),
"stamp error 5 ms": V * 0.005,
}
for name, e in terms.items():
print(f"{name:26s} {e:5.2f} m")
good = math.sqrt(sum(e * e for e in terms.values()))
bad = math.sqrt(sum(e * e for e in terms.values()) + (V * LATENCY) ** 2)
print(f"total with time stamps {good:.2f} m; using the position at result time (latency {LATENCY * 1e3:.0f} ms) {bad:.2f} m")
ground point 7.20 m ahead, 16.20 m right of the point below the drone
box centre off by 10 px 0.30 m
pitch error 1 deg 0.56 m
stamp error 5 ms 0.04 m
total with time stamps 0.64 m; using the position at result time (latency 100 ms) 1.02 m
The pile is 7.20 m ahead of and 16.20 m to the right of the point below the drone. The error sources are a box centre off by 10 pixels (0.30 m), an attitude error of 1 degree (0.56 m), and a time-stamp error of 5 ms (0.04 m). Combined as the square root of the sum of squares they give 0.64 m, which passes the 2 m limit. But if the drone’s position at the time the result arrives is used instead of its position at exposure, the 100 ms latency at 8 m/s adds 0.8 m and the total becomes 1.02 m. This is the largest source, and time stamps as in Example 6 remove it. The example assumes flat ground and independent error sources; sloping ground needs a terrain model.
Example 8 The frame rate that stops in time for a pole, and confirming a pile before pausing the mission
The first half is navigation. The drone flies at 8 m/s, can brake at 3 m/s², and must stop for a pole 0.1 m wide that the detector sees once it is at least 8 pixels wide. The second half is the mission. The detector has a 2% false-detection chance per frame and a 90% chance per frame of detecting a real pile. At 1 fps there are 1,250 frames per sortie, and the footprint along track is 32.4 m from Example 1 of module 1 (all values assumed).
import math
# Navigation: the highest speed at which the drone can still stop for a thin pole (all values assumed)
V, A, L = 8.0, 3.0, 0.100 # speed m/s, usable braking m/s2, p95 processing latency s
FPX, POLE_M, MIN_PX = 1000.0, 0.10, 8 # focal length px, pole 0.1 m wide, must be 8 px or wider to be detected
r_det = FPX * POLE_M / MIN_PX
print(f"detection range {r_det:.1f} m")
for fps in (1, 10):
t_react = 1 / fps + L # worst case: the obstacle appears just after a frame, so wait one frame period and then process
stop = V * t_react + V * V / (2 * A)
vmax = -A * t_react + math.sqrt((A * t_react) ** 2 + 2 * A * r_det)
print(f"{fps:2d} fps: reaction {t_react:.2f} s, stopping {stop:5.1f} m, margin {r_det - stop:+5.1f} m, max speed {vmax:.1f} m/s")
# Mission: confirm a waste pile over several frames before pausing the mission (assumed values)
FOOTPRINT, FRAMES = 32.4, 1250 # footprint along track in m (Example 1) and frames per sortie at 1 fps
P_FP, P_TP = 0.02, 0.90 # chance of a false detection per frame, and of detecting a real pile per frame
view_s = FOOTPRINT / V
print(f"a pile stays in view {view_s:.2f} s: {int(view_s)} frames at 1 fps, {int(view_s * 10)} frames at 10 fps")
def at_least(k, n, p):
"""Chance that an event happens at least k times in n frames when the frames are independent"""
return sum(math.comb(n, i) * p ** i * (1 - p) ** (n - i) for i in range(k, n + 1))
K, N = 3, 5 # confirm when at least 3 of 5 frames at 10 fps (evidence mode) detect it
candidates = FRAMES * P_FP # false candidates at 1 fps per sortie, each one opens evidence mode for N/10 s
print(f"{K} of {N} at 10 fps: decision in {N / 10:.1f} s after {V * N / 10:.1f} m of flight")
print(f"false candidates {candidates:.0f} per sortie cost {candidates * N / 10:.1f} s of evidence mode")
print(f"false alarms {candidates * at_least(K, N, P_FP):.4f} per sortie, true pile confirmed {at_least(K, N, P_TP):.3f}")
detection range 12.5 m
1 fps: reaction 1.10 s, stopping 19.5 m, margin -7.0 m, max speed 6.0 m/s
10 fps: reaction 0.20 s, stopping 12.3 m, margin +0.2 m, max speed 8.1 m/s
a pile stays in view 4.05 s: 4 frames at 1 fps, 40 frames at 10 fps
3 of 5 at 10 fps: decision in 0.5 s after 4.0 m of flight
false candidates 25 per sortie cost 12.5 s of evidence mode
false alarms 0.0019 per sortie, true pile confirmed 0.991
The pole is seen at m. At 1 fps the wait is a full frame period, so the stopping distance is 19.5 m, 7.0 m beyond the detection range, and the safe speed falls to 6.0 m/s. At 10 fps it just works, with only 0.2 m to spare. The conclusion matches Example 1 of module 1: the frame rate comes from the task. 1 fps is enough to search for waste piles but not to dodge a pole at 8 m/s, so either slow down or raise the frame rate (which costs energy, see module 5).
For the mission, a pile stays in view for 4.05 s, which is 4 frames at 1 fps. Confirming over several frames at 1 fps would mean flying almost past the pile before deciding. The team uses two stages: a single detection at 1 fps makes a suspect, which opens evidence mode at 10 fps and confirms when at least 3 of 5 frames detect it. The decision takes 0.5 s, during which the drone flies 4.0 m. There are 25 false suspects per sortie at 1 fps, costing 12.5 s of evidence mode in total, well under the 3-minute ceiling (R2). That leaves 0.0019 false alarms per sortie, while a real pile is confirmed 99.1% of the time. These numbers treat the frames as independent, which is optimistic because a shadow or a look-alike object can repeat its error in every frame, so the false alarm rate must be measured on real test images (see “System testing” in module 5).
Visual odometry and SLAM on the edge
Example 8 assumed the drone knows where it is. Under a bridge, beside a tall building or indoors, GNSS can be weak or missing, and the drone then has to work out its own motion from its camera. Two families of methods do this.
- Visual odometry (VO) estimates how the camera moved between frames, much like counting your steps with your eyes open: it picks distinctive points (features) in one frame, finds them again in the next and solves for the rotation and translation that explain the shift. Adding the IMU gives visual-inertial odometry (VIO), which recovers the true scale in metres and copes with fast turns. VINS-Mono, for example, fuses pre-integrated IMU measurements with feature observations to estimate the full six degrees of freedom.
- SLAM (simultaneous localisation and mapping) also keeps a map of the features it has seen. When the drone returns to a place it knows (loop closure), the error that has built up is corrected. ORB-SLAM3 goes further: when tracking is lost it starts a new map and merges it with the old one when it revisits a mapped area.
A VIO pipeline has three parts with very different loads. The front-end detects and tracks features in every frame, so it must finish within one frame period. The back-end optimises a sliding window of recent keyframes (selected frames kept for optimisation) or runs a Kalman filter, which is heavier but runs only once per keyframe. Loop closure searches the map for a familiar place and is the heaviest part, but it is needed only now and then.
Why does this run on the onboard computer rather than on the ground? The pose feeds the flight controller’s estimator many times per second. PX4, for instance, takes the pose from a companion computer as MAVLink ODOMETRY messages and fuses it with the IMU in EKF2, and the parameter EKF2_EV_DELAY tells the estimator how old each pose is relative to the IMU. Sending video to the ground and the pose back would add the radio’s latency and losses to this loop, so a short dropout would become a position jump. Time stamps as in Example 6 matter here too: PX4 notes the delay could in principle be 0 with correct time stamps and time sync, and otherwise it is tuned from the logs.
Embedded boards are tight for this work. Delmerico and Scaramuzza ran six open-source VIO pipelines on the EuRoC drone datasets on a laptop and on two small boards. On the boards VINS-Mono had to track fewer features (100 instead of 150) to keep up in real time, and loop closure could not run at all on the ODROID. Their conclusion was that there is no free lunch: more accuracy costs more computation, which on a drone competes with the detector for the same CPU, memory and power. So, just like the detector, a VIO pipeline needs a compute budget and a latency budget, and its drift (the error that grows with the distance flown, often quoted as a percentage of distance, so with a drift rate the error after a distance is roughly ) sets how far the drone may fly before it needs a correction.
Example 9 The compute and latency budget of a VIO pipeline, and the drift under a bridge
A team inspects a bridge with no GNSS beneath it. The VIO runs on two CPU cores of the board, one for the front-end and one for the back-end, while the detector uses the accelerator. The measured times are 14 ms per frame for the front-end and 120 ms per keyframe for the back-end, with a keyframe every 5 frames. From mid-exposure to the frame in memory takes 8 ms, and packing and sending ODOMETRY takes 2 ms. The drift is 1% of distance, the drone flies at 3 m/s, and of its 2 m clearance from the piers the team allows 1 m for position error (all values assumed).
# VIO budget on an embedded board: two threads on two CPU cores (all values assumed)
FRONT_MS = 14.0 # front-end: track features in one frame
BACK_MS = 120.0 # back-end: optimise the sliding window once per keyframe
KF_EVERY = 5 # one keyframe every 5 frames
CAPTURE_MS, SEND_MS = 8.0, 2.0 # mid-exposure to frame in memory; pack and send ODOMETRY
for fps in (30, 60):
t_frame = 1000 / fps
front = FRONT_MS / t_frame # share of one core, must stay below 1
back = BACK_MS / (KF_EVERY * t_frame) # share of a second core, must stay below 1
ok = "fits" if max(front, back) < 1 else "overloaded"
print(f"{fps} fps: frame {t_frame:.1f} ms, front-end {front:.0%}, back-end {back:.0%} -> {ok}")
kf_min = BACK_MS / t_frame
print(f" at least {kf_min:.1f} frames between keyframes for the back-end")
latency = CAPTURE_MS + FRONT_MS + SEND_MS
print(f"exposure to ODOMETRY {latency:.0f} ms (starting value for EKF2_EV_DELAY)")
# Drift under a bridge with no GNSS
DRIFT, V, ALLOWED = 0.01, 3.0, 1.0 # 1% of distance (assumed), 3 m/s, 1 m of the 2 m clearance
for d in (30, 100, 300):
print(f"{d:3d} m without correction: error about {DRIFT * d:.1f} m")
d_max = ALLOWED / DRIFT
print(f"limit {d_max:.0f} m or {d_max / V:.0f} s at {V:.0f} m/s before a correction is needed")
print(f"without a time stamp, {latency:.0f} ms at {V:.0f} m/s adds {V * latency / 1000:.2f} m")
30 fps: frame 33.3 ms, front-end 42%, back-end 72% -> fits
at least 3.6 frames between keyframes for the back-end
60 fps: frame 16.7 ms, front-end 84%, back-end 144% -> overloaded
at least 7.2 frames between keyframes for the back-end
exposure to ODOMETRY 24 ms (starting value for EKF2_EV_DELAY)
30 m without correction: error about 0.3 m
100 m without correction: error about 1.0 m
300 m without correction: error about 3.0 m
limit 100 m or 33 s at 3 m/s before a correction is needed
without a time stamp, 24 ms at 3 m/s adds 0.07 m
At 30 fps the front-end uses 42% of its core and the back-end 72% of the other, so both fit with some headroom. Raising the camera to 60 fps “for smoother tracking” halves the frame period: the front-end still fits at 84%, but the back-end now receives a keyframe every 83 ms and needs 120 ms, which is 144% of a core, so its queue grows without limit (as in Example 3). The fix is to space keyframes at least 8 frames apart (above the 7.2 computed), track fewer features, or stay at 30 fps. The pose leaves the board 24 ms after exposure, which is the starting value for EKF2_EV_DELAY, to be refined from the logs as PX4 recommends.
For the drift, 1% means 1 m of error after 100 m, which is about 33 s of flight at 3 m/s. The plan must therefore give the drone a correction at least that often, for example by flying back over the start point so that loop closure can act, or by leaving the bridge to regain GNSS. A missing time stamp would add only 0.07 m at this low speed, much less than the drift, but it grows with speed in the same way as in Example 7. The 1% figure is an assumption, so the team must measure the drift of its own pipeline on its own board.
Module lab
Lab: a real-time pipeline and the sensors
- Camera bandwidth: fix the group’s camera mode, compute the bandwidth with , then capture continuously for 5 minutes and count dropped frames.
- Build a pipeline: capture, pre-process, inference, post-process, with a time stamp at every stage. Record p50, p95 and p99 of the latency from capture to result, and the number of dropped frames, comparing an unbounded FIFO with a one-slot queue that drops the older frame. Start measuring after warm-up.
- Out-of-class extension (in Worksheet 4, if the tools support it): use V4L2 DMABUF or GStreamer to compare copying with zero-copy at the camera’s highest resolution, measuring CPU time and DRAM traffic.
- Compute the bus time budget of the group’s sensors as in Example 5, then measure the real read time (with a logic analyser or time stamps) and compare it with the calculation.
- Estimate the clock offset between the board and the flight controller with TIMESYNC messages as in Example 6, compare one exchange with choosing the short-RTT exchanges, and compute the position error at the group’s real flight speed.
- Out-of-class extension: pick one detection box from recorded video, find its ground position with the code of Example 7 using the group’s real camera values and height, then find the lowest frame rate that stops in time for a given obstacle with the code of Example 8.
- Report a table: latency p50, p95, p99, throughput, dropped frames, bus share used, and time error.
Test on the bench only. If connected to a drone, remove the propellers and make connections with no battery power. Take anti-static precautions when handling boards and camera cables. Never plug or unplug a CSI camera cable while the board is powered.
Common mistakes
Watch out
- Tuning zero-copy before measuring, when at the job’s resolution and frame rate copying is a small part
- Using an unbounded queue in real-time work, so latency grows without limit when the model is slower than the camera
- Reporting only the mean latency, without p95, p99 and the number of dropped frames
- Setting a large batch for a live camera, when the first frame of a batch must wait
- Putting a high-rate sensor on I2C until the bus is full, instead of moving it to SPI
- Forgetting that a UART moves only baud/10 bytes per second when GNSS raw data is switched on
- Stamping an image after a software queue, or using the EOF time instead of SOE without compensation
- Using position data with images without estimating the clock offset and drift
Summary
- The real requirement on time is a predictable deadline, not the mean speed; report p50, p95 and p99 with the measurement conditions
- Camera bandwidth is , and copying at every stage doubles the memory traffic; zero-copy with DMABUF solves it, but measure first to see whether it is the bottleneck
- Latency is the sum of all stages, the throughput of a pipeline is set by its slowest stage, and
- When load exceeds 1, bound the queue and drop old frames; big batches raise throughput but also latency, so they suit images that are ready together and not a live camera
- Compute the bus time budget from each bus’s formulas, move high-rate sensors to SPI, and allow for the UART’s baud rate
- Estimate the clock offset with a two-way exchange and pick the short-RTT exchanges, because a time error at speed is a position error
- A detection in pixels must be turned into a ground position with the pinhole model, the attitude and the time at exposure; navigation needs a detection range beyond the stopping distance , and an autonomous mission should confirm over several frames in evidence mode before pausing
Check your understanding
- What is the raw bandwidth of a 2,560 × 1,440 NV12 camera at 30 fps, in MB/s and in Gbit/s?
- A system passes 25 frames per second on average and each frame spends 80 ms in the system on average. How many frames are in the system on average?
- Reading 6 register bytes over I2C (use ) takes how long at 400 kHz and at 100 kHz? At 50 Hz, what share of the bus is used?
- A GNSS receiver sends 120 bytes 10 times per second over an 8N1 UART. What share is used at 115200 baud, and what is the lowest standard baud rate that keeps it at 25% or less?
- An image time stamp is off by 40 ms while flying at 12 m/s. How far off is the image position?
Answers
- Per frame bytes; at 30 fps that is 165.9 MB/s, or Gbit/s
- frames
- clock periods; 210 µs at 400 kHz and 840 µs at 100 kHz. At 50 Hz the bus is used at 400 kHz and at 100 kHz
- bytes/s = 12,000 bit/s, which is . At most 25% needs baud or more; the next standard rate is 57,600
- m
Key formulas
| Camera bandwidth | |
| Little law | |
| Clock offset from a two-way exchange | |
| Position error from time error | |
| Stopping distance for navigation | |
| Pixel ray in the camera frame | |
| Position drift over distance |
Key references
- Linux kernel developers. Streaming I/O (DMA buffer importing). In The Linux kernel user-space API guide, Video for Linux. link
- Linux kernel developers. Buffers (timestamp and timestamp source flags). In The Linux kernel user-space API guide, Video for Linux. link
- USB Implementers Forum. SuperSpeed USB. USB-IF. link
- MIPI Alliance. MIPI Camera Serial Interface 2 (MIPI CSI-2). Specification overview. link
- Little, J. D. C. (1961). A proof for the queuing formula: L = λW. Operations Research, 9(3), 383–387. link
- MLCommons. MLPerf inference rules. link
- NXP Semiconductors. (2021). I2C-bus specification and user manual (UM10204, Rev. 7.0). link
- Microchip Technology. (2018). Getting started with USART (TB3216). link
- MAVLink Development Team. Time synchronization protocol v2. MAVLink developer guide. link
- MAVLink Development Team. MAVLink common message set (common.xml). link
- Raspberry Pi Ltd. AI HATs (AI HAT+ and AI HAT+ 2). Raspberry Pi documentation. link
- OpenCV. Camera calibration and 3D reconstruction (calib3d module): solvePnP, triangulatePoints. OpenCV 4.x documentation. link
- PX4 Autopilot. Collision prevention. PX4 user guide (main). link
- PX4 Autopilot. Offboard mode (multicopter). PX4 user guide (main). link
- PX4 Autopilot. Mission mode (multicopter). PX4 user guide (main). link
- PX4 Autopilot. Visual inertial odometry (VIO). PX4 guide (main). link
- Qin, T., Li, P., & Shen, S. (2018). VINS-Mono: A robust and versatile monocular visual-inertial state estimator. IEEE Transactions on Robotics, 34(4), 1004–1020. link
- Campos, C., Elvira, R., Gómez Rodríguez, J. J., Montiel, J. M. M., & Tardós, J. D. (2021). ORB-SLAM3: An accurate open-source library for visual, visual–inertial, and multimap SLAM. IEEE Transactions on Robotics, 37(6), 1874–1890. link
- Delmerico, J., & Scaramuzza, D. (2018). A benchmark comparison of monocular visual-inertial odometry algorithms for flying robots. In 2018 IEEE International Conference on Robotics and Automation (ICRA) (pp. 2502-2509). IEEE. https://doi.org/10.1109/ICRA.2018.8460664 link
Further reading
Study the assigned knowledge units in advance, review media and take the module quiz
Picamera2
อินเทอร์เฟซอนุกรม UART I2C SPI CAN และ DroneCAN
การวิเคราะห์วิดีโออัจฉริยะ
In class / field
Lab or field practice from worksheets with a safety checklist
Learning evidence: Checked worksheets and quiz results