Optical flow with Lucas–Kanade
Brightness constancy, one linear system per window, Gauss–Newton iterations — and the aperture problem that makes edges ambiguous.
- Derive the Lucas–Kanade equations from brightness constancy
- Explain the iteration in opticalFlowLK.py and when it converges
- Recognise the aperture problem from the eigenvalues of A^T W A
Optical flow is the apparent motion of image content between two frames. The key assumption is brightness constancy: a point keeps its intensity as it moves, \(I_{t+1}(x + u, y + v) = I_t(x, y)\). A first-order Taylor expansion turns that into one linear equation per pixel,
\[I_x u + I_y v + I_t = 0,\]one equation for two unknowns. Lucas and Kanade assume all pixels in a small window share the same \((u, v)\) and solve the overdetermined system by weighted least squares:
\[(A^{\mathsf T} W A) \begin{pmatrix} u \\ v \end{pmatrix} = -A^{\mathsf T} W\, \mathbf{b}_t, \qquad A^{\mathsf T} W A = \sum w \begin{pmatrix} I_x^2 & I_x I_y \\ I_x I_y & I_y^2 \end{pmatrix}.\]That matrix is the Harris structure tensor of lesson 5 — so the points that track well are exactly the corners.
The iteration
The linearisation only holds for small motions, so OpticalFlowLK.compute iterates: sample the next frame at the current estimate (with bilinear weights for sub-pixel positions), solve for a correction, move, repeat until the step is below epsilon = 0.03 px or 20 iterations pass.
AtWA = np.dot(A.T, A * weights.reshape(-1, 1))
invAtWA = invertMatrix2x2(AtWA)
for j in range(self.iterations):
... # bnext sampled at u
AtWbnbp = np.dot(A.T * weights_flat, bnext - bprev)
deltaU = -np.dot(invAtWA, AtWbnbp)
u += deltaU.reshape((2,))
if np.linalg.norm(deltaU) < self.epsilon:
break
On a vertical edge every gradient points along \(x\), so \(A^{\mathsf T} W A\) has a zero eigenvalue: sliding along the edge changes nothing, and no window that sees only the edge can measure that component. This is why the script tracks goodFeaturesToTrack corners, not arbitrary pixels.
Checked against OpenCV
All three helper tests in __main__.py pass (bilinear weights, Gaussian weights, 2 × 2 inverse). On two consecutive frames of the traffic video, the hand-written tracker and cv2.calcOpticalFlowPyrLK agree closely: over 139 tracked corners the endpoints differ by a median of 0.035 px (90th percentile 0.11 px). The motion between frames is small — a median of 0.67 px for the moving points — which suits a single-level tracker; for fast motion, OpenCV’s pyramid (maxLevel=2) estimates coarse motion at low resolution first.
One robustness fix: the main loop reads frames with ret, frame = cap.read() and resizes immediately. At the end of the video frame is None, and cv2.resize raises an assertion error. if not ret: break right after the read ends the loop cleanly — the same applies to the frame-differencing script of lesson 12.
Try it yourself. Track a point on the bridge railing, which is an edge, and print the eigenvalues of AtWA. Then increase the true motion in the animation’s setting mentally: for a shift of 10 px, would the single-level tracker converge? Test it by skipping frames (cap.set(cv2.CAP_PROP_POS_FRAMES, k + 10)) and comparing with the pyramidal OpenCV version.