Features and matching
ORB keypoints with binary descriptors, brute-force nearest neighbours under Hamming distance, and Lowe's ratio test.
- Describe what an ORB descriptor is and how two are compared
- Implement k-nearest-neighbour matching and the ratio test
- Read a precision trade-off from real match counts
A corner alone is just a position. To find the same point in another photo, each keypoint needs a descriptor: a fingerprint of the patch around it that stays similar when the camera moves. The panorama code uses ORB:
orb = cv2.ORB_create(nfeatures=500, scoreType=cv2.ORB_FAST_SCORE)
keypoints, descriptors = orb.detectAndCompute(image_data['img'], None)
ORB finds FAST corners at several scales, estimates each one’s orientation, and describes the rotated patch with 256 binary tests (“is pixel a brighter than pixel b?”), packed into 32 bytes. Two descriptors are compared by Hamming distance — the number of differing bits, from 0 to 256 — which is a single XOR and popcount.
Two nearest neighbours
matchknn2 finds, for every descriptor in image 1, the closest and second-closest descriptor in image 2 by brute force:
for i in range(descriptors1.shape[0]):
distance = [cv2.norm(descriptors1[i], descriptors2[j], cv2.NORM_HAMMING)
for j in range(descriptors2.shape[0])]
distance = np.asarray(distance)
dm1 = cv2.DMatch(i, np.argmin(distance), np.min(distance))
distance_sorted = np.sort(distance)
dm2 = cv2.DMatch(i, np.argwhere(distance == distance_sorted[1])[0, 0], distance_sorted[1])
(The function first runs cv2.BFMatcher().knnMatch and draws its result, but that matcher uses the default L2 norm, which is the wrong distance for binary descriptors, and its output is discarded anyway. cv2.BFMatcher(cv2.NORM_HAMMING) would replace the whole loop.)
The ratio test
A repeated texture — windows, leaves, bricks — gives many near-identical descriptors, and the nearest neighbour is then a coin toss. Lowe’s ratio test keeps a match only if the best distance is clearly smaller than the second best:
def ratioTest(knnmatches, ratio_threshold):
matches = []
for distances in knnmatches:
if distances[0].distance / distances[1].distance < ratio_threshold:
matches.append(distances[0])
return matches
To measure what the threshold does, the repository’s own functions were run on img.png and a copy warped by a known homography, so every match can be checked against the truth:
The test divides by the second distance, which can be 0 when two descriptors in image 2 are identical; guarding with distances[1].distance > 0 avoids a ZeroDivisionError on synthetic or repetitive images.
Try it yourself. Replace matchknn2’s double loop with cv2.BFMatcher(cv2.NORM_HAMMING).knnMatch(d1, d2, k=2) and confirm you get the same matches. Time both for 500 features. Then add crossCheck=True (with k=1) — a match is kept only if each point is the other’s nearest neighbour — and compare its precision with the ratio test.