Module 15/15 · Weeks 15 · 9 h

Developing inspection, navigation, surveying and intelligent-system applications

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

About 100 minDraft, awaiting reviewLast updated 1 October 2026

Lesson

By the end of this module you will be able to

  1. Turn the requirements of a job into measurable acceptance criteria and design a test that proves them with a confidence interval
  2. Design a marker-based navigation application, from ArUco detection and pose estimation with solvePnP to sending the target angles to the autopilot
  3. Choose the gain of a vision-based control loop that stays stable given the latency of the vision system
  4. Judge the conformity of a survey result with a decision rule that has a guard band derived from the measurement uncertainty
  5. Design N-of-M-frame alerting and a landing state machine that copes with losing sight of the pad, and write the acceptance test as code

Prerequisites: Modules 11 to 14 of this course · UAT 305 Autopilot technology and control systems (recommended) · UAT 106 Statistics and data analysis for technology (recommended)

Why this matters

The first four modules supplied the tools: video pipelines, registration, detection and segmentation, tracking and measurement. But tools are not an application. An application that can be delivered must answer three questions: how is it accepted as meeting the requirement, how does it fail when real conditions differ from the design, and who decides when the system is unsure. This module assembles what has been learned into the four applications of the canal case and uses the acceptance test to decide when the work is finished.

ApplicationInputOutputDecided byKey measure
InspectionHigh-resolution stills after the flightA crack register with width ± UThe inspecting engineerRecall (lower bound of its interval), false alarms per panel
NavigationLive video on boardAngle and position of a targetThe autopilotLatency, availability, stability
SurveyingA set of images with targetsA number with its uncertaintyThe acceptance inspectorA guarded conformity decision
Intelligent systemContinuous videoEvents and alertsThe operatorFalse alerts per hour, delay

The development sequence is the same for all four: write the requirement, turn it into measurable acceptance criteria, design the pipeline, prepare test data that is kept apart from the data used for tuning, test, design the handling of failures, and monitor after use. The method of inspecting structures with drones is in UAT 453, and verification and validation at system level is in the knowledge unit on systems engineering. This module concentrates on the part that concerns images.

The inspection application and the acceptance test

A requirement such as “must find nearly all cracks” cannot be accepted. It must be written as a measurable criterion, for example: “the recall for cracks 1.0 mm wide or more is not below 0.90, with the lower end of its 95% confidence interval not below 0.90, and no more than 2 false alarms per concrete panel” (the figures are an assumed agreement for the project). The test is to seed cracks of known position (for example drawn with a coloured pencil or as stickers of a line with known width) in panels that are then photographed, and see how many the system finds. Recall is a proportion estimated from a limited number of cases, so it must be reported with a confidence interval. The Wilson interval (1927) works better than the normal approximation when the number is small or the proportion is near 1. False alarms are counts of events and use a one-sided Poisson upper bound computed from the chi-square distribution.

Example 1 Accepting recall and false alarms

40 cracks of known position were seeded and the system found 37, and raised 9 false alarms in the 12 panels inspected (assumed). The acceptance criteria are a lower bound of recall of at least 0.90 and an upper bound of false alarms of at most 2 per panel. The last lines compute how many cracks must be seeded to prove a recall of at least 0.90.

import numpy as np
from scipy import stats

def wilson(x, n, z=1.96):                      # Wilson confidence interval of a proportion
    p = x / n
    centre = (p + z * z / (2 * n)) / (1 + z * z / n)
    half = z * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
    return centre - half, centre + half

found, seeded = 37, 40                         # 40 cracks of known position were seeded and the system found 37 (assumed)
lo, hi = wilson(found, seeded)
print(f"recall {found / seeded:.3f}, 95% interval {lo:.3f} to {hi:.3f}")
print(f"requirement recall >= 0.90 (lower bound): {'PASS' if lo >= 0.90 else 'FAIL'}")

false_alarms, panels = 9, 12                   # 9 false alarms in 12 panels inspected (assumed)
upper = stats.chi2.ppf(0.95, 2 * (false_alarms + 1)) / 2 / panels             # one-sided 95% Poisson upper bound
print(f"false alarms {false_alarms / panels:.2f} per panel, 95% upper bound {upper:.2f}; requirement <= 2 per panel: {'PASS' if upper <= 2 else 'FAIL'}")

print("how many seeded cracks are needed to show recall >= 0.90 with the lower bound?")
for true_recall in (0.95, 0.97, 0.99):
    for n in range(10, 400):
        if wilson(round(true_recall * n), n)[0] >= 0.90:
            print(f"  if the true recall is {true_recall:.2f}: n = {n} (expected misses {n - round(true_recall * n)})")
            break
n0 = int(np.ceil(np.log(0.05) / np.log(0.90)))
print(f"with no misses at all: {n0} cracks (0.90^{n0} = {0.90 ** n0:.3f} <= 0.05)")
recall 0.925, 95% interval 0.801 to 0.974
requirement recall >= 0.90 (lower bound): FAIL
false alarms 0.75 per panel, 95% upper bound 1.31; requirement <= 2 per panel: PASS
how many seeded cracks are needed to show recall >= 0.90 with the lower bound?
  if the true recall is 0.95: n = 127 (expected misses 6)
  if the true recall is 0.97: n = 69 (expected misses 2)
  if the true recall is 0.99: n = 35 (expected misses 0)
with no misses at all: 29 cracks (0.90^29 = 0.047 <= 0.05)

The measured recall is 0.925, which looks like a pass, but the 95% interval is 0.801 to 0.974, and the lower end of 0.801 is below 0.90, so it fails: 40 cracks are not enough to confirm that recall reaches 0.90. The false alarms are 0.75 per panel with a 95% upper bound of 1.31, which does not exceed 2, so that criterion passes. The table of seeded cracks needed shows that if the true recall is 0.95, as many as 127 cracks are needed (about 6 misses); if it is 0.97, 69; and if it is 0.99, 35. With no misses at all, 29 consecutive cracks must be found (). The conclusion is that the test plan must compute the sample size beforehand, and not test whatever is convenient and then look at the result.

Horizontal bar chart of four bars of the number of cracks that must be seeded. True recall 0.95 needs 127 cracks, true recall 0.97 needs 69, true recall 0.99 needs 35, no misses needs 29.
Figure 1 Seeded cracks needed to show a recall of at least 0.90

The navigation application: landing on a pad and vision-based control

Two kinds of navigation use images in this case. The first is flying along the canal, using the tilt and the canal-centre position from the Hough transform of module 12 as commands to turn and move sideways. The second is landing on a pad at the pumping station, which uses a square marker with a code inside it, such as ArUco (Garrido-Jurado et al., 2014) or AprilTag (Olson, 2011). The OpenCV ArUco tutorial explains that one marker gives four corners, enough to compute the pose of the camera, and that it works with OpenCV 4.7 and later (through the ArucoDetector class). Once the four corners are found in the image, the function cv2.solvePnP with the option SOLVEPNP_IPPE_SQUARE estimates the position of the marker in camera coordinates, provided the corners are ordered as the documentation requires (OpenCV calib3d module).

What goes to the autopilot: ArduPilot uses the MAVLink message LANDING_TARGET, sent by the companion computer. It carries angle_x and angle_y (radians) for the direction to the target relative to the image centre, computed as and , together with a distance. With PLND_ENABLED = 1 and PLND_TYPE = 1, the ArduPilot documentation says that precision landing needs a valid horizontal position estimate and a steady attitude, and that a poor GPS or EKF or a noisy rangefinder degrades performance. The parameter PLND_STRICT sets what happens when the target is lost: land normally, retry and then land, or retry and then hover. The PX4 documentation reports that the infrared sensor and beacon method gives an accuracy of about 10 cm while GPS may be off by several metres, which is why an image-based aid is wanted.

Example 2 Detecting an ArUco marker and estimating position by height

A downward camera of 1280 × 720 pixels with a horizontal field of view of 90° (a focal length of 640 pixels). A DICT_4X4_50 marker with ID 7, 0.60 m wide with a white border around it. The drone is off the pad by x = 0.40 m and y = −0.25 m. Synthetic images with blur and noise are made at heights from 3 to 30 m, and the example reports whether the marker is found, the range and lateral error from solvePnP, and the angles angle_x and angle_y.

import cv2
import numpy as np

W, H, FPX = 1280, 720, 640.0                   # a downward camera, 1280x720, 90 degree horizontal field of view (assumed)
K = np.array([[FPX, 0, W / 2], [0, FPX, H / 2], [0, 0, 1.0]])
SIDE = 0.60                                    # landing pad marker, 0.60 m side (the black border)
aruco = cv2.aruco
dic = aruco.getPredefinedDictionary(aruco.DICT_4X4_50)
marker = aruco.generateImageMarker(dic, 7, 160)
pad = cv2.copyMakeBorder(marker, 40, 40, 40, 40, cv2.BORDER_CONSTANT, value=255)   # a white quiet zone around the marker
PAD_M = SIDE * pad.shape[0] / marker.shape[0]                                       # pad width including the quiet zone (m)

def render(z, dx, dy, tilt_deg, seed):
    t = np.radians(tilt_deg)
    R = np.array([[1, 0, 0], [0, np.cos(t), -np.sin(t)], [0, np.sin(t), np.cos(t)]])   # camera tilted about x
    c = np.array([dx, dy, 0.0])
    s = PAD_M / pad.shape[0]
    corners = np.array([[0, 0], [pad.shape[1], 0], [pad.shape[1], pad.shape[0]], [0, pad.shape[0]]], np.float64)
    world = np.c_[(corners[:, 0] - pad.shape[1] / 2) * s, (corners[:, 1] - pad.shape[0] / 2) * s, np.zeros(4)]
    cam = (R @ (world - c + np.array([0, 0, z])).T).T   # position in camera coordinates (z points down)
    uv = (K @ cam.T).T
    uv = uv[:, :2] / uv[:, 2:3]
    Hm = cv2.getPerspectiveTransform(corners.astype(np.float32), uv.astype(np.float32))
    img = cv2.warpPerspective(pad, Hm, (W, H), borderValue=110)
    img = cv2.GaussianBlur(img, (0, 0), 1.0)
    return np.clip(img + np.random.RandomState(seed).normal(0, 3, img.shape), 0, 255).astype(np.uint8)

detector = aruco.ArucoDetector(dic, aruco.DetectorParameters())
obj = np.array([[-SIDE / 2, SIDE / 2, 0], [SIDE / 2, SIDE / 2, 0], [SIDE / 2, -SIDE / 2, 0], [-SIDE / 2, -SIDE / 2, 0]], np.float32)   # corner order required by solvePnP IPPE_SQUARE
print("height  marker side  found   range error  lateral error  landing-target angles (deg)")
for z in (3, 6, 10, 15, 20, 30):
    img = render(z, 0.40, -0.25, 0.0, z)       # the drone is off the pad by x = 0.40 m, y = -0.25 m
    corners, ids, _ = detector.detectMarkers(img)
    side_px = FPX * SIDE / z
    if ids is None or 7 not in ids.ravel():
        print(f"{z:5d} m {side_px:9.0f} px {'no':>6s}")
        continue
    c = corners[list(ids.ravel()).index(7)].reshape(4, 2).astype(np.float32)
    ok, rvec, tvec = cv2.solvePnP(obj, c, K, None, flags=cv2.SOLVEPNP_IPPE_SQUARE)
    t = tvec.ravel()
    true = np.array([-0.40, 0.25, float(z)])   # pad position in camera coordinates (opposite to the drone offset)
    centre = c.mean(axis=0)
    ang = np.degrees(np.arctan2(centre - K[:2, 2], FPX))   # angle_x, angle_y of the target for the LANDING_TARGET message
    print(f"{z:5d} m {side_px:9.0f} px {'yes':>6s} {abs(t[2] - z) * 100:9.1f} cm {np.hypot(*(t[:2] - true[:2])) * 100:11.1f} cm   x {ang[0]:6.2f}, y {ang[1]:6.2f}")
height  marker side  found   range error  lateral error  landing-target angles (deg)
    3 m       128 px    yes       0.4 cm         0.3 cm   x  -7.61, y   4.73
    6 m        64 px    yes       9.4 cm         0.8 cm   x  -3.80, y   2.42
   10 m        38 px    yes      24.0 cm         1.2 cm   x  -2.30, y   1.41
   15 m        26 px    yes      65.8 cm         2.2 cm   x  -1.54, y   0.92
   20 m        19 px     no
   30 m        13 px     no

At 3 m the marker is 128 pixels wide and is found, with the position off by only 0.4 cm in range and 0.3 cm sideways. The angles are −7.61° and 4.73°, matching and . At 10 m the marker is 38 pixels wide, the lateral error is still only 1.2 cm, but the range is off by 24.0 cm, and at 15 m (26 pixels) the lateral error is 2.2 cm while the range is off by 65.8 cm. At 20 m (19 pixels) and 30 m (13 pixels) the marker is not found at all. Three lessons follow. First, the angle to the target is far more accurate than the range when the marker is small in the image, so a rangefinder or barometer should supply the range. Second, the height at which detection starts is limited by the marker size in pixels (here about 26 pixels is found and 19 is not), which can be computed beforehand from . Third, if the pad must be found from greater heights, nested markers of two sizes are needed.

Once the angle to the target is known, the application must command the drone to move toward it, which is a simple case of visual servoing. Chaumette and Hutchinson (2006) explain that image-based control feeds the error measured in the image, , into a velocity command , which in a system with no delay makes the error decay exponentially, . A real system has a delay from image processing, waiting for the next frame and the response of the drone, and the equation becomes . With a gain that is too high the loop oscillates and becomes unstable (knowledge from the control courses, including UAT 305).

Example 3 Gain against the latency of the vision system

The drone starts 2.0 m off the pad sideways. The detector delivers a result at 15 Hz with a vision latency of 0.15 s, and the drone follows the velocity command as a first-order lag with a time constant of 0.30 s (assumed). Simulate 30 s at gains from 0.2 to 6.0 per second, reporting the overshoot (the excursion past zero to the other side) and the time after which the error stays within ±0.1 m.

import numpy as np

DT = 0.005                                     # simulation step (s)
RATE, LATENCY, LAG = 15.0, 0.15, 0.30          # detector rate (Hz), vision latency (s), drone velocity time constant (s) (assumed)

def simulate(lam, e0=2.0, t_end=30.0):
    n, e, v, cmd = int(t_end / DT), e0, 0.0, 0.0
    hist = np.zeros(n)
    next_frame = 0.0
    delay_steps = int(round(LATENCY / DT))
    for i in range(n):
        t = i * DT
        hist[i] = e
        if t >= next_frame:                    # a new frame result arrives: the command uses the offset seen LATENCY ago
            e_seen = hist[max(i - delay_steps, 0)]
            cmd = -lam * e_seen                # commanded velocity proportional to the offset seen (P law)
            next_frame += 1 / RATE
        v += DT / LAG * (cmd - v)              # the drone follows the velocity command with a first-order lag
        e += DT * v
        if abs(e) > 50:
            return hist[:i + 1], True
    return hist, False

print("gain 1/s  result       overshoot  time inside +-0.1 m")
for lam in (0.2, 0.5, 1.0, 1.5, 2.5, 4.0, 6.0):
    h, blown = simulate(lam)
    if blown:
        print(f"{lam:8.1f}  unstable (offset grows without limit)")
        continue
    undershoot = max(0.0, -h.min())            # the largest excursion to the other side of zero
    outside = np.nonzero(np.abs(h) > 0.1)[0]
    t_in = (outside[-1] + 1) * DT if outside.size else 0.0
    kind = "smooth" if undershoot < 0.1 else "oscillates"
    print(f"{lam:8.1f}  {kind:11s} {100 * undershoot / 2.0:7.1f}% {t_in:12.1f} s" + ("  (not settled in 30 s)" if t_in >= 29.9 else ""))
total = LATENCY + 0.5 / RATE + LAG             # total delay: vision + half a frame wait + drone response
print(f"total delay {total:.2f} s -> rule of thumb: gain <= 0.3 / {total:.2f} = {0.3 / total:.2f} 1/s for a smooth approach")
gain 1/s  result       overshoot  time inside +-0.1 m
     0.2  smooth          0.0%         13.8 s
     0.5  smooth          0.0%          4.7 s
     1.0  smooth          3.5%          1.7 s
     1.5  oscillates     14.3%          2.5 s
     2.5  oscillates     36.4%          2.9 s
     4.0  oscillates     65.9%          6.8 s
     6.0  oscillates    100.3%         30.0 s  (not settled in 30 s)
total delay 0.48 s -> rule of thumb: gain <= 0.3 / 0.48 = 0.62 1/s for a smooth approach

At gains of 0.2 and 0.5 per second the drone approaches the pad smoothly without crossing zero, but slowly (13.8 s and 4.7 s). At 1.0 it overshoots slightly, by 3.5%, and reaches the band in 1.7 s, the fastest in the table. At 1.5 it begins to oscillate (14.3%), at 2.5 it oscillates by 36.4%, at 4.0 by 65.9%, and at 6.0 the oscillation does not decay within 30 s. The total delay of this system is s, and a simple starting rule is per second for a smooth approach. The 0.3 in this rule is a starting point chosen from this table, not a standard value, so it must always be tested on the real drone. The important point is that reducing the delay (a faster detector, a short drop-old queue from module 11) allows a higher gain and a faster approach.

Horizontal bar chart of seven bars of overshoot by gain of 0.2, 0.5, 1.0, 1.5, 2.5, 4.0 and 6.0 per second: 0.0, 0.0, 3.5, 14.3, 36.4, 65.9 and 100.3 percent. The first three bars are green, the fourth yellow, the last three pink.
Figure 2 Overshoot of the approach to the pad by controller gain

The surveying application and conformity decisions

A survey ends in a decision such as “is the canal bottom width within tolerance?” When the measured value is uncertain, the simple decision “pass if the measured value does not exceed the limit” accepts items that may truly exceed it by a wide margin. JCGM 106, on the role of measurement uncertainty in conformity assessment, offers concepts that work: a decision rule written in advance, a guard band , which is the interval between the tolerance limit and the acceptance limit, and the probability of false acceptance. Guarded acceptance sets the acceptance limit inside the tolerance (, where is the upper limit and usually ), which reduces the risk of accepting something that fails, at the price of a greater risk of rejecting something that passes.

Example 4 Canal bottom width with a guarded rule

The design bottom width is 6.00 m with a tolerance of ±0.10 m (assumed), measured from images at a GSD of 2.0 cm. The uncertainty has four parts: the two edges at 0.5 pixel each, residual lens distortion of 0.5 pixel, ground that is not flat 0.4 pixel, and scale from a target at 0.3%. The table compares the simple rule (pass if the measurement is at most 6.10) with the guarded rule (accept if the measurement is at most 6.10 − U, reject above 6.10 + U, retest in between), computing with a normal distribution the probability that the true width exceeds 6.10 m, and then shows the effect of flight height (GSD).

import numpy as np
from scipy import stats

NOMINAL, TOL = 6.00, 0.10                      # design bottom width 6.00 m, tolerance +-0.10 m (assumed)
UPPER = NOMINAL + TOL

def uncertainty(gsd, width=6.07):              # combined standard uncertainty of the measured width (m)
    px = np.sqrt(0.5 ** 2 + 0.5 ** 2 + 0.5 ** 2 + 0.4 ** 2)     # two edges, residual distortion, non-flat ground (px)
    scale = 0.003 * width                      # scale from the reference target, 0.3%
    return np.hypot(px * gsd, scale)

gsd = 0.020
u = uncertainty(gsd)
print(f"GSD {gsd * 100:.1f} cm/px: standard uncertainty {u * 100:.1f} cm, expanded U (k = 2) {2 * u * 100:.1f} cm")
print("measured  P(true width > limit)  simple rule   guarded rule (accept if measured <= limit - U)")
for m in (6.00, 6.04, 6.07, 6.09):
    p_out = 1 - stats.norm.cdf((UPPER - m) / u)
    simple = "accept" if m <= UPPER else "reject"
    guarded = "accept" if m <= UPPER - 2 * u else ("reject" if m > UPPER + 2 * u else "retest")
    print(f"{m:7.2f} m {100 * p_out:14.1f}% {simple:>14s} {guarded:>14s}")

print("choice of flight height (GSD) for the same measurement of 6.07 m")
print("GSD cm/px  U (cm)   P(true width > limit)")
for g in (0.030, 0.020, 0.010, 0.005):
    ug = uncertainty(g)
    print(f"{g * 100:9.1f} {2 * ug * 100:7.1f} {100 * (1 - stats.norm.cdf((UPPER - 6.07) / ug)):12.1f}%")
GSD 2.0 cm/px: standard uncertainty 2.6 cm, expanded U (k = 2) 5.3 cm
measured  P(true width > limit)  simple rule   guarded rule (accept if measured <= limit - U)
   6.00 m            0.0%         accept         accept
   6.04 m            1.1%         accept         accept
   6.07 m           12.8%         accept         retest
   6.09 m           35.2%         accept         retest
choice of flight height (GSD) for the same measurement of 6.07 m
GSD cm/px  U (cm)   P(true width > limit)
      3.0     6.8         18.8%
      2.0     5.3         12.8%
      1.0     4.1          7.2%
      0.5     3.8          5.6%

At a GSD of 2.0 cm the combined standard uncertainty is 2.6 cm and U = 5.3 cm. Measurements of 6.00 and 6.04 m pass both rules (probabilities that the truth exceeds the limit of 0.0% and 1.1%), but at 6.07 m the simple rule still accepts although the probability that the true width exceeds 6.10 m is 12.8%. The guarded rule orders a retest, because the acceptance limit is 6.10 − 0.053 = 6.047 m, and at 6.09 m the probability jumps to 35.2% while the simple rule still accepts. The last table shows the effect of flight height. Reducing the GSD from 3.0 to 2.0, 1.0 and 0.5 cm lowers U from 6.8 to 5.3, 4.1 and 3.8 cm and the probability from 18.8% to 12.8%, 7.2% and 5.6%. The gain shrinks because once the pixels are small enough, what remains is the scale error (0.3% of 6.07 m is 1.8 cm), which is cured by a more accurate target, not by flying lower.

A number line of the canal bottom width from 5.95 to 6.25 m in three zones. The left green zone, accept, ends at 6.047 m; the middle yellow zone, retest, runs from 6.047 to 6.153 m; the right pink zone is reject. A pink mark at the upper limit of 6.10 m. Below, a dot for the measured 6.07 m with a plus or minus 0.053 m interval, lying in the retest zone.
Figure 3 A guarded decision rule for the canal bottom width; the measured 6.07 m is in the retest zone

Intelligent systems, alerting and handling failure

An intelligent system that raises an alert when it finds floating debris must do three things in a loop: perceive, decide and pass the result to a person. The level of automation should be chosen deliberately (Parasuraman et al., 2000). In this job the system advises and alerts, and the operator decides whether to remove the object or change the flight plan. A per-frame detector often raises a false alert from time to time. If it alerts every time it fires, the operator is flooded and stops trusting the system. The usual remedy is an N-of-M-frame rule: alert when at least N of the last M frames fired, and keep quiet for a while after an alert. It trades false alerts against delay and against the chance of missing an object seen only briefly.

The other side of the system is handling failure. Avizienis et al. (2004) separate a fault, the cause, from an error, the incorrect internal state, and a failure, when the service deviates from what is specified. In this application, a lens smeared with water (fault) makes blurred frames that the quality gate rejects (an error that is caught). Without the gate the system would measure from blurred frames and report a wrong crack (failure). So you must design the points where errors are caught along the pipeline and decide what to do once one is caught: reduce the level of operation, hand over to a person, or stop. Landing on a marker is a state machine, and its acceptance test can be written as code.

Example 5 The N-of-M-frame rule and testing the landing state machine

The first part simulates 30 fps video in which small floating debris is detected with a 40% chance per frame during the 1.5 s of an event, with a 4% false-detection chance per frame (assumed). The rules 1 of 1, 3 of 5, 5 of 10 and 8 of 15 are compared, counting false alerts per hour in a one-hour video with no event (with a quiet time of 10 s), the proportion of real events caught, and the median delay. The second part is a landing state machine with four states: SEARCH, TRACK, DEGRADED and ABORT, with a decision cycle of 0.1 s. It enters TRACK after seeing the marker for 3 cycles in a row, drops to DEGRADED when the marker is not seen, returns to TRACK after 3 consecutive cycles of seeing it, and enters ABORT after more than 2.0 s in DEGRADED, with five test cases whose correct outcomes are known beforehand.

import numpy as np

FPS = 30
P_HIT, P_FALSE = 0.40, 0.04                    # per-frame chance of detecting the debris, and of a false detection (assumed)
rng = np.random.RandomState(21)

def trigger(det, n, m):                        # true when n of the last m frames fired
    return np.convolve(det.astype(int), np.ones(m, int))[:len(det)] >= n          # entry i is the window ending at frame i

def alerts(det, n, m, cooldown=10 * FPS):      # count alert messages with a 10 s quiet time after each
    hit = trigger(det, n, m)
    onsets = np.nonzero(hit & ~np.r_[False, hit[:-1]])[0]
    out, last = [], -10 ** 9
    for o in onsets:
        if o - last >= cooldown:
            out.append(o); last = o
    return out

hours = 1.0
no_event = rng.rand(int(hours * 3600 * FPS)) < P_FALSE                   # one hour with nothing happening
print("rule          false alerts per hour   event caught   median delay")
for n, m in ((1, 1), (3, 5), (5, 10), (8, 15)):
    fa = len(alerts(no_event, n, m)) / hours
    delays = []
    for _ in range(400):                       # a real event lasting 1.5 s (45 frames) starting at frame 240
        det = rng.rand(600) < P_FALSE
        det[240:285] = rng.rand(45) < P_HIT
        hit = trigger(det, n, m)
        hit[:240] = False                      # count only triggers inside the event
        inside = np.nonzero(hit[240:285])[0]
        if inside.size:
            delays.append(inside[0] / FPS)
    med = f"{np.median(delays):.2f} s" if delays else "-"
    print(f"{n:2d} of {m:2d} {fa:21.1f} {100 * len(delays) / 400:12.0f}% {med:>13s}")

# marker landing states, and the acceptance test written as code
TICK = 0.1                                     # seconds per decision cycle
def run(events):
    state, seen_run, degraded, log = "SEARCH", 0, 0, []
    for e in events:                           # e = 1 marker seen, 0 not seen
        seen_run = seen_run + 1 if e else 0
        if state == "SEARCH" and seen_run >= 3:
            state = "TRACK"
        elif state == "TRACK" and not e:
            state, degraded = "DEGRADED", 1
        elif state == "DEGRADED":
            degraded += 1
            if seen_run >= 3:                  # return only after 3 seen cycles in a row, to avoid chatter
                state = "TRACK"
            elif degraded * TICK > 2.0:
                state = "ABORT"
        log.append(state)
    return log

cases = {
    "marker visible all the way":     ([1] * 30,                                 "TRACK", None),
    "lost for 0.5 s then back":       ([1] * 10 + [0] * 5 + [1] * 10,            "TRACK", None),
    "lost for 3 s":                   ([1] * 10 + [0] * 30,                      "ABORT", 10 + 21),
    "flicker: seen every other cycle": ([1] * 10 + [0, 1] * 30,                  "ABORT", None),
    "never seen":                     ([0] * 30,                                 "SEARCH", None),
}
for name, (ev, final, abort_at) in cases.items():
    log = run(ev)
    when = log.index("ABORT") if "ABORT" in log else None
    ok = log[-1] == final and (abort_at is None or when == abort_at - 1)
    print(f"{'PASS' if ok else 'FAIL'}  {name:32s} final {log[-1]:8s}" + (f", abort at cycle {when + 1} ({(when + 1) * TICK:.1f} s)" if when is not None else ""))
rule          false alerts per hour   event caught   median delay
 1 of  1                 331.0          100%        0.03 s
 3 of  5                  25.0          100%        0.20 s
 5 of 10                   2.0           98%        0.40 s
 8 of 15                   0.0           76%        0.63 s
PASS  marker visible all the way       final TRACK   
PASS  lost for 0.5 s then back         final TRACK   
PASS  lost for 3 s                     final ABORT   , abort at cycle 31 (3.1 s)
PASS  flicker: seen every other cycle  final ABORT   , abort at cycle 31 (3.1 s)
PASS  never seen                       final SEARCH  

The 1-of-1 rule gives 331 false alerts per hour (hitting the ceiling set by the 10 s quiet time) although it catches 100% of events. The 3-of-5 rule cuts this to 25 per hour while still catching 100% with a median delay of 0.20 s. The 5-of-10 rule gives 2 per hour but misses 2% of events, and the 8-of-15 rule has no false alert at all in that hour but misses 24% of events (76% caught), because the event lasts only 1.5 s and only 40% of the frames fire, with a median delay of 0.63 s. No rule is best without looking at the job; the choice comes from the cost of a false alert against the cost of a miss. For the state machine, all five cases pass, including the case “marker seen every other cycle”, which can never return to TRACK because 3 consecutive cycles are needed, so it enters ABORT after more than 2.0 s in DEGRADED (cycle 31, or 3.1 s from the start) instead of switching state back and forth without end. Writing such a case as code means that every time a threshold is changed, the test can be rerun in a few seconds.

Two sets of bars. The upper set is the false alerts per hour for the rules 1 of 1, 3 of 5, 5 of 10 and 8 of 15: 331, 25, 2 and 0. The lower set is the percentage of real events caught: 100, 100, 98 and 76.
Figure 4 N-of-M-frame rules trade false alerts against missed events

The last issue is privacy. Video beside a canal may contain identifiable people. An image showing a face or a vehicle registration plate is personal data under the Personal Data Protection Act B.E. 2562 (2019), as the knowledge unit on ethics and PDPA explains. An application that uses images should therefore be designed to collect only what is needed (keep clips around events instead of the whole video), blur or crop the parts showing people before recording or exporting, set a retention period, and log who has accessed the data. The legal framework for flying and the risk assessment for flying close to structures and landing automatically are in UAT 401.

Module lab

Lab: write an acceptance plan and run the application’s test suite

  1. Choose one of the four applications, write its requirement and turn it into at least three measurable acceptance criteria (for example the lower bound of recall, false alarms per panel, p95 latency), with a pass limit and a way of measuring each.
  2. Compute the number of samples needed as in Example 1 for your group’s recall criterion, and prepare the test set (seeded cracks or labels made beforehand) to that size.
  3. For the navigation application, print an ArUco marker of known size, photograph it at several heights, report the greatest height at which it is detected and the error of the angle and range as in Example 2, and then choose the gain by simulation as in Example 3 using the latency you actually measured.
  4. For the surveying application, estimate the uncertainty budget of one width or length, write a guarded decision rule, and state the outcome for three measured values.
  5. For the intelligent-system application, choose an N-of-M rule from the costs of a false alert and of a miss that your group sets, and test it on video that holds at least five real events.
  6. Write at least five failure test cases (camera stops, dark frame, lost pad, tracker lost, slow link) as code that runs and reports pass or fail, and write a one-page acceptance report.

Common mistakes

Watch out

  • Writing requirements that cannot be measured, such as “finds nearly all cracks”, which cannot then be accepted.
  • Reporting a single recall value without a confidence interval. With few samples, a value that looks like a pass still cannot be proved.
  • Testing whatever is convenient instead of computing the sample size beforehand.
  • Using the range from a marker that is small in the image, when the range error is many times the angle error.
  • Setting the gain of a control loop without thinking about delay, which leads to oscillation during landing.
  • Judging conformity by a single measured value, without looking at the uncertainty.
  • Alerting every time the detector fires. The operator will stop trusting the system.
  • Having no state for losing sight of the target, or not writing the failure tests as code.

Summary

  • A deliverable application must say how it is accepted, how it fails and who decides. Requirements must be measurable criteria.
  • Recall must be reported with a Wilson confidence interval and the sample size computed beforehand (with no misses, 29 consecutive cracks are needed to confirm a recall of 0.90).
  • Marker navigation gives an accurate angle but an inaccurate range when the marker is small in the image, and the gain of the control loop is limited by the delay.
  • Conformity decisions need the uncertainty and a guard band, and once the pixels are small enough the remainder comes from the scale, which is cured by a more accurate target.
  • N-of-M rules trade false alerts against delay and misses. States for handling failure and tests written as code let you change the system with confidence, and the personal data in images must be protected.

Self-check questions

  1. 50 cracks were seeded and the system found 45. What are the recall and its 95% Wilson interval, and does it meet a lower bound of at least 0.90?
  2. A camera has a focal length of 640 pixels and a marker 0.60 m wide must appear at least 20 pixels wide. Up to what height can it be detected?
  3. The vision system has a latency of 0.20 s, results come at 10 Hz, and the drone responds with a time constant of 0.25 s. What is the largest gain by the rule of 0.3 divided by the total delay?
  4. The canal bottom width is measured as 6.08 m, the expanded uncertainty is U = 0.053 m and the upper limit is 6.10 m. What does the guarded rule (accept if the measurement is at most 6.10 − U) decide, and roughly what is the probability that the true width exceeds 6.10 m (standard uncertainty 0.0265 m)?
  5. A landing state machine enters ABORT after more than 2.0 s in DEGRADED, with cycles of 0.1 s. How many seconds after the marker is lost does it enter ABORT?
Answers
  1. The recall is and the 95% Wilson interval is 0.786 to 0.957. The lower end of 0.786 is below 0.90, so it does not meet the criterion.
  2. The size in the image is , which gives m.
  3. The total delay is s, and the largest gain is per second.
  4. The acceptance limit is m. The value of 6.08 m is above it, so the decision is retest (not accept). The probability that the true width exceeds 6.10 m is .
  5. The condition is the number of cycles in DEGRADED times 0.1 being greater than 2.0. The first cycle for which that is true is the 21st, so it enters ABORT about 2.1 s after the marker is lost.

Key formulas

Wilson confidence interval of a proportion
Target angles from the image centre
Proportional loop with delay
Acceptance limit of a guarded rule

Key references

  1. Szeliski, R. (2022). Computer vision: Algorithms and applications (2nd ed.). Springer. link
  2. OpenCV. OpenCV documentation. link
  3. Wilson, E. B. (1927). Probable inference, the law of succession, and statistical inference. Journal of the American Statistical Association, 22(158), 209–212. link
  4. Garrido-Jurado, S., Muñoz-Salinas, R., Madrid-Cuevas, F. J., & Marín-Jiménez, M. J. (2014). Automatic generation and detection of highly reliable fiducial markers under occlusion. Pattern Recognition, 47(6), 2280–2292. link
  5. Olson, E. (2011). AprilTag: A robust and flexible visual fiducial system. In 2011 IEEE International Conference on Robotics and Automation (pp. 3400–3407). IEEE. link
  6. OpenCV. Detection of ArUco markers. OpenCV 4.x tutorials (objdetect module). link
  7. OpenCV. Camera calibration and 3D reconstruction (calib3d module): solvePnP, triangulatePoints. OpenCV 4.x documentation. link
  8. ArduPilot Dev Team. Precision landing and loiter. ArduPilot Copter documentation. link
  9. PX4 Autopilot. Precision landing. PX4 user guide (main). link
  10. MAVLink Development Team. MAVLink common message set (common.xml). link
  11. Chaumette, F., & Hutchinson, S. (2006). Visual servo control. I. Basic approaches. IEEE Robotics & Automation Magazine, 13(4), 82–90. link
  12. JCGM. (2012). Evaluation of measurement data: The role of measurement uncertainty in conformity assessment (JCGM 106:2012). BIPM. link
  13. Avizienis, A., Laprie, J.-C., Randell, B., & Landwehr, C. (2004). Basic concepts and taxonomy of dependable and secure computing. IEEE Transactions on Dependable and Secure Computing, 1(1), 11–33. link
  14. Parasuraman, R., Sheridan, T. B., & Wickens, C. D. (2000). A model for types and levels of human interaction with automation. IEEE Transactions on Systems, Man, and Cybernetics – Part A: Systems and Humans, 30(3), 286–297. link
  15. พระราชบัญญัติคุ้มครองข้อมูลส่วนบุคคล พ.ศ. 2562. ราชกิจจานุเบกษา, 136(69 ก), 52–95. 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: Inspection, industry and surveillance · Management, innovation and professional practice · Aircraft, structures and design · Law, safety and risk