Skip to content

Lab: estimate a known motion, then break the estimate

Draw two frames where a textured square moves a known amount, recover the shift by searching every candidate, score it with endpoint error, then dim the light and watch the brightness error and the motion error part ways.

Advanced ~16 min9 steps

What runs in CodeSplash

  • VID029FlowNet Runs as a notebook
  • VID031RAFT Needs a data type CodeSplash doesn't load yet

You will be able to

  • Recover a global shift by searching candidate translations and comparing warped frames
  • Score the estimate with endpoint error against the known motion
  • Show that a brightness change leaves the motion right but the warped error high
  • List the changes that make a single translation unidentifiable or wrong

Read first

01

The setup

Read

Synthetic frames are the one place where the true motion is known exactly, so endpoint error needs no guessed labels.

The first frame is 16 × 20 pixels, black except for a bright 5 × 5 square with one dimmer pixel inside it for texture. The second frame is the first moved three pixels right and one pixel down, with zeros filling the gap.

The estimator tries every shift within four pixels in each direction, moves the first frame by it and keeps the shift whose moved frame differs least from the second frame (mean squared difference). It assumes one shift explains the whole frame and brightness doesn't change.

02

The code

Explore

Run it in a notebook in either language. Both print the best shift, its endpoint error against the true shift, the warped and unwarped differences, and then the same search after the second frame is dimmed.

Python
import numpy as np

def shift(img, dy, dx):                       # move right/down, fill with zeros
    out = np.zeros_like(img); h, w = img.shape
    out[max(0, dy):h + min(0, dy), max(0, dx):w + min(0, dx)] = \
        img[max(0, -dy):h - max(0, dy), max(0, -dx):w - max(0, dx)]
    return out

def best_shift(a, b, r=4):
    return min((np.mean((shift(a, dy, dx) - b) ** 2), dy, dx)
               for dy in range(-r, r + 1) for dx in range(-r, r + 1))

first = np.zeros((16, 20)); first[5:10, 4:9] = 1; first[6, 5] = 0.3
second = shift(first, 1, 3)                   # truth: 3 right, 1 down
mse, dy, dx = best_shift(first, second)
epe = np.hypot(dx - 3, dy - 1)
print("shift", (dx, dy), "EPE", epe, "warped", mse,
      "unwarped", np.mean((first - second) ** 2))
mse2, dy2, dx2 = best_shift(first, 0.6 * second)   # dim the second frame
print("dimmed: shift", (dx2, dy2), "warped", round(mse2, 6))
R
shift <- function(img, dy, dx) {              # move right/down, fill with zeros
  h <- nrow(img); w <- ncol(img); out <- matrix(0, h, w)
  rs <- max(1, 1 - dy):min(h, h - dy); cs <- max(1, 1 - dx):min(w, w - dx)
  out[rs + dy, cs + dx] <- img[rs, cs]; out
}
best_shift <- function(a, b, r = 4) {
  best <- c(Inf, 0, 0)
  for (dy in -r:r) for (dx in -r:r) {
    m <- mean((shift(a, dy, dx) - b)^2)
    if (m < best[1]) best <- c(m, dy, dx)
  }
  best
}
first <- matrix(0, 16, 20); first[6:10, 5:9] <- 1; first[7, 6] <- 0.3
second <- shift(first, 1, 3)                  # truth: 3 right, 1 down
b <- best_shift(first, second)
cat("shift", b[3], b[2], "EPE", sqrt((b[3] - 3)^2 + (b[2] - 1)^2),
    "warped", b[1], "unwarped", mean((first - second)^2), "\n")
b2 <- best_shift(first, 0.6 * second)         # dim the second frame
cat("dimmed: shift", b2[3], b2[2], "warped", round(b2[1], 6), "\n")

Notebook exercise · ~12 min

Estimate a known motion and its endpoint error

Estimate one global motion with Lucas–Kanade least squares, score it by endpoint error against the known shift, then break it with a large motion.

  1. One global motion by least squares

    With I_x and I_y the gradients of frame1 and I_t = inner(frame2) − inner(frame1), solve the 2 × 2 system [ΣI_x² ΣI_xI_y; ΣI_xI_y ΣI_y²] (u, v) = −(ΣI_xI_t, ΣI_yI_t). Store (u, v) in flow.

    Show a solution
    Python
    def lucas_kanade(a, b):
        Ix, Iy, It = grad_x(a), grad_y(a), inner(b) - inner(a)
        A = np.array([[np.sum(Ix * Ix), np.sum(Ix * Iy)], [np.sum(Ix * Iy), np.sum(Iy * Iy)]])
        return np.linalg.solve(A, -np.array([np.sum(Ix * It), np.sum(Iy * It)]))
    flow = lucas_kanade(frame1, frame2)
    R
    lucas_kanade <- function(a, b) {
      Ix <- grad_x(a); Iy <- grad_y(a); It <- inner(b) - inner(a)
      A <- matrix(c(sum(Ix * Ix), sum(Ix * Iy), sum(Ix * Iy), sum(Iy * Iy)), 2, 2)
      solve(A, -c(sum(Ix * It), sum(Iy * It)))
    }
    flow <- lucas_kanade(frame1, frame2)
  2. Endpoint error

    The endpoint error is the distance between the estimated and the true motion vectors. Store it, for the true (1.2, −0.7), in epe.

    Show a solution
    Python
    epe = math.hypot(flow[0] - 1.2, flow[1] + 0.7)
    R
    epe <- sqrt((flow[1] - 1.2)^2 + (flow[2] + 0.7)^2)
  3. Break it with a large motion

    Make new frames with frames(4.0, -3.0), estimate the motion the same way, and store the endpoint error against the true (4, −3) in epe_large.

    Show a solution
    Python
    a, b = frames(4.0, -3.0)
    est = lucas_kanade(a, b)
    epe_large = math.hypot(est[0] - 4, est[1] + 3)
    R
    big <- frames(4.0, -3.0)
    est <- lucas_kanade(big[[1]], big[[2]])
    epe_large <- sqrt((est[1] - 4)^2 + (est[2] + 3)^2)

In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.

03

Predict the clean result

Predict

Predict first

The square moves exactly three pixels right and one down, inside the search radius, with no lighting change. What does the search report?

The search finds the true shift exactlyIt finds a nearby shift with a small errorIt can't decide between several shifts
Reveal

The true shift, exactly. Moving the first frame by the true shift reproduces the second frame pixel for pixel, so the warped difference is zero and so is the endpoint error. The unwarped difference, comparing the frames without moving them, is not zero: that gap is what motion explains.

04

Dim the light

Predict

Predict first

Now the second frame is dimmed to 60% brightness, as if a cloud passed. What happens?

The shift goes wrongThe shift stays right, but the warped difference is no longer zeroNothing changes
Reveal

The shift stays right; the warped difference doesn't return to zero. In this fixture the best shift is still the true one, so the endpoint error is still zero, but no shift can explain a brightness change. A brightness error and a motion error measure different things: a model judged by how well it rebuilds frames can be right about motion and still score badly, or the reverse.

05

Ways to break it

Read

Change one thing at a time and rerun:

  • Move farther than the radius. The true shift isn't a candidate, so the search returns a wrong one with full confidence.
  • Crop the square at the edge. Fewer pixels pin the answer down.
  • Remove the texture or flatten the square. Several shifts can match about equally well.
  • Add a second square moving the other way. One global shift can't describe two motions; dense flow is needed.

None of these is a failure of the code. Each breaks an assumption the estimate depends on. This lab measures one shift for the whole frame; it is never dense flow for every pixel.

DExplorable · Optical flow: Lucas–Kanade, warping and endpoint error

How can a computer tell how far each part of an image moved between two frames?

With this picture and motion, what will Lucas–Kanade find?

How sure?

Picture

Many small blobs (rich texture), diagonal stripes, or two broad smooth blobs.

1.5

How far the picture moves to the right between the frames.

−1.0

How far the picture moves down between the frames.

0.0

Turns the picture about its center, so the motion differs from place to place.

1.00

Scales the picture about its center: things move outward when it grows.

3

Lucas–Kanade assumes one motion inside a square window this many pixels around each point.

3

Each step warps the second frame by the current estimate and solves for the remaining motion.

0.01

Random noise added to the second frame.

Frame 1Frame 2 with motion (arrows drawn 2× long)0.210No warp0.017Warped by the estimate

Mean endpoint error 0.14 px. 4% of the windows see the pattern change in one direction only.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

06

From the lab to learned flow

Read

Learned estimators do a softer version of the same search. RAFT's all-pairs correlation is this lab's comparison of every shift, learned on features instead of raw brightness, followed by repeated small corrections.

Reference · VID031 · Needs a data type CodeSplash doesn't load yetRAFTComputes all-pairs feature correlations and repeatedly updates a dense flow field using a recurrent refinement operator.

FlowNet's training loss is the endpoint error you computed, summed over output scales. The same brightness trap applies: a model trained to rebuild frames is rewarded for explaining brightness, which isn't always motion.

Reference · VID029 · Runs as a notebookFlowNetPredicts dense optical flow between two images with a convolutional encoder-decoder. FlowNet established a direct learned mapping from image pairs to per-pixel displacement, useful for motion measurement and as input to…
07

What runs here

Read
EntryIn CodeSplash
VID029 · FlowNetRuns as a notebook (the reference program; no method)
VID031 · RAFTNeeds a data type CodeSplash doesn't load yet (video)
08

Check: the flow lab

Checkpoint

Check yourself

Why does the lab use frames the code draws itself?

Show the answer

Answer: b

Ground-truth flow is rare in real footage. A known synthetic shift makes the score exact.

Check yourself

After dimming the second frame, the best shift is still correct but the warped difference isn't zero. What does that show?

Show the answer

Answer: b

No shift explains a lighting change, so the rebuild error stays even when the motion is right.

Check yourself

The square moves six pixels, but the search only tries shifts up to four. What happens?

Show the answer

Answer: b

A search can only choose among the candidates it tries. Learned refiners like RAFT also have limits on how far their lookups reach; test large motions.

Check yourself

A second square enters, moving left while the first moves right. What should you conclude about the global-shift estimator?

Show the answer

Answer: b

A single translation is a model of the whole frame. Independent motions break it.

Check yourself

You remove the texture inside the square and make it a flat block. What can go wrong with matching?

Show the answer

Answer: a

Flat regions look the same after small shifts. That ambiguity is why textureless areas are hard for every flow method.

09

Recap

Recap
  • With a known synthetic shift, endpoint error is exact.
  • Searching candidate shifts and comparing warped frames recovers one global motion.
  • A brightness change leaves the motion right and the rebuild error high: two different errors.
  • Large motion, flat texture and several moving objects break a single-shift estimate.

Concepts in this lesson