Edges, features and image matching
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 four stages of the Canny edge detector and set its two thresholds from an area that holds no object of interest
- Use the Hough transform to find the tilt of the canal and the spacing of the joints, and convert them to metres with the GSD
- Register two flights with ORB or SIFT, the ratio test and RANSAC, and measure the corner error of the result
- Estimate the accumulated drift of a chained mosaic and design anchoring with targets of known position
- Detect change between two flights by correcting brightness and tolerating a small shift before taking the difference
Why this matters
The canal was flown twice, before and after the flood season. The irrigation office wants to know which cracks have grown and which panels have changed. But the images of two flights never line up exactly: the camera angle, the position and the light all differ. Subtract the images directly and the result is full of false changes. The first step is image registration, finding the transformation that makes the second flight overlay the first, and only then comparing. In the same way, flying along the canal needs the tilt of the banks, and counting panels needs the spacing of the joints. All of this starts from edges and lines in the image.
UAT 307 has already taught edges with Sobel, Harris corners, descriptors, the ratio test and homography. This module does not repeat them. It builds on them with the tools that applications really use: the Canny edge detector, the Hough transform for lines, the ORB and SIFT feature detectors, mosaicking and change detection, with the emphasis on when each one breaks and how to measure whether it is good enough.
The Canny edge detector
Canny (1986) designed an edge detector for good detection, good localisation and a single response to each edge. According to the OpenCV tutorial the algorithm has four stages. First, noise is reduced with a 5 × 5 Gaussian filter. Second, the gradient is found with Sobel kernels, giving the strength and direction of the edge. Third, non-maximum suppression keeps only the pixels that are local maxima along the gradient direction, giving thin one-pixel edges. Fourth comes hysteresis, which uses two thresholds: an edge whose gradient is above the high threshold is certainly an edge, one below the low threshold is dropped, and one in between is kept only if it connects to a certain edge. The OpenCV Canny detector tutorial recommends a high-to-low ratio between 2:1 and 3:1. Its sample code calls blur() before Canny(), which is a practice worth following, so always smooth the image yourself first.
The real problem is how to set the two thresholds so that a crack is not broken up while the concrete texture does not become edges. A repeatable method is to measure in an area known to be free of cracks: set the high threshold so that only 0.2% of that area’s pixels exceed it, and the low threshold at half of it.
Example 1 Hysteresis thresholds and a crack that fades
A synthetic 320 × 240 pixel concrete image has a crack 3 pixels wide running across it, and the middle of the crack fades to about 40% of the contrast of its start (assumed). The high threshold is chosen from the lower part of the image, which has no crack. Three settings are compared, measuring the fraction of the crack covered, the number of gaps along the crack and the longest gap, and the edge pixels that are not the crack, before and after removing edge pieces shorter than 40 pixels.
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)
img = concrete(240, 320, 4, 0.4).astype(np.float32)
crack = np.zeros((240, 320), np.uint8)
path = np.array([(20, 60), (90, 85), (150, 110), (210, 140), (300, 175)], np.int32)
cv2.polylines(crack, [path], False, 1, 1) # centreline of the crack (truth)
dark = cv2.GaussianBlur(cv2.dilate(crack, np.ones((3, 3), np.uint8)).astype(np.float32), (0, 0), 0.8)
fade = np.interp(np.arange(320), [0, 100, 160, 240, 319], [1.0, 0.9, 0.4, 0.36, 0.5]) # the middle of the crack fades
img = img - 70 * dark * fade[None, :]
img = np.clip(img + np.random.RandomState(9).normal(0, 3, img.shape), 0, 255).astype(np.uint8)
blur = cv2.GaussianBlur(img, (5, 5), 1.4)
gx, gy = cv2.Sobel(blur, cv2.CV_32F, 1, 0, ksize=3), cv2.Sobel(blur, cv2.CV_32F, 0, 1, ksize=3)
mag = np.hypot(gx, gy)
t_high = float(np.percentile(mag[170:235, 5:315], 99.8)) # high threshold from a crack-free area (0.2% of pixels exceed it)
t_low = 0.5 * t_high # ratio 2:1
print(f"gradient: high threshold {t_high:.0f}, low threshold {t_low:.0f}")
def drop_small(e, min_px): # remove edge pieces shorter than min_px
n, lab, st, _ = cv2.connectedComponentsWithStats(e.astype(np.uint8), connectivity=8)
keep = np.zeros(n, bool)
keep[1:] = st[1:, cv2.CC_STAT_AREA] >= min_px
return keep[lab]
near = cv2.distanceTransform(1 - cv2.dilate(crack, np.ones((3, 3), np.uint8)), cv2.DIST_L2, 3) <= 4
ys = np.argwhere(crack > 0)
ys = ys[np.argsort(ys[:, 1])] # centreline points ordered along x
print("setting covered gaps longest gap stray pixels stray after dropping pieces < 40 px")
for name, lo, hi in (("one threshold", t_high, t_high), ("hysteresis", t_low, t_high), ("thresholds too low", 0.4 * t_low, 0.4 * t_high)):
e = cv2.Canny(blur, lo, hi, L2gradient=True) > 0
hit = cv2.dilate(e.astype(np.uint8), np.ones((5, 5), np.uint8))[ys[:, 0], ys[:, 1]] > 0
runs = np.diff(np.r_[0, (~hit).astype(int), 0])
starts, ends = np.where(runs == 1)[0], np.where(runs == -1)[0]
longest = int((ends - starts).max()) if starts.size else 0
stray = int((e & ~near).sum())
stray_after = int((drop_small(e, 40) & ~near).sum())
print(f"{name:18s} {100 * hit.mean():7.1f}% {starts.size:5d} {longest:9d} px {stray:12d} {stray_after:20d}")
gradient: high threshold 74, low threshold 37
setting covered gaps longest gap stray pixels stray after dropping pieces < 40 px
one threshold 73.3% 9 13 px 140 0
hysteresis 100.0% 0 0 px 1250 403
thresholds too low 100.0% 0 0 px 19997 15416
A single threshold (high equal to low) covers 73.3% of the crack, with 9 gaps and a longest gap of 13 pixels, because where the crack fades the gradient falls below the threshold. Hysteresis with thresholds 74 and 37 covers 100% of the crack with no gaps, because the faint part connects to the stronger part. The price is that stray edge pixels rise from 140 to 1,250, which removing pieces shorter than 40 pixels cuts to 403. Thresholds set too low by a factor of 2.5 also cover the whole crack but let in 19,997 stray pixels (26% of the image), which is useless. The conclusion is that hysteresis trades continuity of the crack against stray edges, and a filter on edge-piece length must always follow.
The Hough transform for straight lines
Every straight line can be written as , where is the perpendicular distance from the origin to the line and is the angle of that perpendicular. In OpenCV’s convention a vertical line has and a horizontal line has . In the Hough transform (Duda & Hart, 1972) each edge pixel votes for every pair that a line through it could have. A real line with many pixels collects a high count in the accumulator. The function cv2.HoughLines returns the pairs whose count exceeds a threshold and takes an edge image as input. cv2.HoughLinesP uses the progressive probabilistic method (Matas et al., 2000) and returns the end points of line segments directly, with parameters for the minimum length and the largest gap that may be bridged (OpenCV Hough line transform tutorial). The result of HoughLinesP has shape (N, 1, 4) in the OpenCV 4.x that the documentation shows, and (N, 4) in the 5.0 release used for testing, so the code uses reshape(-1, 4) to work on both.
In navigation, an image from the video camera at 30 m height (GSD 40 mm after shrinking the image to 640 × 480, assumed) has two useful groups of lines. The lines along the canal are the bank edges and give the tilt of the route and the position of the canal centre relative to the image centre. The lines across are the panel joints and give the spacing, which times the GSD is in metres and lets panels be counted (used again in module 15).
Example 2 Canal tilt and joint spacing from an overhead image
A synthetic 640 × 480 pixel image at a GSD of 0.040 m. The two banks are 12.0 m apart and tilted 3.0° from the vertical image axis, and the canal centre is shifted 18 pixels from the image centre. Transverse joints are spaced every 5.0 m (125 pixels), and noise is added. Canny is followed by a Hough transform with an angle step of 0.25°; the lines are split by angle into nearly vertical and nearly horizontal groups, and the duplicate lines of each bank are averaged.
import cv2
import numpy as np
GSD = 0.040 # m per pixel at 30 m height (assumed)
W, H = 640, 480
TRUE_ANGLE, TRUE_OFFSET_PX, SPACING_PX = 3.0, 18.0, 125 # degrees, pixels, joint spacing (5 m / 0.04)
rng = np.random.RandomState(2)
img = np.full((H, W), 150, np.uint8)
t = np.tan(np.radians(TRUE_ANGLE))
cx0 = W / 2 + TRUE_OFFSET_PX # canal centre on the bottom image row
for side in (-150, 150): # the two bank edges, 12 m apart
x_bottom = cx0 + side
cv2.line(img, (int(round(x_bottom + t * H)), 0), (int(round(x_bottom)), H - 1), 60, 4)
ang = np.radians(TRUE_ANGLE)
for k in range(-6, 12): # transverse joints every 125 px
y0 = 20 + k * SPACING_PX
p1 = (int(cx0 - 220 * np.cos(ang)), int(y0 + 220 * np.sin(ang)))
p2 = (int(cx0 + 220 * np.cos(ang)), int(y0 - 220 * np.sin(ang)))
cv2.line(img, p1, p2, 105, 3)
img = np.clip(img + rng.normal(0, 8, img.shape), 0, 255).astype(np.uint8)
edges = cv2.Canny(cv2.GaussianBlur(img, (5, 5), 1.4), 40, 100)
lines = cv2.HoughLines(edges, 1, np.pi / 720, 160).reshape(-1, 2) # (rho, theta), angle step 0.25 degrees
deg = np.degrees(lines[:, 1])
along = lines[(deg < 20) | (deg > 160)] # nearly vertical = bank edges
cross = lines[(deg > 70) & (deg < 110)] # nearly horizontal = joints
print(f"{len(lines)} lines found: {len(along)} along the canal, {len(cross)} across")
th = np.where(along[:, 1] > np.pi / 2, along[:, 1] - np.pi, along[:, 1])
heading = np.degrees(th.mean()) # tilt of the canal against the image vertical
x_at_bottom = [] # x of each bank line on the bottom row
for rho, theta in along:
x_at_bottom.append((rho - (H - 1) * np.sin(theta)) / np.cos(theta))
x_at_bottom = np.array(x_at_bottom)
mid = (x_at_bottom.min() + x_at_bottom.max()) / 2
left, right = x_at_bottom[x_at_bottom < mid].mean(), x_at_bottom[x_at_bottom >= mid].mean() # average the duplicate lines of each bank
print(f"canal tilt {heading:.2f} deg (true {TRUE_ANGLE}), width {(right - left) * GSD:.2f} m (true 12.00)")
print(f"centre offset {(left + right) / 2 - W / 2:.1f} px = {((left + right) / 2 - W / 2) * GSD:.2f} m (true {TRUE_OFFSET_PX:.0f} px)")
y_c = np.sort([(rho - 320 * np.cos(theta)) / np.sin(theta) for rho, theta in cross]) # y of each joint at the image centre
runs = np.split(y_c, np.where(np.diff(y_c) > 20)[0] + 1) # merge near-duplicate lines
centres = np.array([r.mean() for r in runs])
print(f"{len(centres)} joints, spacing {np.median(np.diff(centres)):.1f} px = {np.median(np.diff(centres)) * GSD:.2f} m (true 5.00 m)")
segs = cv2.HoughLinesP(edges, 1, np.pi / 180, 60, minLineLength=100, maxLineGap=10).reshape(-1, 4) # x1, y1, x2, y2 (reshape because the result shape differs between OpenCV versions)
length = np.hypot(segs[:, 2] - segs[:, 0], segs[:, 3] - segs[:, 1])
print(f"HoughLinesP returns {len(segs)} segments with end points, longest {length.max():.0f} px")
36 lines found: 12 along the canal, 24 across
canal tilt 3.00 deg (true 3.0), width 12.02 m (true 12.00)
centre offset 17.9 px = 0.72 m (true 18 px)
4 joints, spacing 125.0 px = 5.00 m (true 5.00 m)
HoughLinesP returns 21 segments with end points, longest 480 px
The Hough transform finds 36 lines, 12 along the canal and 24 across. That is more than the real number of lines, because one line several pixels thick gives several nearby pairs, so overlapping groups must be averaged before use. The result is a tilt of 3.00° (true 3.0), a width of 12.02 m (true 12.00), a centre offset of 17.9 pixels or 0.72 m (true 18 pixels) and joints 5.00 m apart, matching the truth in every value. HoughLinesP returns 21 segments with a longest of 480 pixels, ready to use with their end points, but a broken line gives several segments. Real images contain grass lines and shadows, so always filter by angle and length before trusting a line.
Features, descriptors and matching
UAT 307 covered the three steps of matching: detect points, describe them, and match with the ratio test proposed by Lowe (2004). In an application you must choose which descriptor to use. Two widely used descriptors in the main OpenCV build (which also includes AKAZE, BRISK and KAZE) are SIFT and ORB. SIFT (Lowe, 2004) tolerates changes of scale and rotation and gives a vector of 128 real numbers compared by L2 distance; it is accurate but slower. ORB (Rublee et al., 2011) joins FAST to BRIEF, finds the orientation of a point from the intensity centroid, and gives a binary descriptor compared by Hamming distance. It is fast and free of patents, as the OpenCV ORB tutorial says. Both work with BFMatcher and knnMatch(k=2), a binary descriptor with NORM_HAMMING and a real-valued one with NORM_L2 (OpenCV feature matching tutorial).
Matches that pass the ratio test still contain wrong pairs, so they go to cv2.findHomography with RANSAC (Fischler & Bolles, 1981). RANSAC repeatedly picks the smallest set of pairs that can define a homography, builds it, and counts the pairs that agree within a distance (here 3 pixels). The model with the most agreeing pairs (inliers) is kept. What you must always report is the number of inliers and the error of the result, not just that a matrix came out.
Example 3 Registering two flights, and the repeating-pattern case
Flight 2 is made from flight 1 by a 4° rotation, a scale of 1.03, a shift of (22, −14) pixels, a slight change of viewpoint, 12% more brightness and noise (assumed). Because the true transformation is known, the mean corner error of the four image corners can be measured. The test is then repeated on a “repeating pattern”, a surface where every panel looks exactly the same, which can happen with panels cast in one mould and finished smooth.
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 register(a, b, kind):
# find H that maps image b coordinates onto image a
det = cv2.ORB_create(nfeatures=1500) if kind == "ORB" else cv2.SIFT_create(nfeatures=1500)
norm = cv2.NORM_HAMMING if kind == "ORB" else cv2.NORM_L2
ka, da = det.detectAndCompute(a, None)
kb, db = det.detectAndCompute(b, None)
if da is None or db is None or len(ka) < 2 or len(kb) < 2:
return None, (0, 0, 0, 0)
pairs = cv2.BFMatcher(norm).knnMatch(db, da, k=2)
good = [p[0] for p in pairs if len(p) == 2 and p[0].distance < 0.75 * p[1].distance] # ratio test
if len(good) < 4:
return None, (len(ka), len(kb), len(good), 0)
src = np.float32([kb[m.queryIdx].pt for m in good])
dst = np.float32([ka[m.trainIdx].pt for m in good])
H, inl = cv2.findHomography(src, dst, cv2.RANSAC, 3.0)
return H, (len(ka), len(kb), len(good), int(inl.sum()) if inl is not None else 0)
def corner_error(H, H_true, w, h): # mean error of the four image corners (px)
if H is None:
return float("nan")
c = np.float32([[0, 0], [w, 0], [w, h], [0, h]]).reshape(-1, 1, 2)
return float(np.linalg.norm(cv2.perspectiveTransform(c, H) - cv2.perspectiveTransform(c, H_true), axis=2).mean())
h, w = 360, 480
flight_a = concrete(h, w, 5) # flight 1
c, s = np.cos(np.radians(4.0)), np.sin(np.radians(4.0))
M = np.array([[1.03 * c, -1.03 * s, 22.0], [1.03 * s, 1.03 * c, -14.0], [2e-5, -1e-5, 1.0]]) # flight 2 sees the lining slightly differently
flight_b = cv2.warpPerspective(flight_a, M, (w, h), borderMode=cv2.BORDER_REFLECT)
flight_b = np.clip(flight_b.astype(np.float32) * 1.12 - 6 + np.random.RandomState(1).normal(0, 3, (h, w)), 0, 255).astype(np.uint8)
H_true = np.linalg.inv(M) # from image 2 back to image 1
def show(scene, kind, a, b):
H, (na, nb, ng, ni) = register(a, b, kind)
err = corner_error(H, H_true, w, h)
err_text = "no homography" if np.isnan(err) else f"{err:.2f} px"
print(f"{scene:10s} {kind:5s} {na:5d} {nb:5d} {ng:10d} {ni:8d} {err_text}")
print("scene method kpA kpB ratio-test inliers corner error")
for kind in ("ORB", "SIFT"):
show("textured", kind, flight_a, flight_b)
tile = concrete(90, 120, 6) # concrete that repeats on every panel: all panels look identical
period_a = np.tile(tile, (4, 4))
period_b = cv2.warpPerspective(period_a, M, (w, h), borderMode=cv2.BORDER_REFLECT)
for kind in ("ORB", "SIFT"):
show("repeating", kind, period_a, period_b)
scene method kpA kpB ratio-test inliers corner error
textured ORB 1500 1500 801 781 0.18 px
textured SIFT 1501 1500 833 833 0.03 px
repeating ORB 1508 1500 177 33 9.27 px
repeating SIFT 1502 1500 0 0 no homography
On normal texture ORB passes 801 pairs through the ratio test, has 781 inliers and a corner error of 0.18 pixels, while SIFT has 833 pairs, 833 inliers and an error of 0.03 pixels. ORB is faster and wrong by only a fraction of a pixel, which is enough for this job. On the repeating pattern, however, ORB keeps 177 pairs through the ratio test but only 33 inliers (19%), and the corner error jumps to 9.27 pixels. SIFT keeps no pairs at all (no homography), because identical panels give descriptors so close that the ratio approaches 1 and everything is rejected. The ratio test is working correctly; the scene simply has no information that separates one panel from another. The remedy is information from outside the image, such as a GNSS position that restricts which panel to match, or targets that differ from panel to panel.
Mosaicking and accumulated drift
Once a homography is known for a pair of images, cv2.warpPerspective moves one image into the coordinates of the other, giving a larger image or mosaic. What is left is the visible seam when the two images differ in brightness. Brown and Lowe (2007) solved it with gain compensation and multi-band blending, and also adjusted the parameters of all images together (bundle adjustment) so that errors do not accumulate. The next example uses something simpler: it estimates a brightness gain from the overlap and weights the images by distance from the image border (feathering).
When images are chained along the whole canal, the error of each pair accumulates. If the random error per pair is and the systematic error per pair is (for example from imperfectly calibrated lens distortion), the error after pairs is . The systematic part grows linearly with and the random part with the square root. The remedy is to anchor the chain to targets of known position at intervals.
Example 4 A two-strip mosaic and the drift along the canal
A 900 pixel run of concrete is cut into two strips that overlap by 220 pixels, the second 10% brighter. They are registered with SIFT and joined in two ways, pasted directly, and feathered with a brightness correction, and the RMSE against the true surface is measured. The second part simulates a chain of 25,000 pairs (about 11.8 km at a frame spacing of 0.47 m) with a random error of 0.30 pixels and a systematic error of 0.05 pixels per pair, at a GSD of 0.289 mm.
import cv2
import numpy as np
big = concrete(300, 900, 8) # a long run of lining (used as the truth)
cv2.line(big, (450, 0), (450, 299), 70, 3) # one panel joint
strip1 = big[:, 0:560].copy()
strip2 = np.clip(big[:, 340:900].astype(np.float32) * 1.10 + np.random.RandomState(3).normal(0, 2, (300, 560)), 0, 255).astype(np.uint8) # strip 2 is 10% brighter, overlapping by 220 px
H, (_, _, n_good, n_inl) = register(strip1, strip2, "SIFT")
print(f"SIFT: {n_good} matches after the ratio test, {n_inl} inliers; shift of strip 2 = ({H[0, 2]:.2f}, {H[1, 2]:.2f}) px (true 340, 0)")
canvas = (300, 900)
w2 = cv2.warpPerspective(strip2, H, canvas[::-1]) # strip 2 in strip 1 coordinates
m2 = cv2.warpPerspective(np.full(strip2.shape, 255, np.uint8), H, canvas[::-1]) > 0
w1 = np.zeros(canvas, np.uint8); w1[:, :560] = strip1
m1 = np.zeros(canvas, bool); m1[:, :560] = True
both = m1 & m2
gain = np.median(w1[both].astype(float) / np.maximum(w2[both], 1)) # gain compensation from the overlap
d1 = cv2.distanceTransform(m1.astype(np.uint8), cv2.DIST_L2, 3)
d2 = cv2.distanceTransform(m2.astype(np.uint8), cv2.DIST_L2, 3)
wt = d1 / np.maximum(d1 + d2, 1e-6) # feather weights by distance to the border
mosaic = np.where(both, wt * w1 + (1 - wt) * w2 * gain, np.where(m1, w1, w2 * gain))
naive = np.where(m1, w1, w2) # pasted without correction
inside = np.zeros(canvas, bool); inside[:, 5:895] = True
print(f"gain estimated {gain:.3f} (true {1 / 1.10:.3f}); overlap {int(both[0].sum())} px wide")
for name, im in (("truth", big), ("pasted", naive), ("feathered + gain", mosaic)):
err = np.abs(im.astype(float) - big)[inside & (m1 | m2)]
seam = abs(im[:, 540:560].mean() - im[:, 560:580].mean()) # difference of mean brightness on each side of the seam
print(f"{name:17s}: RMSE against truth {np.sqrt((err ** 2).mean()):5.2f}, brightness step across the seam {seam:5.2f}")
FRAME_SPACING_M, GSD_MM = 0.47, 0.289 # along-track frame spacing (70% overlap) and the crack camera GSD
rng = np.random.RandomState(4)
steps = 25000 # chained pairs, about 11.8 km
e_rand = rng.normal(0, 0.30, steps) # random error of each pair (px)
e_bias = 0.05 # systematic error per pair (px), residual lens distortion
drift = np.cumsum(e_rand + e_bias)
print("pairs distance drift (px) drift (mm)")
for n in (10, 100, 1000, 25000):
print(f"{n:5d} {n * FRAME_SPACING_M:8.0f} m {drift[n - 1]:12.1f} {drift[n - 1] * GSD_MM:12.1f}")
K = 200 # anchor to a surveyed target every 200 pairs (~94 m)
anchored = np.concatenate([np.cumsum(e_rand[i:i + K] + e_bias) for i in range(0, steps, K)])
print(f"anchored every {K} pairs: worst drift {np.abs(anchored).max() * GSD_MM:.1f} mm")
SIFT: 489 matches after the ratio test, 486 inliers; shift of strip 2 = (340.02, 0.01) px (true 340, 0)
gain estimated 0.912 (true 0.909); overlap 220 px wide
truth : RMSE against truth 0.00, brightness step across the seam 2.44
pasted : RMSE against truth 9.10, brightness step across the seam 16.95
feathered + gain : RMSE against truth 1.36, brightness step across the seam 2.41
pairs distance drift (px) drift (mm)
10 5 m -0.3 -0.1
100 47 m 6.1 1.8
1000 470 m 65.5 18.9
25000 11750 m 1252.6 362.0
anchored every 200 pairs: worst drift 5.6 mm
Registration finds 486 inliers and shifts the second strip by 340.02 pixels (true 340). The estimated brightness gain of 0.912 is close to the true 0.909. Direct pasting gives an RMSE of 9.10 and a visible seam (a brightness step across the seam of 16.95, against 2.44 in the true surface), while feathering with the gain correction gives an RMSE of 1.36 and a step of 2.41, the same as the true surface. For the chain, the accumulated drift is only 0.1 mm at 10 pairs (5 m), but 18.9 mm at 1,000 pairs (470 m) and 362.0 mm at 25,000 pairs (11.75 km), mostly from the systematic error growing linearly. If the chain is anchored to a target of known position every 200 pairs (about 94 m), the drift never exceeds 5.6 mm.
Detecting change between two flights
This is the heart of the repeat inspection before and after the flood season. The basic steps of change detection are summarised in the survey by Radke et al. (2005): align the images, correct for illumination, take the difference, decide with a threshold and clean the result. The knowledge unit on repeat surveys stresses separating real change from alignment error and uncertainty before calling anything a detection. Three problems fill the result with false changes: different light, images that still differ slightly after registration (which turns every edge into a double line) and noise.
The method used in the next example has three layers. The first adjusts brightness by matching the median and the robust spread (MAD), which tolerates the real changes because most of the image is unchanged. The second is a shift-tolerant difference: compare each pixel of the later image with the maximum and the minimum in a window around the same pixel of the first, , which differs only when the value leaves the range of its neighbours. The third sets a threshold from the spread of the unchanged area, then applies an opening and a closing and keeps only regions that are large enough.
Example 5 Finding a new crack and a stain from two flights
A synthetic 400 × 300 pixel image. The first flight has an existing crack and a panel joint. The later flight has the crack extended and one elliptical stain (two real changes), is 12% brighter and still misregistered by 1.5 pixels after registration (assumed). Three methods are compared, counting the real changes found and the false regions.
import cv2
import numpy as np
GSD_MM = 0.289 # mm per pixel of the crack camera
h, w = 300, 400
before = concrete(h, w, 21, 0.6).astype(np.float32)
cv2.polylines(before, [np.array([(30, 40), (120, 70), (200, 90)], np.int32)], False, 90, 2) # the existing crack
cv2.line(before, (260, 0), (260, h - 1), 85, 3) # a panel joint
before = np.clip(before, 0, 255)
after = before.copy() # two real changes
cv2.polylines(after, [np.array([(200, 90), (250, 120), (330, 130)], np.int32)], False, 80, 3) # the crack extends
cv2.ellipse(after, (90, 220), (22, 12), 0, 0, 360, 95, -1) # a wet patch or vegetation
truth_boxes = {"crack extension": (200, 85, 335, 135), "patch": (65, 205, 115, 235)}
after = after * 1.12 - 8 # different light: 12% brighter
after = cv2.warpAffine(after, np.float32([[1, 0, 1.5], [0, 1, -1.0]]), (w, h), borderMode=cv2.BORDER_REFLECT) # residual misregistration of 1.5 px
after = np.clip(after + np.random.RandomState(5).normal(0, 3, after.shape), 0, 255)
before = np.clip(before + np.random.RandomState(6).normal(0, 3, before.shape), 0, 255)
def report(name, mask, min_area):
n, lab, st, cen = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8)
found = {k: False for k in truth_boxes}
big_parts, stray = 0, 0
for i in range(1, n):
if st[i, cv2.CC_STAT_AREA] < min_area:
continue
cx, cy = cen[i]
hit = [k for k, (x0, y0, x1, y1) in truth_boxes.items() if x0 <= cx <= x1 and y0 <= cy <= y1]
if hit:
found[hit[0]] = True; big_parts += 1
else:
stray += 1
print(f"{name:34s}: real changes found {sum(found.values())} of 2, false regions {stray:3d}")
report("1 plain difference > 25", np.abs(after - before) > 25, 20)
mad = lambda x: np.median(np.abs(x - np.median(x)))
gain = mad(after) / mad(before) # match the median and spread robustly (most of the image is unchanged)
off = np.median(after) - gain * np.median(before)
norm = (after - off) / gain
print(f"brightness fit: gain {gain:.3f} (true 1.12), offset {off:.1f}")
report("2 + brightness normalised", np.abs(norm - before) > 25, 20)
a, b = cv2.GaussianBlur(before, (0, 0), 1.5), cv2.GaussianBlur(norm, (0, 0), 1.5)
k5 = np.ones((5, 5), np.uint8)
up, lo = cv2.dilate(a, k5), cv2.erode(a, k5) # tolerate a shift of +-2 px: compare with the local maximum and minimum
d = np.maximum(np.maximum(b - up, lo - b), 0)
sigma = 1.4826 * mad(b - a) # spread of the unchanged area (MAD of the signed difference)
thr = 4 * sigma
print(f"signed difference spread {sigma:.2f}, threshold 4 sigma = {thr:.1f}")
mask = cv2.morphologyEx((d > thr).astype(np.uint8), cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
report("3 + tolerant difference + cleaning", mask, 60)
n, lab, st, cen = cv2.connectedComponentsWithStats(mask, connectivity=8)
for i in range(1, n):
if st[i, cv2.CC_STAT_AREA] >= 60:
print(f"region at ({cen[i][0]:.0f}, {cen[i][1]:.0f}) px: box {st[i, cv2.CC_STAT_WIDTH]} x {st[i, cv2.CC_STAT_HEIGHT]} px, area {st[i, cv2.CC_STAT_AREA]} px (upper bound {st[i, cv2.CC_STAT_AREA] * GSD_MM ** 2:.0f} mm2)")
1 plain difference > 25 : real changes found 2 of 2, false regions 288
brightness fit: gain 1.077 (true 1.12), offset -2.1
2 + brightness normalised : real changes found 2 of 2, false regions 80
signed difference spread 6.54, threshold 4 sigma = 26.2
3 + tolerant difference + cleaning: real changes found 2 of 2, false regions 0
region at (229, 106) px: box 53 x 33 px, area 328 px (upper bound 27 mm2)
region at (298, 125) px: box 68 x 13 px, area 332 px (upper bound 28 mm2)
region at (91, 219) px: box 43 x 24 px, area 740 px (upper bound 62 mm2)
A plain difference at a threshold of 25 finds both real changes but with 288 false regions. Correcting the brightness reduces this to 80 (the estimated gain is 1.077 against a true 1.12), because what is left is the 1.5 pixel misregistration that turns every edge into a double line. With the shift-tolerant difference, a threshold of 4 times the spread (26.2) and the cleaning step, both real changes are found and the false regions fall to 0. The result has three regions because the extended crack is split in two where it crosses the panel joint (the new crack and the joint are about equally dark, so there is no difference at the crossing). The areas given are only upper bounds (27, 28 and 62 mm²) because the tolerance and the closing enlarge the regions. Measuring the width and length of a real crack is done on the registered image in modules 13 and 14. The thresholds in this example are tuned to this image set, so they must be proved again with the acceptance test of module 15 before use on real work.
Module lab
Lab: register and compare two flights
- Photograph a textured concrete surface or wall at the university twice, at least an hour apart, with a slightly different angle and light, flying within CAAT conditions in visual line of sight or shooting from a tripod if the lecturer specifies.
- Set the Canny thresholds from an area with no cracks or objects as in Example 1, and report the continuity of the line of interest and the stray edges.
- Use the Hough transform to find the angle and spacing of regular lines in the image (joints, building edges) and compare with a tape measure that appears in the picture.
- Register the two images with ORB and SIFT, report the number of pairs, the inliers and the processing time of each, then measure the error at five check points marked by hand.
- Try a scene with a repeating pattern (for example tiles or precast flooring) and record how the matching fails.
- Build the change detector of Example 5 after placing one new object in the scene, and report the regions found and the false ones.
Common mistakes
Watch out
- Calling Canny without smoothing the image first, or using fixed thresholds copied from an online example instead of measuring in an area with no object.
- Not filtering the short edge pieces that hysteresis lets through, which fills the image with false cracks.
- Trusting every line from the Hough transform. One line may give several pairs; merge the groups and filter by angle and length.
- Reporting only that a homography was found, without the inlier count and the error.
- Matching images of a repeating surface with no outside position information to help.
- Chaining images over a long run without anchoring to targets. A small systematic error accumulates to several centimetres.
- Differencing two flights without correcting brightness or allowing a shift, which yields hundreds of false changes.
Summary
- Canny has four stages, and hysteresis trades continuity of a crack against stray edges. Measure the thresholds in an area with no object and follow with a filter on short edge pieces.
- The Hough transform gives the angle and position of lines, which times the GSD gives the tilt of the flight path, the canal width and the joint spacing.
- ORB is fast and enough for normal texture, SIFT is a little more accurate, and both fail on repeating patterns. Report the inliers and the corner error.
- A chain of images accumulates error as and must be anchored to targets of known position at intervals.
- Change detection must correct brightness and tolerate a shift before differencing, and its thresholds must be proved by an acceptance test.
Self-check questions
- In an image with a GSD of 0.040 m the spacing of the joints measures 118 pixels. What is the real spacing, and how many percent does it differ from the design value of 5.00 m?
- Registering with ORB gives 177 pairs that pass the ratio test, and RANSAC leaves 33 inliers. What is the inlier rate, and what should you suspect?
- A chain of images has a random error of 0.30 pixels and a systematic error of 0.05 pixels per pair. After 400 pairs, what are the systematic part and the random part (one standard deviation) in millimetres at a GSD of 0.289 mm?
- What are for a vertical straight line at x = 150 pixels, in OpenCV’s convention?
- Why must brightness be corrected and a shift of ±2 pixels tolerated before differencing two flights?
Answers
- m, which differs from 5.00 m by . Either the real spacing differs from the design, or the flight was lower than assumed (a GSD smaller than 0.040).
- , which is very low. Suspect a scene with a repeating pattern in which most pairs are wrong; outside position information or targets are needed.
- Systematic: pixels mm. Random: pixels mm.
- and , because a vertical line has and .
- Different light (12% here) raises the difference everywhere, and a misregistration of 1.5 pixels turns every edge into a double line. In the example the plain difference had 288 false regions, while the method that corrects both had 0.
Key formulas
| Hough transform for lines | |
| Lowe ratio test | |
| Drift of a chain of images | |
| Shift-tolerant difference |
Key references
- Szeliski, R. (2022). Computer vision: Algorithms and applications (2nd ed.). Springer. link
- OpenCV. OpenCV documentation. link
- Canny, J. (1986). A computational approach to edge detection. IEEE Transactions on Pattern Analysis and Machine Intelligence, PAMI-8(6), 679–698. link
- OpenCV. Canny edge detection. OpenCV 4.x Python tutorials. link
- OpenCV. Canny edge detector. OpenCV 4.x tutorials (imgproc module). link
- Duda, R. O., & Hart, P. E. (1972). Use of the Hough transformation to detect lines and curves in pictures. Communications of the ACM, 15(1), 11–15. link
- Matas, J., Galambos, C., & Kittler, J. (2000). Robust detection of lines using the progressive probabilistic Hough transform. Computer Vision and Image Understanding, 78(1), 119–137. link
- OpenCV. Hough line transform. OpenCV 4.x Python tutorials. link
- Rublee, E., Rabaud, V., Konolige, K., & Bradski, G. (2011). ORB: An efficient alternative to SIFT or SURF. In 2011 International Conference on Computer Vision (pp. 2564–2571). IEEE. link
- OpenCV. ORB (Oriented FAST and Rotated BRIEF). OpenCV 4.x Python tutorials. link
- Lowe, D. G. (2004). Distinctive image features from scale-invariant keypoints. International Journal of Computer Vision, 60(2), 91-110. https://doi.org/10.1023/B:VISI.0000029664.99615.94 link
- OpenCV. Feature matching. OpenCV 4.x Python tutorials. link
- Fischler, M. A., & Bolles, R. C. (1981). Random sample consensus: A paradigm for model fitting with applications to image analysis and automated cartography. Communications of the ACM, 24(6), 381-395. https://doi.org/10.1145/358669.358692 link
- Brown, M., & Lowe, D. G. (2007). Automatic panoramic image stitching using invariant features. International Journal of Computer Vision, 74(1), 59–73. link
- Radke, R. J., Andra, S., Al-Kofahi, O., & Roysam, B. (2005). Image change detection algorithms: A systematic survey. IEEE Transactions on Image Processing, 14(3), 294–307. 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