Module 11/15 · Weeks 11 · 9 h

Image and video pipelines with OpenCV

UAT 456 Artificial Intelligence, Machine Learning and Computer Vision for UAS

About 95 minDraft, awaiting reviewLast updated 24 October 2026

Lesson

By the end of this module you will be able to

  1. Read images and video with OpenCV and use frame time instead of frame count when frames go missing
  2. Choose a queue size and a drop policy that keep the latency of a time-critical pipeline under control
  3. Check frame quality with relative sharpness and the fraction of clipped pixels before a frame reaches analysis
  4. Choose an image filter for the type of noise, and separate vegetation with HSV colour and morphology

Prerequisites: UAT 104 Computer programming · UAT 307 Computer vision and perception technology (recommended)

Why this matters

UAT 307 taught the basics of perception: edges with Sobel, thresholds with Otsu, and homography. This course takes the next step, building applications that use those techniques on real drone images and video and that can be shown to meet an acceptance criterion. Applications rarely fail because a formula is wrong. They fail because of what surrounds the formula: frames that go missing on the way, a queue that grows until the image being processed is several seconds old, or a blurred frame that slips into the measurement step. This module therefore starts with the image and video pipeline, before any single technique.

Modules 11 to 15 of the course use one fictional case through all of them: an irrigation office asks a drone team to inspect a 12 km concrete-lined supply canal before and after the flood season. Four kinds of work use images: (1) inspecting the concrete lining panels, finding cracks, measuring their width and comparing changes between two flights; (2) navigation, following the canal and landing on a pad at the pumping station; (3) surveying, measuring the canal bottom width, the surface speed of the water and the area of vegetation in the joints; (4) an intelligent system that raises an alert when floating debris appears. The lining panels are 5.0 m long along the canal and 3.0 m wide down the slope. Two cameras are used: one for crack inspection close to the surface (a 1-inch sensor of 5,472 × 3,648 pixels, a 50 mm lens, 6.0 m from the panel, giving a GSD of 0.289 mm) and a 1080p 30 fps video camera at 30 m height for navigation and surveying (GSD 20 mm). All figures are fictional. The Python code can be downloaded from /downloads/uat-456/.

The course runs alongside modules 1–5 of this course Intelligent image-analysis systems (deep models, tracking by detection), UAT 455 Sensor technology and surveillance camera systems, UAT 451 Aerial photography and photogrammetry, and UAT 453 UAS for building and infrastructure inspection. It does not repeat what those courses teach; it concentrates on how techniques are assembled into an application that can be accepted. All examples were tested with OpenCV 5.0.0 (the opencv-python-headless package), released in July 2026 (4.14 followed later in the same month) according to the PyPI release history checked on 2 October 2026. Only 5.0.0 was tested. The functions used are mostly standard ones that exist in 4.x as well, but they were not tested there, and the output shape of some functions differs between versions, which is noted where it matters. The ArUco example needs OpenCV 4.7 or later.

Images and video in OpenCV

An image in OpenCV is a NumPy array of shape (rows, columns, 3) and type uint8, with colours ordered BGR (blue, green, red), not RGB. One 1080p frame is 1,920 × 1,080 × 3 = 6.2 MB, which is 187 MB/s at 30 fps. A 4K frame is 24.9 MB, or 746 MB/s. Data of this size does not travel as raw images but as a compressed stream (for example H.264) that must be decoded first, so decoding and processing take real time and belong in the application’s time budget (Szeliski, 2022).

The cv2.VideoCapture class opens a file, a camera by index, or a stream from another backend such as GStreamer. The read() method does two things in sequence: grab() takes the next frame from the device, and retrieve() decodes it into an array. The OpenCV documentation explains that grab() is meant for the case where frames from several cameras must be as close in time as possible, because the slower part, retrieve(), can be done afterwards. The get() method returns properties such as CAP_PROP_POS_MSEC, but it returns 0 when the backend does not support the property, and the value passes through several layers (backend, operating system, driver, hardware), so it may differ from what the device really does. In practice, do not trust the fps or the time that get() reports without checking. Record your own time when a frame arrives, using a clock that never goes backwards (time.monotonic()), or use the device timestamp if there is one.

import time
import cv2

cap = cv2.VideoCapture("canal_pass1.mp4")      # a file, a camera index, or a GStreamer stream
stamps = []
while True:
    ok = cap.grab()                            # take the next frame, fast
    if not ok:
        break
    t = time.monotonic()                       # stamp the time as soon as the frame arrives
    ok, frame = cap.retrieve()                 # decode into an array, slower
    stamps.append(t)
    # ... send (t, frame) to the queue of the next stage ...
cap.release()

This block is not run in the lesson because it needs a video file or a camera. The next example therefore uses simulated frame arrival times.

Example 1 Missing frames and choosing key frames by time

A 10 s, 30 fps video from the navigation camera, flown at 4.0 m/s with a GSD of 20 mm and 1,080 image rows. 18 frames go missing on the way, 15 of them in one run (assumed). The team wants key frames for stitching with 80% overlap along the flight line. The overlap between two frames is , where is the number of rows.

import numpy as np

FPS, V, GSD, ROWS = 30, 4.0, 0.020, 1080     # fps, flight speed m/s, GSD m/px, image rows (assumed)
rng = np.random.RandomState(3)
sent = np.arange(300)                         # 10 s of video
dropped = set([41, 42] + list(range(120, 135)) + [250])   # frames lost on the way (assumed)
got = np.array([i for i in sent if i not in dropped])
t = got / FPS + rng.normal(0, 0.0015, got.size)           # arrival times with 1.5 ms jitter

dt = np.diff(t)
periods = np.round(dt * FPS).astype(int)      # spacing of received frames in frame periods
print(f"received {got.size} of {sent.size}, missing {int((periods - 1).sum())}, effective rate {got.size / (t[-1] - t[0]):.1f} fps")
print(f"normal step {V / FPS / GSD:.1f} px per frame")
print(f"longest gap {dt.max() * 1000:.0f} ms = {periods.max()} periods, the drone moved {V * dt.max():.2f} m = {V * dt.max() / GSD:.0f} px")

foot = ROWS * GSD                             # along-track footprint (m)
want = 0.80                                   # required overlap
step_t = (1 - want) * foot / V                # time between key frames (s)

def overlap(ta, tb):
    return 1 - V * (tb - ta) / foot

by_time, last = [0], t[0]                     # choose by timestamp
for k in range(1, t.size):
    if t[k] - last >= step_t - 0.5 / FPS:
        by_time.append(k); last = t[k]
by_index = list(range(0, t.size, round(step_t * FPS)))   # choose every Nth received frame
for name, ks in (("by timestamp", by_time), ("by index", by_index)):
    ov = [overlap(t[a], t[b]) for a, b in zip(ks[:-1], ks[1:])]
    print(f"{name}: {len(ks)} key frames, overlap {min(ov):.2f} to {max(ov):.2f}")
received 282 of 300, missing 18, effective rate 28.3 fps
normal step 6.7 px per frame
longest gap 531 ms = 16 periods, the drone moved 2.13 m = 106 px
by timestamp: 10 key frames, overlap 0.77 to 0.80
by index: 9 key frames, overlap 0.71 to 0.80

The rate actually achieved is 28.3 fps, not 30, and the longest run of missing frames lasts 531 ms, during which the drone flew 2.13 m or 106 pixels, against a normal step of only 6.7 pixels per frame. This matters for module 14, because a tracker that expects small image motion will get lost across this gap. For key frames, choosing by timestamp gives an overlap of 0.77 to 0.80, while choosing every 32nd frame in order gives 0.71 to 0.80, because the missing frames make the real spacing longer than assumed. The lesson is to always use frame time, never the frame count, and to set a minimum (for example 0.75) instead of expecting to hit the target exactly.

Queues, latency and the frames you must drop

If the processing stage is slower than the camera, frames pile up. A 30 fps camera has a period of 33.3 ms. If processing takes 36.4 ms on average, the load is , more than 1, so the stage can never keep up. There are four options: make the stage faster, reduce the resolution or process only the region of interest, process only some of the frames, or drop frames by policy. The point to understand is that a queue between stages absorbs variation in processing time but does not help when the load exceeds 1. The GStreamer documentation explains that its queue element blocks by default when it is full, and that the leaky property makes it drop new or old buffers instead. The default limits are 200 buffers, 10 MB or one second of data, whichever is reached first.

The latency of a frame is the time from its arrival to the end of its processing. It is tied to the number of frames in the system by Little’s law, , where is the average number of frames in the system, is the rate at which frames pass through, and is the average time a frame spends in the system (Little, 1961; Little, 2011). A long queue means high latency; you cannot have one without the other.

Example 2 Queue size and drop policy

A 30 fps camera. The processing stage takes 25 ms for 70% of frames and 62 ms for the other 30% (assumed). Simulate 60 s. Try queues of 1 and 4 frames, with the policy of dropping the new frame that arrives (drop-new) and of dropping the oldest frame in the queue (drop-old), against an unbounded queue.

import numpy as np

FPS, T_END = 30, 60.0
rng = np.random.RandomState(5)
arr = np.arange(0, T_END, 1 / FPS)            # frame arrival times
svc = np.where(rng.rand(arr.size) < 0.7, 0.025, 0.062)   # processing time: 70% take 25 ms, 30% take 62 ms (assumed)
print(f"mean processing {svc.mean() * 1000:.1f} ms vs frame period {1000 / FPS:.1f} ms, load {svc.mean() * FPS:.2f}")

def simulate(cap, policy):
    # cap = frames allowed to wait (not counting the one in service)
    queue, done, busy_until, lat, used = [], 0, 0.0, [], 0
    def start(now):
        nonlocal busy_until
        while queue and busy_until <= now:
            a, s = queue.pop(0)
            busy_until = max(busy_until, a) + s
            lat.append(busy_until - a)
    for a, s in zip(arr, svc):
        start(a)
        if len(queue) >= cap:
            if policy == "drop-new":
                continue
            queue.pop(0)                      # discard the oldest frame
        queue.append((a, s))
    start(1e9)
    return np.array(lat)

for cap, policy in ((1, "drop-new"), (1, "drop-old"), (4, "drop-new"), (4, "drop-old"), (10 ** 6, "unbounded")):
    lat = simulate(cap, policy)
    name = f"cap {cap}" if cap < 10 ** 6 else "no limit"
    print(f"{name:9s} {policy:9s}: processed {100 * lat.size / arr.size:5.1f}%, latency mean {lat.mean() * 1000:6.0f} ms, p95 {np.percentile(lat, 95) * 1000:6.0f} ms")
    if (cap, policy) == (4, "drop-old"):
        rate = lat.size / T_END               # processed frames per second
        print(f"          Little's law L = rate x latency = {rate:.1f} x {lat.mean():.3f} = {rate * lat.mean():.1f} frames in the system")
mean processing 36.4 ms vs frame period 33.3 ms, load 1.09
cap 1     drop-new : processed  85.5%, latency mean     53 ms, p95     98 ms
cap 1     drop-old : processed  86.0%, latency mean     47 ms, p95     85 ms
cap 4     drop-new : processed  91.2%, latency mean    133 ms, p95    215 ms
cap 4     drop-old : processed  91.0%, latency mean    121 ms, p95    178 ms
          Little's law L = rate x latency = 27.3 x 0.121 = 3.3 frames in the system
no limit  unbounded: processed 100.0%, latency mean   2609 ms, p95   5097 ms

A load of 1.09 lets the unbounded queue process 100% of the frames, but the mean latency climbs to 2,609 ms and the p95 to 5,097 ms, which means the application is looking at images from several seconds ago. The bounded queues drop 14% (1-frame queue) and 9% (4-frame queue) of the frames, and keep latency under 250 ms in both cases. The 4-frame drop-old queue has a mean latency of 121 ms, which agrees with Little’s law: 27.3 × 0.121 = 3.3 frames in the system, within the maximum of 5 (4 waiting plus 1 being processed). The two policies differ in which frames survive. Drop-old keeps the fresh frame, which suits navigation that needs the latest data. For inspection, where every frame has value, do not drop: record every frame to disk and process after the flight.

Five boxes from left to right joined by arrows: camera 30 fps, queue 4 frames, quality gate, processing 36 ms per frame, result save or alert. A measuring bar under all the boxes reads mean latency 121 ms, p95 178 ms.
Figure 1 A video pipeline from camera to result. The latency comes from the 4-frame drop-old queue of Example 2.
Horizontal bar chart with five groups, each with a mean latency bar and a p95 bar. Queue 1 drop new 53 and 98 ms, queue 1 drop old 47 and 85, queue 4 drop new 133 and 215, queue 4 drop old 121 and 178, unbounded queue 2,609 and 5,097, drawn with bars cut by a break mark.
Figure 2 Frame latency by queue size and drop policy. The bars of the unbounded queue are cut short.

Checking frame quality before use

A blurred or too dark frame should not enter the measurement or detection stage, because it produces wrong results that look real. A fast and sound check uses three values. The first is sharpness, measured by the variance of the Laplacian, . A sharp frame has many edges, so the variance is high; the measure is widely used for autofocus (Pech-Pacheco et al., 2000). The second is the fraction of pixels that are very dark (≤ 5) or very bright (≥ 250), where information is already lost. The third is the mean brightness. The causes of each kind of bad frame are covered in the knowledge unit on image quality, for example motion blur and the choice of shutter speed in UAT 455.

Example 3 A frame-quality gate

Five synthetic concrete images: a good frame, a defocused one, one with 9 pixels of motion blur, a dark one (brightness × 0.35) and an over-exposed one (× 1.9). The gate rule is: sharpness at least 0.5 times that of the reference frame, no more than 2% clipped pixels, and a mean brightness between 60 and 200. The last lines compare a smooth surface in focus with a rough surface that is blurred.

import cv2
import numpy as np

def concrete(h, w, seed, contrast=1.0):       # synthetic concrete texture
    r = np.random.RandomState(seed)
    fine = cv2.GaussianBlur(r.normal(0, 1, (h, w)).astype(np.float32), (0, 0), 0.8)
    mid = cv2.GaussianBlur(r.normal(0, 1, (h, w)).astype(np.float32), (0, 0), 3.0)
    img = 150 + contrast * (25 * fine / fine.std() + 18 * mid / mid.std())
    return np.clip(img, 0, 255).astype(np.uint8)

def sharpness(g):                             # variance of the Laplacian
    return cv2.Laplacian(g, cv2.CV_64F).var()

def clipped(g):                               # fraction of very dark or very bright pixels
    return float(((g <= 5) | (g >= 250)).mean())

base = concrete(240, 320, 1)
motion_kernel = np.zeros((9, 9), np.float32)
motion_kernel[4, :] = 1 / 9                   # 9 px motion blur
frames = [("sharp", base),
          ("defocus", cv2.GaussianBlur(base, (0, 0), 2.0)),
          ("motion", cv2.filter2D(base, -1, motion_kernel)),
          ("dark", (base * 0.35).astype(np.uint8)),
          ("bright", np.clip(base.astype(np.float32) * 1.9, 0, 255).astype(np.uint8))]
ref = sharpness(base)                         # reference from the last good frame
for name, g in frames:
    s, c = sharpness(g), clipped(g)
    ok = s >= 0.5 * ref and c <= 0.02 and 60 <= g.mean() <= 200
    print(f"{name:8s} sharpness {s:7.1f} ({s / ref:4.2f} of ref), clipped {100 * c:4.1f}%, mean {g.mean():5.1f} -> {'accept' if ok else 'reject'}")

smooth_sharp = concrete(240, 320, 2, contrast=0.12)     # smooth plaster, in focus
rough_blur = cv2.GaussianBlur(concrete(240, 320, 3, contrast=2.0), (0, 0), 1.2)   # rough surface, blurred
print(f"smooth but sharp {sharpness(smooth_sharp):6.1f}  rough but blurred {sharpness(rough_blur):6.1f}  fixed threshold 100")
sharp    sharpness  1845.1 (1.00 of ref), clipped  0.1%, mean 150.5 -> accept
defocus  sharpness    11.9 (0.01 of ref), clipped  0.0%, mean 150.5 -> reject
motion   sharpness   218.9 (0.12 of ref), clipped  0.0%, mean 150.5 -> reject
dark     sharpness   227.5 (0.12 of ref), clipped  0.0%, mean  52.2 -> reject
bright   sharpness  2024.5 (1.10 of ref), clipped 73.3%, mean 243.9 -> reject
smooth but sharp   28.2  rough but blurred  291.2  fixed threshold 100

The good frame passes and the other four are rejected for different reasons. The defocused frame keeps 0.01 of the reference sharpness and the motion-blurred one 0.12. The dark frame has a sharpness of 0.12 and a mean brightness of only 52.2. The over-exposed frame has a sharpness of 1.10, higher than the reference, because multiplying the brightness by 1.9 also magnifies the differences between pixels, but 73.3% of its pixels are clipped at 255, so it must be rejected. A single sharpness value is not enough. The last line shows why sharpness must be relative: smooth plaster that is in focus has a variance of only 28.2, while a rough blurred surface still has 291.2. A fixed threshold of 100 would reject the good image and accept the blurred one. The remedy is to compare with the median of the most recent accepted frames of the same scene, and to choose the thresholds from the real frames of the job, not from the numbers in the lesson.

Horizontal bar chart of five bars, sharpness against the reference frame. Sharp 1.00 in green, defocused 0.01, motion blur 0.12, too dark 0.12, over-exposed 1.10 but 73% clipped, all pink except the first. A dashed pink line at 0.5.
Figure 3 Sharpness of each frame against the reference frame. The over-exposed frame is sharp but is rejected because its pixels are clipped.

Image filters, colour and regions of interest

Each filter suits a different kind of noise. According to the OpenCV smoothing tutorial, the median filter replaces the centre value with the median of the pixels under the kernel and is highly effective against salt-and-pepper noise, while the bilateral filter weights pixels by both distance and brightness difference, so it removes texture but keeps edges. A Gaussian blurs everything equally, edges included. In practice you should not look only at the RMSE against a clean image; measure whether what the application needs survives, which here is thin cracks and joint edges.

Example 4 Choosing a filter for the type of noise

A synthetic 160 × 120 pixel image has a joint edge (brightness 80 to 180) and a crack 2 pixels wide that is 50 units darker than the background. Two kinds of noise are added, 5% salt and pepper, and Gaussian noise with a standard deviation of 15, and five filters are applied. The table reports the RMSE, the edge width (the number of pixels between 20% and 80% of the step) and the crack contrast left (true value 50).

import cv2
import numpy as np

clean = np.full((120, 160), 80, np.uint8)
clean[:, 80:] = 180                           # a panel joint edge (brightness step)
clean[:, 40:42] = 30                          # a thin crack 2 px wide

rng = np.random.RandomState(7)
sp = clean.copy()
r = rng.rand(*clean.shape)
sp[r < 0.025] = 0
sp[r > 0.975] = 255                           # salt and pepper, 5%
gn = np.clip(clean + rng.normal(0, 15, clean.shape), 0, 255).astype(np.uint8)   # Gaussian noise

filters = {"none": lambda g: g,
           "gauss 5x5": lambda g: cv2.GaussianBlur(g, (5, 5), 0),
           "median 3x3": lambda g: cv2.medianBlur(g, 3),
           "median 5x5": lambda g: cv2.medianBlur(g, 5),
           "bilateral": lambda g: cv2.bilateralFilter(g, 7, 40, 5)}

def rmse(a):
    return float(np.sqrt(np.mean((a.astype(float) - clean) ** 2)))

def edge_width(a):                            # edge width: pixels between 20% and 80% of the step
    row = a[10:110, 60:100].astype(float).mean(axis=0)
    return int(((row > 80 + 0.2 * 100) & (row < 80 + 0.8 * 100)).sum())

def crack_depth(a):                           # darkness left in the crack (80 is background, 30 the true crack)
    return float(80 - a[10:110, 40:42].mean())

print("noise      filter        RMSE  edge width  crack contrast left (true 50)")
for nname, noisy in (("salt-pepper", sp), ("gaussian", gn)):
    for fname, f in filters.items():
        o = f(noisy)
        print(f"{nname:11s} {fname:11s} {rmse(o):6.1f} {edge_width(o):6d} {crack_depth(o):9.1f}")
noise      filter        RMSE  edge width  crack contrast left (true 50)
salt-pepper none          30.5      0      48.8
salt-pepper gauss 5x5      9.8      2      29.2
salt-pepper median 3x3     0.8      0      50.0
salt-pepper median 5x5     5.6      0       0.0
salt-pepper bilateral     28.5      0      30.1
gaussian    none          14.9      0      49.3
gaussian    gauss 5x5      6.1      2      30.3
gaussian    median 3x3     6.5      0      39.6
gaussian    median 5x5     6.1      0      12.3
gaussian    bilateral      4.4      0      31.4

For salt and pepper, the 3 × 3 median is best: the RMSE drops to 0.8, the edge stays sharp (width 0) and the crack keeps its full 50.0. The Gaussian gives an RMSE of 9.8 and blurs the edge to 2 pixels, and the bilateral filter does not help (RMSE 28.5) because the salt-and-pepper spikes differ so much from their neighbours that they are treated as edges. The 5 × 5 median has an RMSE of 5.6, which looks good, but it erases the crack (0.0 left) because in a 5 × 5 window only 10 of the 25 pixels belong to a crack 2 pixels wide, so the median is the background value. For Gaussian noise the bilateral filter has the lowest RMSE, 4.4, and keeps the edge, but only 31.4 of the 50 units of crack contrast remain. The rule of thumb is that the median kernel must be smaller than twice the width of what you need to keep, and the effect must be measured on that feature directly.

For colour, use HSV when objects are separated by colour, because it separates hue (H) from saturation (S) and brightness (V). OpenCV gives H the range 0 to 179 and S and V the range 0 to 255; other software uses other scales, so convert when you carry thresholds across tools (OpenCV colour-space tutorial). A colour mask usually has small scattered specks from noise. A morphological opening, an erosion followed by a dilation with a small kernel, removes them (OpenCV morphology tutorial).

Example 5 Measuring vegetation in the joints with HSV

A synthetic 480 × 160 pixel image of grey concrete panels with elliptical vegetation in three joints and a shadow cast over one stretch of the panels. Compare a “green dominates” rule in RGB with HSV (H 35 to 85, S at least 70, V at least 40), and with HSV followed by a 3 × 3 opening, reporting the percentage of vegetation in a 100 pixel wide window around each joint.

import cv2
import numpy as np

H, W = 160, 480
rng = np.random.RandomState(11)
img = np.full((H, W, 3), (150, 156, 158), np.uint8)       # grey concrete (BGR)
img = np.clip(img + rng.normal(0, 6, img.shape), 0, 255).astype(np.uint8)
truth = np.zeros((H, W), bool)                 # ground truth of vegetation
joints = [(40, 80), (200, 80), (360, 80)]      # centres of three joints (x, y)
sizes = [(10, 30), (18, 40), (4, 12)]          # half axes of the vegetation ellipses (x, y)
for (cx, cy), (ax, ay) in zip(joints, sizes):
    cv2.ellipse(img, (cx, cy), (ax, ay), 0, 0, 360, (55, 135, 60), -1)
    cv2.ellipse(truth.view(np.uint8), (cx, cy), (ax, ay), 0, 0, 360, 1, -1)
img[20:140, 100:160] = (img[20:140, 100:160] * 0.45).astype(np.uint8)   # a shadow cast on the panels
img = np.clip(img + rng.normal(0, 8, img.shape), 0, 255).astype(np.uint8)

b, g, r = [img[..., i].astype(int) for i in range(3)]
rule_rgb = (g > r + 8) & (g > b + 8)           # a "green dominates" RGB rule
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
rule_hsv = cv2.inRange(hsv, (35, 70, 40), (85, 255, 255)) > 0     # H 35-85, S >= 70, V >= 40 (OpenCV hue runs 0-179)
clean = cv2.morphologyEx(rule_hsv.astype(np.uint8), cv2.MORPH_OPEN, np.ones((3, 3), np.uint8)) > 0

def cover(mask, cx, half=50):                  # percent vegetation in a window around a joint
    return 100 * mask[:, max(cx - half, 0):cx + half].mean()

print("joint  truth%  RGB rule%  HSV%  HSV+open%")
for k, (cx, cy) in enumerate(joints, 1):
    print(f"{k:5d} {cover(truth, cx):7.1f} {cover(rule_rgb, cx):10.1f} {cover(rule_hsv, cx):5.1f} {cover(clean, cx):10.1f}")
shadow = (slice(20, 140), slice(100, 160))
print(f"false green in the shadow only: RGB rule {100 * rule_rgb[shadow].mean():.1f}%, HSV {100 * rule_hsv[shadow].mean():.1f}%, HSV+open {100 * clean[shadow].mean():.1f}%")
joint  truth%  RGB rule%  HSV%  HSV+open%
    1     7.0       22.4   7.2        7.0
    2    14.8       28.3  15.4       14.8
    3     1.1       17.6   1.2        1.1
false green in the shadow only: RGB rule 12.0%, HSV 6.2%, HSV+open 0.0%

The RGB rule badly overstates the vegetation (22.4%, 28.3% and 17.6% against true values of 7.0%, 14.8% and 1.1%) because noise in each channel makes some grey pixels look green-dominant. HSV gives 7.2%, 15.4% and 1.2%, very close to the truth, and the opening brings all three joints to the true values. In the shadow region 12.0% of the pixels are wrongly classed as green by the RGB rule and 6.2% by HSV, before the opening reduces that to 0.0%. In shadow the pixels get darker and noise makes the saturation (S) swing high, so some pixels pass the green test by chance. The lower limits of S and V must therefore be set sensibly and tested on an image whose light differs from the one used to set the thresholds.

Frames from thermal and multispectral sensors

Everything so far assumed an ordinary 8-bit colour frame. A thermal or multispectral camera delivers different data, and treating it like a photograph is the easiest way to corrupt it.

Thermal frames are often 16-bit counts, not pictures. A radiometric module such as the FLIR Lepton can report temperature in kelvin with a step of 0.1 K or 0.01 K that the user selects (FLIR, 2016), so the first job is to read the scale from the documentation or metadata and convert: °C = counts × step − 273.15. Casting to 8 bits with astype(np.uint8) keeps only the low byte and scrambles the values. For display, the module converts its 14-bit image into a contrast-enhanced one with a histogram-based function (FLIR, 2016); a percentile stretch in your own code does the same job, but only for the eye. The same person gets a different grey level when something hotter enters the frame, so detection thresholds belong on temperature, not on grey level.

Multispectral frames give one image per band. NDVI is (NIR − red)/(NIR + red) from the near-infrared and red bands (USGS, n.d.), and pixels where both bands are zero must be masked, not divided. A pretrained network that expects three colour channels cannot take four or five bands directly: feed a three-band composite such as near infrared, red and green, or change the first layer and fine-tune. Band alignment and conversion to reflectance come first, as in the MicaSense image-processing tutorials (MicaSense, n.d.).

Example 6 What does a careless conversion do to thermal data?

A 6 × 8 raw thermal frame is stored in counts of 0.01 K (a scale assumed for the example): a background at 295.05 K, a warm person and a hot vent. Convert it to °C, see what an 8-bit cast does, see how a percentile stretch changes the person’s grey level when the vent is in view, and compute NDVI for four multispectral pixels (canopy, mud, water and no data) with the no-data pixel masked.

import numpy as np

# a 6 x 8 raw thermal frame in counts of 0.01 K (the scale a radiometric module reports in its documentation)
raw = np.full((6, 8), 29505, np.uint16)       # 295.05 K background
raw[2:4, 3:5] = 30705                         # a warm person
raw[0, 7] = 33105                             # a hot vent
celsius = raw * 0.01 - 273.15
print(f"background {celsius[5, 0]:.1f} C, person {celsius[2, 3]:.1f} C, vent {celsius[0, 7]:.1f} C")

wrapped = raw.astype(np.uint8)                # wrong: the high byte is thrown away
print(f"cast to 8 bit: background {wrapped[5, 0]}, person {wrapped[2, 3]}, vent {wrapped[0, 7]}")

def stretch(a):                               # display only: scale the 1st to 99th percentile to 0..255
    lo, hi = np.percentile(a, (1, 99))
    return np.clip((a - lo) / (hi - lo), 0, 1) * 255

with_vent, no_vent = raw.astype(float), raw.astype(float)
no_vent[0, 7] = 29505
print(f"person after stretch: {stretch(with_vent)[2, 3]:.0f} with the vent in view, {stretch(no_vent)[2, 3]:.0f} without it")
print(f"pixels above 30 C: {int((celsius > 30).sum())}")

# multispectral: NDVI from reflectance; the last pixel has no data (both bands 0)
nir = np.array([0.45, 0.30, 0.02, 0.0])
red = np.array([0.04, 0.20, 0.05, 0.0])
den = nir + red
ndvi = np.where(den > 0, (nir - red) / np.where(den > 0, den, 1), np.nan)
print("NDVI canopy, mud, water, no data:", [None if np.isnan(x) else round(float(x), 2) for x in ndvi])
background 21.9 C, person 33.9 C, vent 57.9 C
cast to 8 bit: background 65, person 241, vent 81
person after stretch: 124 with the vent in view, 255 without it
pixels above 30 C: 5
NDVI canopy, mud, water, no data: [0.84, 0.2, -0.43, None]

Converted correctly, the frame reads 21.9 °C, 33.9 °C and 57.9 °C, and five pixels exceed 30 °C (the person’s four and the vent). The 8-bit cast turns the 57.9 °C vent into 81, close to the background’s 65, while the person becomes 241: the hottest object in the frame has vanished. The percentile stretch keeps the order, but the person is 124 with the vent in view and 255 without it, so a grey-level threshold would work in one frame and fail in the next. NDVI is 0.84 for canopy, 0.20 for mud and −0.43 for water, and the no-data pixel stays empty instead of being reported as 0.

Module lab

Lab: build a pipeline that receives, checks and records frames

  1. Record at least 30 s of video from a training drone flying slowly along a building or road at the university, within CAAT conditions in visual line of sight, or use the sample video the lecturer provides.
  2. Write a script that reads the video with VideoCapture, records the arrival time of each frame with a clock that never goes backwards, and reports the missing frames, the real frame rate and the longest gap, as in Example 1.
  3. Time your group’s processing stage and feed the real times to the queue simulator of Example 2. Choose a queue size and drop policy, with reasons.
  4. Add the quality gate of Example 3 and tune the thresholds on the real frames. Report how many frames were accepted and dropped, with three dropped frames shown and the reason for each.
  5. Add your own noise to one frame, try three filters and measure how much of the edge or line you care about is left, as in Example 4.
  6. If the scene has vegetation or a dominant colour, separate it with HSV and compare with an area drawn by hand on the same image.

Common mistakes

Watch out

  • Using the frame count instead of time. When frames go missing the real spacing is longer than assumed and the overlap falls short.
  • Using an unbounded queue. The application ends up processing images from several seconds ago without knowing it.
  • Setting the sharpness threshold as a fixed number, when the value depends on how rough the surface is.
  • Trusting the value from get(), which is 0 when the backend does not support the property.
  • Using a large median kernel on thin lines. The line disappears even though the image looks cleaner.
  • Forgetting that OpenCV orders colour as BGR and then applying colour thresholds from another tool directly.

Summary

  • An image is a large BGR array; decoding and processing time belong in the application’s budget, and frame time replaces frame count.
  • The load of the processing stage must not exceed 1, and a bounded queue controls latency according to .
  • Navigation should drop old frames to keep the data fresh; inspection should record every frame and process after the flight.
  • A quality gate uses relative sharpness, the fraction of clipped pixels and the mean brightness together.
  • Choose the filter for the type of noise and measure the result on the feature to be kept; separate colours with HSV and remove scattered specks with an opening.

Self-check questions

  1. An image with 1,080 rows has a GSD of 0.020 m and the drone flies at 5.0 m/s. For 70% overlap, how often should a key frame be taken, and what is that in frames at 30 fps?
  2. A 25 fps camera feeds a stage that takes 50 ms per frame on average. What is the maximum number of frames per second it can process, and what happens to latency with an unbounded queue?
  3. A system holds 3.3 frames on average and 27 frames per second pass through it. What is the mean latency of a frame?
  4. The sharpness (variance of the Laplacian) of the reference frame is 60 and a new frame gives 24. With a threshold of 0.5 times the reference, should the frame be accepted or dropped?
  5. Why does a 5 × 5 median erase a crack 2 pixels wide, even though it reduces noise well?
Answers
  1. The image length along the flight line is m. The spacing between key frames is m, which takes s, or frames.
  2. It can process frames per second, fewer than 25 fps. The load is , so an unbounded queue grows by about 5 frames every second and the latency increases without limit.
  3. s, about 122 ms.
  4. The ratio is , below 0.5, so the frame is dropped.
  5. A 5 × 5 window holds 25 pixels, and a crack 2 pixels wide covers only 10 of them, fewer than half. The median is therefore the background value and the crack disappears.

Key formulas

Queue law of Little
Overlap along the flight line
Sharpness from the variance of the Laplacian

Key references

  1. Szeliski, R. (2022). Computer vision: Algorithms and applications (2nd ed.). Springer. link
  2. OpenCV. OpenCV documentation. link
  3. opencv-python-headless. Python Package Index (release history checked 2 October 2026). link
  4. OpenCV. cv::VideoCapture class reference. OpenCV 4.x documentation. link
  5. GStreamer. queue element (coreelements plugin). GStreamer documentation. link
  6. Little, J. D. C. (1961). A proof for the queuing formula: L = λW. Operations Research, 9(3), 383–387. link
  7. Little, J. D. C. (2011). Little's law as viewed on its 50th anniversary. Operations Research, 59(3), 536–549. link
  8. Pech-Pacheco, J. L., Cristóbal, G., Chamorro-Martínez, J., & Fernández-Valdivia, J. (2000). Diatom autofocusing in brightfield microscopy: A comparative study. In Proceedings 15th International Conference on Pattern Recognition (Vol. 3, pp. 314–317). IEEE. link
  9. OpenCV. Smoothing images. OpenCV 4.x Python tutorials. link
  10. OpenCV. Changing colorspaces. OpenCV 4.x Python tutorials. link
  11. OpenCV. Morphological transformations. OpenCV 4.x Python tutorials. link
  12. FLIR Systems, Inc. (2016). FLIR Lepton with radiometry datasheet (Document No. 500-0763-01-09, Rev. 110). link
  13. U.S. Geological Survey. Landsat normalized difference vegetation index. link
  14. MicaSense. imageprocessing: MicaSense RedEdge and Altum image processing tutorials (MIT License) [Software]. GitHub. link

Further reading

Study the assigned knowledge units in advance, review media and take the module quiz

In class / field

Lab or field practice from worksheets with a safety checklist

Learning evidence: Checked worksheets and quiz results

Module quiz

This is a formative self-check, not a graded exam

Knowledge domain: Surveying, mapping and geoinformatics · Artificial intelligence and computer vision · Inspection, industry and surveillance