Week 03 · Feature matching and RANSAC

Fit a planar transform in the presence of bad matches.

← Week 2 · Subject contents · Week 4 →

Fit a planar transform in the presence of bad matches.

Work through the problem

A homography maps planar homogeneous coordinates by x′∝Hx. In Cartesian form u′=(h₁₁u+h₁₂v+h₁₃)/(h₃₁u+h₃₂v+1), with an analogous equation for v′. Four matches in a suitable configuration determine the eight free parameters when h₃₃=1.

RANSAC proposes a model from a small subset, projects every match, and counts those below a reprojection threshold. At inlier fraction 0.75, a four-match draw is all inliers with approximate probability 0.75⁴≈0.316 under independent draws. Repeated proposals improve the chance of finding a good hypothesis. Multiple depths under camera translation can need different models.

Run the Python lab

import numpy as np
rng = np.random.default_rng(7)
src = rng.uniform(-1,1,(36,2))
H = np.array([[1.,.1,.2],[.1,.9,-.1],[.12,-.07,1.]])
def project(matrix, points):
    p = np.c_[points,np.ones(len(points))]@matrix.T
    return p[:,:2]/p[:,2:]
dst = project(H,src)
dst[-9:] = rng.uniform(-1,1,(9,2))
def fit(indices):
    rows,rhs = [],[]
    for (x,y),(u,v) in zip(src[indices],dst[indices]):
        rows += [[x,y,1,0,0,0,-u*x,-u*y],[0,0,0,x,y,1,-v*x,-v*y]]
        rhs += [u,v]
    params = np.linalg.lstsq(rows,rhs,rcond=None)[0]
    return np.r_[params,1].reshape(3,3)
best = np.zeros(len(src),dtype=bool)
for _ in range(100):
    predicted = project(fit(rng.choice(len(src),4,replace=False)),src)
    inside = np.linalg.norm(predicted-dst,axis=1)<.01
    if inside.sum()>best.sum():
        best=inside
print("Inliers:",best.sum())
print("Recovered transform:",fit(best).round(2))
assert best.sum()==27 and np.allclose(fit(best),H)

Output from the lab

Inliers: 27
Recovered transform: [[ 1.    0.1   0.2 ]
 [ 0.1   0.9  -0.1 ]
 [ 0.12 -0.07  1.  ]]

Practice

  1. What does a loose threshold do?

Check your reasoning

  1. It can count incorrect correspondences as inliers, allowing a poor transform to win.

← Week 2 · Subject contents · Week 4 →

Further reading · Szeliski · Computer Vision: Algorithms and Applications