Tracking and image-based measurement
UAT 456 Artificial Intelligence, Machine Learning and Computer Vision for UAS
Lesson
By the end of this module you will be able to
- Explain the assumptions of Lucas-Kanade and use Shi-Tomasi points, pyramids and a backward check to measure the surface speed of water
- Design a single-object tracker with TRACK and COAST states that searches again after an occlusion
- Compute the image scale from the geometry and from a reference target, and combine the uncertainty of a length following the GUM
- Measure crack width near the resolution limit and state below how many pixels it cannot be measured
- Estimate the step between panels by triangulation from two camera stations, and explain the effect of the baseline and of a camera-pose error
Why this matters
Module 13 produced a mask of the crack. The next job is to measure how wide and how long it is, and to track what moves in the video. In the canal case three jobs need both: measuring the surface speed of the water from the movement of foam, tracking a floating log as it passes under a bridge, and measuring the width, length and step of a crack on a concrete panel. Each number must come with its uncertainty, because the user decides whether to repair from that number, and because measuring a crack at a GSD of only 0.289 mm is already close to the limit of the image.
UAT 307 taught tracking with the Kalman filter and depth from stereo (Z = fB/d), and UAT 451 teaches photogrammetry in full. This module therefore concentrates on what an application must know: pixel-level tracking that survives missing frames and occlusion, computing the scale with an uncertainty budget, measuring width at the resolution limit, and triangulation with the OpenCV functions, including which kinds of error cancel and which do not.
Optical flow and point tracking with KLT
Optical flow is the apparent motion of an image between two frames. The OpenCV tutorial makes two assumptions: the brightness of an object does not change between frames, and neighbouring pixels move alike. A Taylor expansion gives , where are the image gradients, is the temporal gradient and is the unknown motion. One equation has two unknowns. Lucas and Kanade (1981) solve it by assuming that the pixels in a small window move together, which gives many equations that are solved by least squares. The matrix to be inverted has the same form as that of the Harris corner detector, so places with corners can be tracked well while flat regions and single edges cannot. Shi and Tomasi (1994) therefore choose the points where the smaller eigenvalue of that matrix is large, which is cv2.goodFeaturesToTrack.
The method works when the motion is smaller than the window. For larger motion an image pyramid is used, which shrinks the image into several levels and tracks from the coarse level to the fine one (Bouguet, 2001); this is the maxLevel parameter of cv2.calcOpticalFlowPyrLK. In module 11 a run of 16 missing frames made the image jump 106 pixels, which is a case where the pyramid has to help. To learn which points were tracked wrongly, use the forward-backward error of Kalal et al. (2010): track from the first frame to the second, then track back, and drop the points that do not return to their start within a tolerance ( greater than 0.5 pixel).
Example 1 Surface speed from tracking foam
A synthetic 640 × 300 pixel image from a camera hovering at 30 m (GSD 0.020 m, 30 fps). The left side is the bank, which moves −0.3 pixel per frame because the drone drifts slightly; the right side is the water, where foam moves 2.1 pixels per frame and its pattern changes from frame to frame (assumed). Track with Shi-Tomasi and LK, without a pyramid and with 3 levels, with frames 1 apart and 16 apart, counting the points that pass the backward check, and compute the surface speed relative to the ground.
import cv2
import numpy as np
H, W, SPLIT = 300, 640, 200 # a 640x300 image: bank on the left, water on the right
GSD, FPS = 0.020, 30 # m per pixel at 30 m, frames per second (assumed)
V_WATER_PX, V_BANK_PX = 2.1, -0.3 # pixels per frame in the image: foam, and bank (the drone drifts a little)
def blobs(h, w, seed, sigma): # multi-scale texture: fine, medium and coarse patterns
r, n = np.random.RandomState(seed), 0
for sg, wt in ((sigma, 1.0), (3 * sigma, 1.5), (7 * sigma, 2.0)):
g = cv2.GaussianBlur(r.normal(0, 1, (h, w)).astype(np.float32), (0, 0), sg)
n = n + wt * g / g.std()
n = (n - n.min()) / (n.max() - n.min())
return 40 + 190 * n ** 1.5
foam, bank = blobs(H, W + 400, 1, 2.2), blobs(H, W + 400, 2, 3.0) # two textures
def frame(k):
def shifted(tex, v):
return cv2.warpAffine(tex, np.float32([[1, 0, v * k - 200], [0, 1, 0]]), (W, H), borderMode=cv2.BORDER_REFLECT)
water = 0.8 * shifted(foam, V_WATER_PX) + 0.2 * blobs(H, W, 500 + k, 2.2) # the foam also changes from frame to frame, it does not only shift
img = np.where(np.arange(W)[None, :] < SPLIT, shifted(bank, V_BANK_PX), water)
return np.clip(img + np.random.RandomState(100 + k).normal(0, 2, img.shape), 0, 255).astype(np.uint8)
def track(a, b, levels, win=21):
p0 = cv2.goodFeaturesToTrack(a, 300, 0.05, 9) # Shi-Tomasi corners
p0 = p0[(np.abs(p0[:, 0, 0] - SPLIT) > 20)] # drop points near the bank-water boundary
crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 30, 0.01)
p1, st, _ = cv2.calcOpticalFlowPyrLK(a, b, p0, None, winSize=(win, win), maxLevel=levels, criteria=crit)
back, st2, _ = cv2.calcOpticalFlowPyrLK(b, a, p1, None, winSize=(win, win), maxLevel=levels, criteria=crit)
fb = np.linalg.norm(back - p0, axis=2).ravel() # forward-backward error
ok = (st.ravel() == 1) & (st2.ravel() == 1) & (fb < 0.5)
return p0.reshape(-1, 2), p1.reshape(-1, 2), ok, st.ravel() == 1
f0 = frame(0)
print("gap levels bank points kept water points kept median px/frame: bank, water")
for gap in (1, 16):
f1 = frame(gap)
for levels in (0, 3):
p0, p1, ok, tracked = track(f0, f1, levels)
d = (p1 - p0)[:, 0] / gap
is_bank = p0[:, 0] < SPLIT
kb, kw = ok & is_bank, ok & ~is_bank
med = lambda m: f"{np.median(d[m]):5.2f}" if m.sum() >= 5 else " n/a"
print(f"{gap:3d} {levels:6d} {kb.sum():7d} of {is_bank.sum():3d} {kw.sum():10d} of {(~is_bank).sum():3d} {med(kb):>16s} {med(kw):>7s}")
f1 = frame(1)
p0, p1, ok, _ = track(f0, f1, 3)
d = (p1 - p0)[:, 0]
water_d, bank_d = d[ok & (p0[:, 0] > SPLIT)], d[ok & (p0[:, 0] < SPLIT)]
rel = np.median(water_d) - np.median(bank_d) # water speed relative to the ground (drone drift removed)
se = 1.4826 * np.median(np.abs(water_d - np.median(water_d))) / np.sqrt(water_d.size)
print(f"relative displacement {rel:.2f} px/frame -> surface speed {rel * GSD * FPS:.2f} m/s (true {(V_WATER_PX - V_BANK_PX) * GSD * FPS:.2f}), standard error {se * GSD * FPS:.3f} m/s")
gap levels bank points kept water points kept median px/frame: bank, water
1 0 13 of 13 190 of 256 -0.30 2.12
1 3 13 of 13 189 of 256 -0.30 2.13
16 0 13 of 13 12 of 256 -0.30 2.10
16 3 13 of 13 186 of 256 -0.30 2.10
relative displacement 2.42 px/frame -> surface speed 1.45 m/s (true 1.44), standard error 0.026 m/s
With frames 1 apart both methods work equally well: 189 to 190 of the 256 water points pass the check, giving 2.12 to 2.13 pixels per frame on the water and −0.30 on the bank. With frames 16 apart (the water moves 33.6 pixels) the method without a pyramid keeps only 12 points of 256, while the 3-level pyramid keeps 186, again giving 2.10 pixels per frame. The speed of the water relative to the ground must remove the motion of the bank first (2.1 − (−0.3) = 2.40 pixels per frame). The measured value is 2.42 pixels per frame, which times the GSD and fps gives 1.45 m/s (true 1.44), with a standard error of 0.026 m/s. This is the speed at the surface, not the mean speed over the canal cross-section, which needs a coefficient calibrated against a current meter, beyond the scope of this course.
A single-object tracker and handling a loss
When a single object must be tracked, such as a floating log, ready-made trackers are available, for example KCF, which uses a kernelised correlation filter (Henriques et al., 2015). The OpenCV Tracking API documentation lists TrackerKCF and TrackerCSRT in the tracking module. In this course’s environment (OpenCV 5.0.0 headless from pip) only TrackerMIL was found; KCF and CSRT need a build that includes the extra (contrib) modules. Whichever is used, what the application must always design for itself is what to do when the tracker loses the object. When the log is hidden by a bridge or leaves the image, a tracker that always accepts the best match locks onto the background and never comes back.
The next example builds a tracker from template matching (from module 13) to show the whole mechanism. It is in the TRACK state while the match score is at least 0.6. The next position is predicted from the latest velocity, and the velocity is updated only when the score is very high (0.85). When the score drops it enters the COAST state: it moves on at the old velocity without trusting the image, searching a wider window every frame, and returns to TRACK when it finds a match with a score of at least 0.8. If it is lost for more than 40 frames, it declares failure (FAILED). A normalised template match does not change with contrast, so the bridge deck must really hide the object, not just darken it.
Example 2 A log floating under a bridge
A synthetic 90-frame video of a 24 × 14 pixel log moving 3.0 pixels per frame horizontally and 0.5 pixel per frame downwards. The bridge deck is a band 60 pixels wide that hides everything beneath it. Compare (1) a tracker that accepts the best match in a ±20 pixel window every frame with (2) a tracker with the TRACK and COAST states described above.
import cv2
import numpy as np
H, W, N = 200, 420, 90
bg = cv2.GaussianBlur(np.random.RandomState(7).normal(0, 1, (H, W)).astype(np.float32), (0, 0), 2.0)
bg = 120 + 28 * bg / bg.std() # water surface
OBJ_W, OBJ_H = 24, 14
obj_tex = 200 + 30 * np.random.RandomState(8).rand(OBJ_H, OBJ_W) # a floating log, brighter than the water
truth = np.array([(40 + 3.0 * k, 100 + 0.5 * k) for k in range(N)]) # true centre (x, y)
BAND = (200, 260) # under the bridge: a dark band that hides the log
def frame(k):
img = bg.copy()
cx, cy = truth[k]
x0, y0 = int(round(cx - OBJ_W / 2)), int(round(cy - OBJ_H / 2))
img[y0:y0 + OBJ_H, x0:x0 + OBJ_W] = obj_tex
img[:, BAND[0]:BAND[1]] = 35 + 0.2 * bg[:, BAND[0]:BAND[1]] # the bridge deck hides everything under it
return np.clip(img + np.random.RandomState(200 + k).normal(0, 3, img.shape), 0, 255).astype(np.uint8)
frames = [frame(k) for k in range(N)]
tmpl = frames[0][int(truth[0][1]) - 9:int(truth[0][1]) + 9, int(truth[0][0]) - 16:int(truth[0][0]) + 16] # template from the first frame
th, tw = tmpl.shape
def search(img, centre, radius): # look for the template in a window around the expected position
x0, y0 = int(centre[0] - tw / 2 - radius), int(centre[1] - th / 2 - radius)
x0, y0 = max(x0, 0), max(y0, 0)
x1, y1 = min(int(centre[0] + tw / 2 + radius), W), min(int(centre[1] + th / 2 + radius), H)
if x1 - x0 <= tw or y1 - y0 <= th:
return centre, -1.0
res = cv2.matchTemplate(img[y0:y1, x0:x1], tmpl, cv2.TM_CCOEFF_NORMED)
_, score, _, loc = cv2.minMaxLoc(res)
return np.array([x0 + loc[0] + tw / 2, y0 + loc[1] + th / 2]), score
# 1 no loss handling: always accept the best match
pos, naive = truth[0].copy(), []
for k in range(N):
pos, _ = search(frames[k], pos, 20)
naive.append(pos)
err_naive = np.linalg.norm(np.array(naive) - truth, axis=1)
# 2 with TRACK / COAST states: a score gate, velocity prediction, and a wider search after a loss
state, pos, vel, lost_for, states, est = "TRACK", truth[0].copy(), np.array([3.0, 0.5]), 0, [], []
for k in range(N):
expect = pos + vel
if state == "TRACK":
cand, score = search(frames[k], expect, 15)
if score >= 0.6:
if score >= 0.85: # update the velocity only when sure (a partly hidden log scores low)
vel = 0.7 * vel + 0.3 * (cand - pos)
pos, lost_for = cand, 0
else:
state, pos, lost_for = "COAST", expect, 1
else: # COAST: move on at the old velocity and try a wider search
cand, score = search(frames[k], expect, 15 + 3 * lost_for)
if score >= 0.8:
state, pos, lost_for = "TRACK", cand, 0
else:
pos, lost_for = expect, lost_for + 1
if lost_for > 40:
state = "FAILED"
states.append(state); est.append(pos.copy())
if state == "FAILED":
break
err = np.linalg.norm(np.array(est) - truth[:len(est)], axis=1)
n_coast = states.count("COAST")
first_coast = states.index("COAST")
back = first_coast + states[first_coast:].index("TRACK")
hidden = [k for k in range(N) if BAND[0] <= truth[k][0] - OBJ_W / 2 and truth[k][0] + OBJ_W / 2 <= BAND[1]]
print(f"the log is fully hidden in frames {hidden[0]} to {hidden[-1]} ({len(hidden)} frames = {len(hidden) / 30:.2f} s at 30 fps)")
print(f"1 no loss handling : error at the end {err_naive[-1]:6.1f} px, worst {err_naive.max():6.1f} px")
print(f"2 with states : COAST frames {n_coast} (from frame {first_coast}), locked again at frame {back}, final state {states[-1]}, error at the end {err[-1]:.1f} px, worst {err.max():.1f} px")
the log is fully hidden in frames 58 to 69 (12 frames = 0.40 s at 30 fps)
1 no loss handling : error at the end 115.8 px, worst 115.8 px
2 with states : COAST frames 23 (from frame 53), locked again at frame 76, final state TRACK, error at the end 0.5 px, worst 8.9 px
The log is fully hidden in frames 58 to 69 (12 frames, or 0.40 s) and partly hidden for several frames before and after that. Tracker 1 locks onto the bridge deck and never returns, ending 115.8 pixels off. Tracker 2 enters COAST at frame 53, when the log starts to be hidden, stays there for 23 frames, and locks on again at frame 76, when almost the whole log is visible. Its error at the end is 0.5 pixel, and the worst error on the way is 8.9 pixels, from the start of the occlusion, when the model still half trusted the image. The design lesson is that the velocity used for prediction must not be updated by partly hidden frames, which score low; otherwise the prediction during COAST gets worse with every frame.
Scale and the uncertainty of a measurement
Pixels must be converted to millimetres with a scale. The first way is from the geometry, , where is the distance to the surface, the pixel size and the focal length (used already in UAT 455 and UAT 451). The second is from a reference target, for example a 200 mm bar laid on the panel and measured in pixels in the image. The first depends on , which in the field can be uncertain by 5% or more. The second measures the scale at the real surface directly, but is valid only for the plane on which the target lies.
A complete measurement result always has two parts, the value and its uncertainty. The GUM (JCGM 100) gives each source a standard uncertainty and combines them by root sum of squares, (when the sources are independent). A Type B source known only by its bounds is given a uniform distribution, so , and the expanded uncertainty is reported with (about 95% confidence). Take care with a bias whose direction is known (for example a tilted surface makes lengths shorter): correct the value first, and then enter the remainder as uncertainty.
Example 3 The length of a crack with an uncertainty budget
The crack camera (sensor 13.2 mm wide, 5,472 pixels, a 50 mm lens, 6.0 m from the surface with an uncertainty of 0.3 m) traces a crack along its centreline as 3,410 pixels (uncertainty 1.5 pixels). A 200 mm reference bar (standard uncertainty 0.2 mm) measures 690.4 pixels, both ends being uncertain by ±0.5 pixel, and the panel is tilted from the image plane by no more than 8° in an unknown direction (all assumed). Compute the GSD both ways, the length with its U, and cross-check with 200,000 random trials.
import numpy as np
PITCH, F = 13.2e-3 / 5472, 0.050 # pixel pitch (m) and focal length (m) of the crack camera
D, D_U = 6.00, 0.30 # distance to the lining (m) and its uncertainty (assumed)
gsd_geo = D * PITCH / F * 1000 # mm per pixel from the geometry
print(f"GSD from geometry {gsd_geo:.4f} mm/px, with distance uncertainty {100 * D_U / D:.1f}% -> +-{gsd_geo * D_U / D:.4f} mm/px")
BAR, BAR_U = 200.0, 0.2 # a 200 mm reference bar laid on the lining (standard uncertainty 0.2 mm)
bar_px = 690.4 # bar length measured in the image (px) (assumed)
u_bar_px = np.hypot(0.5, 0.5) / np.sqrt(3) # both ends may be off by +-0.5 px (uniform distribution)
gsd_fid = BAR / bar_px
print(f"GSD from the bar {gsd_fid:.4f} mm/px, relative uncertainty {100 * np.hypot(BAR_U / BAR, u_bar_px / bar_px):.2f}%")
N, U_N = 3410.0, 1.5 # crack length traced along the centreline (px) and its uncertainty (assumed)
TILT = np.radians(8.0) # the lining is tilted 8 degrees from the image plane (assumed)
tilt_half = 1 / np.cos(TILT) - 1 # largest effect of the tilt on a length along the tilt direction (direction unknown, so between 0 and this value)
comp = {
"scale from the bar": np.hypot(BAR_U / BAR, u_bar_px / bar_px),
"tracing the crack": U_N / N,
"tilt of the plane": tilt_half / (2 * np.sqrt(3)), # correct by half the bound, then the half-width is tilt_half / 2 (uniform distribution)
}
L_raw = N * gsd_fid
L = L_raw * (1 + tilt_half / 2)
u_rel = np.sqrt(sum(v ** 2 for v in comp.values())) # root sum of squares (GUM)
print(f"L = {N:.0f} px x {gsd_fid:.4f} = {L_raw:.1f} mm, corrected for half of the tilt bound: {L:.1f} mm")
for k, v in comp.items():
print(f" {k:19s} {100 * v:5.2f}% ({100 * v ** 2 / u_rel ** 2:3.0f}% of the variance)")
print(f"combined {100 * u_rel:.2f}% = {L * u_rel:.1f} mm; expanded (k = 2) U = {2 * L * u_rel:.1f} mm")
rng = np.random.RandomState(1) # a Monte Carlo cross-check
M = 200000
bar_s = rng.normal(BAR, BAR_U, M)
bar_pix = bar_px + rng.uniform(-0.5, 0.5, M) + rng.uniform(-0.5, 0.5, M)
n_s = rng.normal(N, U_N, M)
tilt_s = 1 + rng.uniform(0, tilt_half, M) # the tilt factor, uniform between 1 and 1.0098
Ls = n_s * bar_s / bar_pix * tilt_s
print(f"Monte Carlo: mean {Ls.mean():.1f} mm, standard deviation {Ls.std():.1f} mm, 95% interval {np.percentile(Ls, 2.5):.1f} to {np.percentile(Ls, 97.5):.1f} mm")
print(f"if the tilt were ignored the length could be low by up to {100 * tilt_half:.2f}% = {L_raw * tilt_half:.1f} mm")
GSD from geometry 0.2895 mm/px, with distance uncertainty 5.0% -> +-0.0145 mm/px
GSD from the bar 0.2897 mm/px, relative uncertainty 0.12%
L = 3410 px x 0.2897 = 987.8 mm, corrected for half of the tilt bound: 992.7 mm
scale from the bar 0.12% ( 14% of the variance)
tracing the crack 0.04% ( 2% of the variance)
tilt of the plane 0.28% ( 84% of the variance)
combined 0.31% = 3.1 mm; expanded (k = 2) U = 6.1 mm
Monte Carlo: mean 992.7 mm, standard deviation 3.1 mm, 95% interval 987.2 to 998.2 mm
if the tilt were ignored the length could be low by up to 0.98% = 9.7 mm
The GSD from geometry is 0.2895 mm per pixel but uncertain by ±0.0145 (5%), while the bar gives 0.2897 with a relative uncertainty of only 0.12%. The crack length of 3,410 pixels is 987.8 mm before any correction for tilt. A tilt of 8° can shorten a length along the tilt direction by at most . Because the direction is unknown, the value is corrected by half of the bound (giving 992.7 mm) and the remainder is treated as a uniform distribution. The relative uncertainty comes from the bar at 0.12%, the tracing at 0.04% and the tilt at 0.28%, so the tilt is 84% of the total variance. The combined uncertainty is 0.31%, or 3.1 mm, and U at k = 2 is 6.1 mm. The random trials give a mean of 992.7 mm, a standard deviation of 3.1 mm and a 95% interval from 987.2 to 998.2 mm, agreeing with the GUM method. If the tilt were ignored the length could be low by up to 9.7 mm, more than U. That is the lesson that a bias nobody accounted for is often larger than the noise. Keeping the gimbal angle square to the surface, or using a homography from four targets (UAT 307, module 2), reduces it.
Measuring crack width near the resolution limit
The image of a crack through a lens is not a sharp-edged line but is blurred by the point spread function of the system. There are two main ways to measure the width. The first is the full width at half maximum (FWHM), finding where the cross-section crosses half of the depth of the crack, with linear interpolation between pixels to get a sub-pixel value. The second is counting the pixels darker than the midpoint between the background and the darkest pixel, which gives integers only. The inspection method in the knowledge base sets the rule that a crack should be at least 3 pixels wide in the image, and recent research finds very large uncertainty for cracks represented by only a few pixels (Lee et al., 2026).
Example 4 Measured width against true width
Synthetic cross-sections of cracks 0.3, 0.6, 1.0, 1.5, 2.0 and 3.0 mm wide at a GSD of 0.289 mm per pixel (1.0 to 10.4 pixels), integrating the light in each pixel, blurring with a blur of 0.8 pixel and adding noise. Each width is measured 300 times with the FWHM, with pixel counting, and with the FWHM after the blur of the system is removed in quadrature, the blur having been measured first on one very thin line.
import numpy as np
GSD = 0.289 # mm per pixel
PSF = 0.8 # lens blur (standard deviation, px) (assumed)
rng = np.random.RandomState(2)
x = np.arange(41)
k = np.exp(-0.5 * (np.arange(-5, 6) / PSF) ** 2); k /= k.sum()
def profile(width_px, centre): # a cross-section: light integrated per pixel, then blurred, plus noise
lo, hi = centre - width_px / 2, centre + width_px / 2
cover = np.clip(np.minimum(x + 0.5, hi) - np.maximum(x - 0.5, lo), 0, 1)
p = 150 - 80 * cover
p = np.convolve(np.pad(p, 5, mode="edge"), k, mode="valid")
return p + rng.normal(0, 3, p.size)
def fwhm(p): # width at half depth, with linear interpolation between pixels
base = np.median(p)
d = base - p
half = d.max() / 2
i = int(np.argmax(d))
l = i
while l > 0 and d[l] > half: l -= 1
r = i
while r < len(p) - 1 and d[r] > half: r += 1
xl = l + (half - d[l]) / (d[l + 1] - d[l])
xr = r - 1 + (d[r - 1] - half) / (d[r - 1] - d[r])
return xr - xl
def count_px(p): # count pixels darker than the midpoint between the background and the darkest pixel
base = np.median(p)
d = base - p
return int((d > d.max() / 2).sum())
psf_fwhm = np.mean([fwhm(profile(0.05, 20.0 + rng.rand())) for _ in range(200)]) # width measured on a hairline = blur of the system
print(f"hairline measured as {psf_fwhm:.2f} px = {psf_fwhm * GSD:.2f} mm (the blur of the system)")
print("true width FWHM (mean +- sd) pixel count corrected FWHM")
for w_mm in (0.3, 0.6, 1.0, 1.5, 2.0, 3.0):
w = w_mm / GSD
f = np.array([fwhm(profile(w, 20.0 + rng.rand())) for _ in range(300)]) * GSD
c = np.array([count_px(profile(w, 20.0 + rng.rand())) for _ in range(300)]) * GSD
corr = np.sqrt(np.maximum(f ** 2 - (psf_fwhm * GSD) ** 2, 0)) # remove the blur in quadrature
print(f"{w_mm:4.1f} mm = {w:4.1f} px {f.mean():5.2f} +- {f.std():4.2f} mm {c.mean():5.2f} +- {c.std():4.2f} mm {corr.mean():5.2f} +- {corr.std():4.2f} mm")
hairline measured as 1.14 px = 0.33 mm (the blur of the system)
true width FWHM (mean +- sd) pixel count corrected FWHM
0.3 mm = 1.0 px 0.63 +- 0.09 mm 0.59 +- 0.13 mm 0.53 +- 0.10 mm
0.6 mm = 2.1 px 0.76 +- 0.05 mm 0.72 +- 0.14 mm 0.68 +- 0.05 mm
1.0 mm = 3.5 px 1.03 +- 0.05 mm 1.02 +- 0.14 mm 0.97 +- 0.05 mm
1.5 mm = 5.2 px 1.48 +- 0.04 mm 1.48 +- 0.10 mm 1.45 +- 0.04 mm
2.0 mm = 6.9 px 1.97 +- 0.04 mm 1.97 +- 0.12 mm 1.94 +- 0.04 mm
3.0 mm = 10.4 px 2.95 +- 0.04 mm 2.96 +- 0.13 mm 2.93 +- 0.04 mm
A very thin line is measured as 1.14 pixels (0.33 mm), which is the blur of the system itself, so a crack narrower than this cannot be measured correctly. A true width of 0.3 mm (1.0 pixel) is measured as 0.63 mm by the FWHM and 0.59 mm by pixel counting, about twice the truth. A crack of 0.6 mm (2.1 pixels) is measured as 0.76 and 0.72 mm. At 1.0 mm (3.5 pixels) the results approach the truth: the FWHM gives 1.03 ± 0.05 mm and pixel counting 1.02 ± 0.14 mm, and wider cracks follow the truth to within 0.05 mm for the FWHM. Pixel counting has a spread of ±0.10 to 0.14 mm, close to the pixel size (0.289 mm), because it gives integers only. Removing the blur helps a little at 0.3 and 0.6 mm but is still not right (0.53 and 0.68 mm), and reads slightly low at 1.0 mm (0.97 mm). The practical conclusion is to report widths only for cracks at least 3 pixels wide (0.87 mm at this GSD) and to report narrower ones as “narrower than the measurement limit”. To measure a 0.3 mm crack the GSD must be at least three times smaller (fly lower or use a longer lens).
Depth and the step between panels from two camera stations
The step between adjacent panels (faulting) indicates settlement, but it cannot be measured from one image; it needs two viewpoints. UAT 307 taught from the difference of position in the images (disparity). In practice you usually have the projection matrices and of each station, and the function cv2.triangulatePoints finds the 3D position of a point seen in both images (OpenCV calib3d module). The depth error of one point is , where is the error of the disparity and is the baseline between the two stations (Hartley & Zisserman, 2004). It grows with the square of the distance and is inversely proportional to the baseline. The step is the difference between the mean depths of the two panels. Averaging many points per panel reduces the random error, and any error common to both panels cancels in the difference. A nadir image of a surface that is not square to the camera axis, or of a surface with relief, has a scale that is not constant, as the photogrammetry textbooks explain (Wolf et al., 2014); the next example therefore assumes that the panels are square to the camera axis.
Example 5 A 3 mm step from two camera stations
A 50 mm camera (focal length 20,729 pixels), 6.0 m from the panels, takes pictures from two stations a distance B apart along the canal. Two adjacent panels differ in level by 3 mm, with 100 matched points per panel and a matching error of 0.5 pixel per image. Each B is repeated 200 times and the results compared. Finally the second camera is rotated by a wrong 0.01° without anyone knowing.
import cv2
import numpy as np
F = 0.050 / (13.2e-3 / 5472) # focal length in pixels (the 50 mm crack camera)
K = np.array([[F, 0, 2736.0], [0, F, 1824.0], [0, 0, 1.0]])
Z0, STEP = 6.0, 0.003 # distance to the panel (m) and a 3 mm step between neighbouring panels (assumed)
def rot_y(deg):
c, s = np.cos(np.radians(deg)), np.sin(np.radians(deg))
return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
def project(X, R, C): # X: 3xN world points
p = K @ (R @ (X - C.reshape(3, 1)))
return p[:2] / p[2]
def trial(B, sigma_px, rng, rot_err_deg=0.0, n=100):
x = np.r_[rng.uniform(-0.8, -0.05, n), rng.uniform(0.05, 0.8, n)] # points on panel A (left) and panel B (right)
y = rng.uniform(-0.5, 0.5, 2 * n)
z = np.r_[np.full(n, Z0), np.full(n, Z0 + STEP)]
X = np.vstack([x, y, z])
C1, C2 = np.array([-B / 2, 0, 0.0]), np.array([B / 2, 0, 0.0]) # two camera stations B apart along the canal
R1, R2 = np.eye(3), rot_y(rot_err_deg) # the second camera is rotated slightly wrong
u1 = project(X, R1, C1) + rng.normal(0, sigma_px, (2, 2 * n))
u2 = project(X, R2, C2) + rng.normal(0, sigma_px, (2, 2 * n))
P1 = K @ np.hstack([np.eye(3), -C1.reshape(3, 1)]) # projection matrices used (the pose error is unknown)
P2 = K @ np.hstack([np.eye(3), -C2.reshape(3, 1)])
Xh = cv2.triangulatePoints(P1, P2, u1.astype(np.float64), u2.astype(np.float64))
Z = Xh[2] / Xh[3]
return Z[:n].mean(), Z[n:].mean(), Z - z
rng = np.random.RandomState(5)
print("baseline depth error per point step estimate (mean +- sd) trials within +-0.5 mm of the true 3 mm")
for B in (0.3, 0.75, 1.5, 3.0):
res = [trial(B, 0.5, rng) for _ in range(200)] # a matching error of 0.5 px
step = np.array([b - a for a, b, _ in res]) * 1000
perpoint = np.std(np.concatenate([e for _, _, e in res])) * 1000
print(f"{B:6.2f} m {perpoint:15.2f} mm {step.mean():17.2f} +- {step.std():4.2f} mm {100 * np.mean(np.abs(step - 3.0) < 0.5):28.0f}%")
res = [trial(1.5, 0.5, rng, rot_err_deg=0.01) for _ in range(200)]
za = np.mean([a for a, _, _ in res]); step = np.array([b - a for a, b, _ in res]) * 1000
print(f"camera 2 rotated wrongly by 0.01 deg: panel A depth off by {(za - Z0) * 1000:.1f} mm, but the step is {step.mean():.2f} +- {step.std():.2f} mm")
print(f"theory for one point: dZ = Z^2 * sigma / (f * B) = {Z0 ** 2 * 0.5 * np.sqrt(2) / (F * 1.5) * 1000:.2f} mm at B = 1.5 m")
baseline depth error per point step estimate (mean +- sd) trials within +-0.5 mm of the true 3 mm
0.30 m 4.10 mm 2.99 +- 0.56 mm 63%
0.75 m 1.64 mm 3.03 +- 0.22 mm 98%
1.50 m 0.82 mm 2.99 +- 0.11 mm 100%
3.00 m 0.41 mm 3.00 +- 0.06 mm 100%
camera 2 rotated wrongly by 0.01 deg: panel A depth off by 4.4 mm, but the step is 2.85 +- 0.12 mm
theory for one point: dZ = Z^2 * sigma / (f * B) = 0.82 mm at B = 1.5 m
At a baseline of 0.30 m the depth error per point is 4.10 mm and the 3 mm step is estimated as 2.99 ± 0.56 mm, with only 63% of the trials within ±0.5 mm. Raising the baseline to 0.75 m cuts the error per point to 1.64 mm, the step is 3.03 ± 0.22 mm and 98% are within the limit. At 1.50 m the error per point is 0.82 mm, matching the formula ( gives 0.82 mm), the step is 2.99 ± 0.11 mm and 100% are within the limit, and at 3.00 m it is ±0.06 mm. The key point is the last line. A wrong rotation of only 0.01° in the second camera makes the absolute depth of panel A wrong by 4.4 mm, more than the step to be measured, but the step is still 2.85 ± 0.12 mm, because the common error cancels in the difference, unlike the absolute depth, which does not cancel. The conclusion is to design the measurement as a difference between two areas of the same image when you can, and to choose the baseline so that the error per point after averaging is at least twice as small as the required resolution.
Module lab
Lab: track and measure with uncertainty
- Film a short video of a floating or slow-moving object whose true speed is known (for example a foam block on a conveyor or a radio-controlled boat) from a hovering camera or a tripod. Track the foam or pattern with LK and compare the speed obtained with the true one, after removing the motion of the background.
- Try frames 1, 4 and 16 apart and compare the number of points that pass the backward check with and without a pyramid.
- Write a tracker with TRACK and COAST states, then hide the object with a sheet of paper for 5 to 20 frames. Report the frame where it was lost and the frame where it was found again.
- Lay a reference bar of known length on a test surface, find the GSD by both methods, and compute the uncertainty budget of one line length with U at k = 2.
- Print a test sheet with lines 0.3 to 3 mm wide, photograph it at a known GSD, measure the widths with the FWHM and by pixel counting, and find the smallest width for which the result can still be trusted.
- Place two plates 3 mm apart in level, photograph them from two stations, estimate the step by triangulation, and compare with the value measured by a contact instrument.
Common mistakes
Watch out
- Forgetting to remove the motion of the background. When the drone drifts slightly, the measured speed of the object is wrong.
- Using plain LK for large motion or frames far apart, without a pyramid and the backward check.
- A tracker that always accepts the best match has no lost state, so it keeps tracking the background.
- Updating the tracker’s velocity with partly hidden frames.
- Reporting a number without its uncertainty, or folding a bias into the noise instead of correcting the value first.
- Reporting the width of a crack narrower than 3 pixels. The result always reads too high because of blur.
- Using absolute depth from two stations to find a small step, when a difference within one image is more accurate.
Summary
- LK assumes constant brightness and neighbouring pixels moving alike. Use a pyramid for large motion and the backward check to drop wrong points. The speed must have the background motion removed.
- A tracker needs TRACK and COAST states with a re-search, and should update its velocity only when it is sure.
- Scale from a reference target is more accurate than from the geometry when the distance is uncertain, and a value must be reported with its uncertainty following the GUM, with biases corrected first.
- A crack narrower than 3 pixels cannot be measured; the result reads too high because of blur.
- A step can be measured from two camera stations when the baseline is long enough, and more accurately as a difference within the same image, because the common error cancels.
Self-check questions
- A crack 1.0 mm wide must be at least 3 pixels wide in the image. The camera has a sensor 13.2 mm wide with 5,472 pixels and a 50 mm lens. How far from the surface may it fly at most?
- In the image the water moves 1.8 pixels per frame after the bank motion is removed, the GSD is 0.025 m and the camera runs at 25 fps. What is the surface speed?
- A length has a relative uncertainty from the scale of 0.2% and from the tracing of 0.3% (independent). For a length of 2.00 m, what are the combined standard uncertainty and U at k = 2?
- A 50 mm camera (20,729 pixels) is 6.0 m from the surface, the baseline is 1.5 m and the matching error is 0.5 pixel per image. Roughly what is the depth error of one point?
- A tracker predicts a velocity of 3 pixels per frame, but the truth is 4. After a 20-frame occlusion, how far off is the predicted position, and how wide must the search radius be at least?
Answers
- The GSD must be at most mm. The pixel size is µm. From , m.
- m/s.
- of 2.00 m, which is 7.2 mm, and mm.
- mm.
- The accumulated error is pixels, so the search radius must be at least 20 pixels around the predicted position (and should allow more, since the velocity may change).
Key formulas
| Optical flow equation | |
| Forward-backward error | |
| Ground sampling distance (GSD) | |
| Combined standard uncertainty | |
| Depth error from two camera stations |
Key references
- Szeliski, R. (2022). Computer vision: Algorithms and applications (2nd ed.). Springer. link
- OpenCV. OpenCV documentation. link
- Lucas, B. D., & Kanade, T. (1981). An iterative image registration technique with an application to stereo vision. In Proceedings of the 7th International Joint Conference on Artificial Intelligence (Vol. 2, pp. 674–679). link
- Shi, J., & Tomasi, C. (1994). Good features to track. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (pp. 593–600). IEEE. link
- Bouguet, J.-Y. (2001). Pyramidal implementation of the Lucas Kanade feature tracker: Description of the algorithm. Intel Corporation, Microprocessor Research Labs. link
- OpenCV. Optical flow. OpenCV 4.x tutorials (video module). link
- Kalal, Z., Mikolajczyk, K., & Matas, J. (2010). Forward-backward error: Automatic detection of tracking failures. In 2010 20th International Conference on Pattern Recognition (pp. 2756–2759). IEEE. link
- Henriques, J. F., Caseiro, R., Martins, P., & Batista, J. (2015). High-speed tracking with kernelized correlation filters. IEEE Transactions on Pattern Analysis and Machine Intelligence, 37(3), 583–596. link
- OpenCV. Tracking API (TrackerKCF, TrackerCSRT). OpenCV 4.x documentation. link
- JCGM. (2008). Evaluation of measurement data — Guide to the expression of uncertainty in measurement (JCGM 100:2008). BIPM. link
- Lee, S. B., Lee, D. H., & Kim, J. (2026). An exploratory study on imaging resolution, operational parameters, and measurement uncertainty in UAV-based crack inspection. Sensors, 26(3), 1031. link
- Hartley, R., & Zisserman, A. (2004). Multiple view geometry in computer vision (2nd ed.). Cambridge University Press. link
- OpenCV. Camera calibration and 3D reconstruction (calib3d module): solvePnP, triangulatePoints. OpenCV 4.x documentation. link
- Wolf, P. R., DeWitt, B. A., & Wilkinson, B. E. (2014). Elements of photogrammetry with applications in GIS (4th ed.). McGraw-Hill Education. 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