Estimate the optical flow (u,v) (horizontal, vertical, in pixels) of chosen points between two grayscale frames with the Lucas-Kanade method, optionally iterated.
Implement lucas_kanade(I1, I2, points, half=2, tau=1e-2, iters=1). I1, I2 are float (H, W) arrays and points is an (N, 2) integer array of pixel positions (x,y) = (column, row). Every window in the tests lies inside the image with at least one pixel to spare.
- Gradients of
I1 by central differences: Ix[r,c]=2I1[r,c+1]−I1[r,c−1] and Iy[r,c]=2I1[r+1,c]−I1[r−1,c].
- For a point, the window is the (2h+1)×(2h+1) block of pixels with rows y−h…y+h and columns x−h…x+h (h =
half). Form the structure tensor M=(∑Ix2∑IxIy∑IxIy∑Iy2) over the window.
- If the smallest eigenvalue of M is below
tau, the point is untrackable: return flow (0,0) and valid false.
- Otherwise start from (u,v)=(0,0) and repeat
iters times: sample I2 at every window pixel shifted by the current flow, (c+u, r+v), with bilinear interpolation (coordinates clipped to [0,W−1] and [0,H−1], x0=⌊x⌋, x1=min(x0+1,W−1), same for y); set It=I2(shifted)−I1 over the window; solve M(ΔuΔv)=−(∑IxIt∑IyIt) and add (Δu,Δv) to the flow. The gradients and M stay those of I1.
Return (flow, valid): a float (N, 2) array of (u,v) and a boolean (N,) array. With iters=1 this is classic single-step Lucas-Kanade with It=I2−I1.