Algorithm Search⌘K

Algorithmadvanced

Tracking-learning-detection

Also called TLD, Predator tracker.

Run a median flow tracker and a detector side by side, and let each correct the other through positive and negative expert constraints that train the detector online.

Time
Θ(N (P + W (D + M Q) + G)) worst · averageΘ(N (P + W + G)) best
Space
Θ(P + W + M Q + C) extra
Where
C = the number of counters in the fern tables; D = the number of pixel comparisons in all ferns; G = the number of tracked points times the pixels in the window of each point; M = the number of patches in the object model; N = the number of frames; P = the number of pixels in a frame; Q = the number of pixels in a normalized patch; W = the number of scanning windows
Properties
randomizednot exactnot iterativenot localonline
Origin
Zdenek Kalal, Krystian Mikolajczyk, Jiri Matas, 2012

Tracking-learning-detection (TLD) is a method for long-term tracking of one object that is given by a box in the first frame. It runs two components on every frame. A short-term tracker, median flow, moves the box from the previous frame by the median motion of reliable points. A detector scans the whole frame with a cascade of three classifiers and finds every place that looks like the object. An integrator picks one answer, and a learning step uses the answer to correct the detector: windows on a reliable trajectory become positive examples, and windows far from it become negative examples. The tracker can follow new appearances that the detector does not know yet, and the detector can find the object again after the tracker has lost it. Kalal, Mikolajczyk and Matas published the method in 2012.

In plain words

One helper follows the object from frame to frame. It is accurate but forgets nothing and fixes nothing, so after the object is hidden it is lost for good. A second helper looks at every place in the picture and asks whether the object is there. It can find the object anywhere, but at the start it knows only one picture of it. So we let the two teach each other. While the follower is sure, the places it visits teach the searcher what the object looks like, and every other place in the picture teaches the searcher what the object is not. When the follower gives up, the searcher, which has learned a lot by then, tells the follower where to start again.

The problem

The input is a video and a box B0=(x1,y1,x2,y2)B_0 = (x_1, y_1, x_2, y_2) around the object in frame 0. In each later frame the output is a box, or the answer that the object is not visible. The object can change its appearance, leave the view, be hidden for many frames and come back at another place. Two boxes are compared by their overlap, the intersection over union. Pixel (u,v)(u, v) has its center at the point (u,v)(u, v).

Object model. A patch is the content of a box resampled to a fixed size and normalized to zero mean and unit norm; the paper uses 15×1515 \times 15 pixels. The similarity of two patches is S(a,b)=12(NCC(a,b)+1)S(a, b) = \frac12 (\mathrm{NCC}(a, b) + 1), where NCC is the normalized cross-correlation. The model is a list of positive patches, in the order they were added, and a list of negative patches. For a patch pp, let S+S^+ and S−S^- be its largest similarity to a positive and to a negative patch, and S50%+S^+_{50\%} its largest similarity to the older half of the positives. The relative similarity is Sr=S+/(S++S−)S^r = S^+ / (S^+ + S^-) and the conservative similarity is Sc=S50%+/(S50%++S−)S^c = S^+_{50\%} / (S^+_{50\%} + S^-).

The algorithm

  1. MEDIAN-FLOW(F_prev, F, B)
  2. 1place a grid of points in B
  3. 2track each point from F_prev to F with Lucas-Kanade, and back again
  4. 3e_i ← the forward-backward error of point i; c_i ← the NCC of the windows around it
  5. 4keep the points with e_i ≤ median(e) and c_i ≥ median(c); fail if none or median(e) > e_max
  6. 5d ← the median displacement of the kept points
  7. 6fail if the median distance of all displacements from d is above 10 pixels
  8. 7s ← the median ratio of point distances after and before; return B moved by d and scaled by s
  9. DETECT(F)
  10. 8reject each scanning window whose gray value variance is below half that of B₀
  11. 9reject each remaining window whose mean fern posterior is not above 1/2
  12. 10return the remaining windows with S^r > θ_NN
  13. TLD-FRAME(F_prev, F)
  14. 11T ← MEDIAN-FLOW(F_prev, F, B) if B exists
  15. 12group the windows of DETECT(F) into clusters of overlap above 1/2, one box per cluster
  16. 13B ← the candidate (T or a cluster box) with the largest S^c, or NONE if there is no candidate
  17. 14reliable ← (B = T and reliable) or S^c(B) > θ_core
  18. 15if reliable then LEARN(F, B)
  19. LEARN(F, B)
  20. 16for the 10 windows closest to B: train the ferns on warped copies labeled positive
  21. 17add the patch of B to the positives if S^r - θ_NN < λ
  22. 18for each window with overlap below 0.2 that passes the variance test and the ferns: train the ferns on it labeled negative
  23. 19add its patch to the negatives if S^r > θ_NN - λ

If line L13 gives NONE, the object is reported as not visible and the trajectory is not reliable. The detector of lines L8 to L10 is a cascade: each stage is more expensive than the one before and sees only the windows the earlier stages let through. The scanning windows are all positions and scales of the first box; the paper uses scales in steps of 1.2, shifts of 10 percent of the width and of the height, and a smallest box of 20 pixels, which gives about 50,000 windows on a 320×240320 \times 240 image. Line L8 computes each variance in constant time from two integral images, one of the values and one of their squares.

Ferns. Each fern compares a fixed random set of dd pixel pairs inside the window, which gives a dd-bit code. It stores, for each code, the number pp of positive and nn of negative training windows with that code, and its posterior is p/(p+n)p / (p + n). Line L9 averages the posteriors of all ferns. The paper blurs the image with a Gaussian of standard deviation 3 before the comparisons and uses 13 comparisons per fern. A fern is trained on an example only if the ensemble classifies it wrongly, except in the first frame.

Learning. The P-expert (positive) assumes that the object moves along a trajectory, so windows close to a reliable box are positive. The N-expert (negative) assumes that the object is at one place only, so windows far from it are negative. In the first frame the paper takes the 10 windows closest to B0B_0 and makes 20 warped copies of each (shift by up to 1 percent, scale by up to 1 percent, rotation by up to 10 degrees, Gaussian noise of standard deviation 5), 200 positives in all. In later frames it makes 10 copies of each, with rotation up to 5 degrees. The nearest neighbor model gets a new patch only if its label is wrong or its margin Sr−θNNS^r - \theta_{\text{NN}} is smaller than λ=0.1\lambda = 0.1, so the model stays small. The paper uses θNN=0.6\theta_{\text{NN}} = 0.6 and reports similar results from 0.5 to 0.7.

Integrator and reliability. The integrator outputs the most confident candidate by ScS^c, or nothing if neither the tracker nor the detector gives a box. A trajectory becomes reliable when ScS^c of the box is above a threshold, which the paper calls entering the core of the model, and stays reliable until the detector reinitializes it or the tracker fails. Only reliable boxes train the detector.

The code on this page follows these rules with smaller numbers for small test images: a 10×1010 \times 10 grid of points, 10 ferns of 10 comparisons on unblurred pixels, warps by shift, scale and noise only (no rotation), θNN=θcore=0.55\theta_{\text{NN}} = \theta_{\text{core}} = 0.55, and an extra failure test of line L4, a median forward-backward error above 5 pixels. These values are this page's choices.

Example

Similarities by hand. Let a patch have S+=0.9S^+ = 0.9, S−=0.6S^- = 0.6 and S50%+=0.8S^+_{50\%} = 0.8. Then Sr=0.9/1.5=0.6S^r = 0.9 / 1.5 = 0.6 and Sc=0.8/1.4≈0.571S^c = 0.8 / 1.4 \approx 0.571. A patch identical to a positive has S+=1S^+ = 1, but if one negative has S−=0.636S^- = 0.636, its relative similarity is only 1/1.636≈0.6111 / 1.636 \approx 0.611. In small images with few textures this happens, and it is why the code uses thresholds of 0.55.

Median flow by hand. Five kept points move by (1,0)(1, 0), (1.1,0)(1.1, 0), (0.9,0.1)(0.9, 0.1), (1,−0.1)(1, -0.1) and (8,6)(8, 6); the last one is on an occluder. The medians of the coordinates are 11 and 00, so the box moves by (1,0)(1, 0) and the bad point has no effect. Its distance from the median motion is about 9.2 pixels, but the median of the five distances is 0.1, so line L6 does not report a failure.

A full run. The frames are 40×4040 \times 40. The background is smooth, with two textured distractors, a checkerboard and vertical stripes. The object is a 10×1010 \times 10 square of random gray values from {30,90,160,230}\{30, 90, 160, 230\}, first at (6,4)(6, 4), moving by (2,1)(2, 1) per frame. There are 2,891 scanning windows at the three scales 1/1.21/1.2, 1 and 1.2; 708 of them pass the variance test in frame 0 (the object variance is 5,252). The first learning step adds 200 warped positives to the ferns, trains them on 527 negative windows, and puts 35 negative patches into the model.

frame object at output box IoU with truth ScS^c reliable
1 (8,5)(8, 5) (8.00,5.00,18.00,15.00)(8.00, 5.00, 18.00, 15.00) 0.999 0.618 yes
4 (14,8)(14, 8) (14.01,8.01,23.99,17.99)(14.01, 8.01, 23.99, 17.99) 0.995 0.618 yes
5 hidden none no
6 hidden none no
7 (26,22)(26, 22) (25.75,21.75,36.25,32.25)(25.75, 21.75, 36.25, 32.25) 0.907 0.617 yes
8 (25,24)(25, 24) (24.75,23.75,35.25,34.25)(24.75, 23.75, 35.25, 34.25) 0.907 0.617 yes

In frames 5 and 6 a flat gray square covers the object. Median flow fails because the median forward-backward error is far above 5 pixels, and the detector finds no window, so the output is "not visible". In frame 7 the object is back at another place. The tracker has nothing to follow, but the detector returns 4 windows in one cluster, and their mean box starts the trajectory again. In frame 8 median flow continues from it.

Correctness

TLD as a whole is a heuristic: nothing proves that its box covers the object. The full proof of the parts that can be proved is in proofs/correctness.md.

  • Theorem: exact variance in constant time. Four reads from each integral image give the sum and the sum of squares of any box.
  • Theorem: median flow. It is exact for a translation, the scale estimate is exact for a similarity, and if more than half of the kept displacements lie in an interval, the median does too.
  • Theorem: similarity ranges. SS, SrS^r and ScS^c are in [0,1][0, 1], SrS^r grows with S+S^+ and falls with S−S^-, and Sc≤SrS^c \le S^r.
  • Theorem: stability of P-N learning (under the paper's model). With constant precision and recall of the two experts, the false positives and false negatives follow x(k+1)=Mx(k)x(k + 1) = M x(k), and they go to 0 if and only if both eigenvalues of MM are below 1 in absolute value. If all four qualities equal 1−ε1 - \varepsilon, this holds exactly when ε<1/2\varepsilon < 1/2.
  • Heuristic. The failure tests, the integrator, the reliability rule and all thresholds.
Proof: The parts of tracking-learning-detection that can be proved exactly, the median flow estimates, the constant-time variance filter, the similarity ranges, and the stability condition of P-N learningfull

Notation as on the page. TLD as a whole is a heuristic: it has no guarantee that the box it outputs covers the object. What can be proved is that each part computes what it says it computes, and, under the model of Kalal, Mikolajczyk and Matas, when the errors of P-N learning go down. The claims below do that.

Claim 1: the variance filter is exact and costs constant time per window

Let S(x,y)=∑u<x, v<yI(u,v)S(x, y) = \sum_{u < x,\, v < y} I(u, v) and S2S_2 the same sum of I(u,v)2I(u, v)^2, with S(0,⋅)=S(⋅,0)=0S(0, \cdot) = S(\cdot, 0) = 0. For the integer box B=[x1,x2)×[y1,y2)B = [x_1, x_2) \times [y_1, y_2) with nn pixels,

∑(u,v)∈BI(u,v)=S(x2,y2)−S(x1,y2)−S(x2,y1)+S(x1,y1),\sum_{(u, v) \in B} I(u, v) = S(x_2, y_2) - S(x_1, y_2) - S(x_2, y_1) + S(x_1, y_1),

and the same holds for S2S_2. Then the variance of the pixels of BB is E[I2]−E[I]2E[I^2] - E[I]^2 with both means read from these sums.

Proof. S(x2,y2)S(x_2, y_2) counts every pixel with u<x2u < x_2 and v<y2v < y_2. Subtracting S(x1,y2)S(x_1, y_2) and S(x2,y1)S(x_2, y_1) removes the pixels with u<x1u < x_1 or v<y1v < y_1, but removes the pixels with u<x1u < x_1 and v<y1v < y_1 twice, and adding S(x1,y1)S(x_1, y_1) restores them once. So each pixel of BB is counted once and every other pixel zero times. The variance identity is 1n∑(I−m)2=1n∑I2−2m1n∑I+m2=E[I2]−m2\frac1n \sum (I - m)^2 = \frac1n \sum I^2 - 2 m \frac1n \sum I + m^2 = E[I^2] - m^2 with m=E[I]m = E[I]. Four reads from each table and a few operations give the value, so line L8 costs O(1)O(1) per window after O(P)O(P) work to build the tables. □\square

Claim 2: median flow is exact for a translation and robust to a minority of bad points

Let the points pip_i of line L1 move to qi=pi+diq_i = p_i + d_i, and let dmd_m be the median (taken coordinate by coordinate) of the displacements of the kept points of line L4.

(a) If every kept point has di=dd_i = d, then line L5 gives dm=dd_m = d, and every distance ratio of line L7 is 1, so the box moves by dd and keeps its size.

(b) If the points obey a similarity, qi=sRpi+tq_i = s R p_i + t with RR a rotation and s>0s > 0, then every ratio ∣qi−qj∣/∣pi−pj∣|q_i - q_j| / |p_i - p_j| equals ss, so line L7 gives exactly ss.

(c) If more than half of the kept displacements have their first coordinate in an interval [a,b][a, b], then the first coordinate of dmd_m is in [a,b][a, b]; the same holds for the second coordinate.

Proof. (a) The median of equal numbers is that number, and ∣qi−qj∣=∣pi−pj∣|q_i - q_j| = |p_i - p_j|. (b) ∣qi−qj∣=∣sR(pi−pj)∣=s∣pi−pj∣|q_i - q_j| = |s R (p_i - p_j)| = s |p_i - p_j| because a rotation keeps lengths. (c) Sort the kk values as v1≤⋯≤vkv_1 \le \dots \le v_k. Fewer than k/2k/2 values are outside [a,b][a, b], so fewer than k/2k/2 are below aa, and therefore vj≥av_j \ge a for every j≥k/2j \ge k/2. In the same way fewer than k/2k/2 are above bb, so vj≤bv_j \le b for every j≤k/2+1j \le k/2 + 1. The median is v(k+1)/2v_{(k+1)/2} for odd kk, or the mean of vk/2v_{k/2} and vk/2+1v_{k/2 + 1} for even kk; in both cases the values used have indices in [k/2,k/2+1][k/2, k/2 + 1], so they are in [a,b][a, b], and so is their mean. □\square

So a few points on an occluder or on the background cannot move the box far, as long as most kept points follow the object. Lines L3 and L4 try to make this true by dropping the points with a large forward-backward error or a low NCC, but this is a heuristic: a point can be wrong and still have a small forward-backward error.

Claim 3: the similarities are in [0, 1] and are monotone in the right direction

For normalized patches aa, bb (zero mean, unit norm), NCC(a,b)=⟨a,b⟩∈[−1,1]\mathrm{NCC}(a, b) = \langle a, b \rangle \in [-1, 1] by the Cauchy-Schwarz inequality, so S(a,b)=12(NCC+1)∈[0,1]S(a, b) = \frac12 (\mathrm{NCC} + 1) \in [0, 1], with 1 only for b=ab = a and 0 only for b=−ab = -a. Let S+S^+ and S−S^- be the largest similarities to a positive and to a negative patch. Then Sr=S+/(S++S−)∈[0,1]S^r = S^+ / (S^+ + S^-) \in [0, 1] grows with S+S^+ and falls with S−S^-, and Sc≤SrS^c \le S^r.

Proof. The first part is Cauchy-Schwarz, with equality only for parallel vectors; unit norm leaves b=±ab = \pm a. SrS^r has the derivative S−/(S++S−)2≥0S^- / (S^+ + S^-)^2 \ge 0 in S+S^+ and −S+/(S++S−)2≤0-S^+ / (S^+ + S^-)^2 \le 0 in S−S^-. The conservative similarity uses S50%+S^+_{50\%}, the largest similarity to the older half of the positives, which is a subset, so S50%+≤S+S^+_{50\%} \le S^+ and by monotony Sc≤SrS^c \le S^r. □\square

A consequence that the example on the page shows: a patch identical to a positive has Sr=1/(1+S−)S^r = 1 / (1 + S^-), so SrS^r can be well below 1 when one negative is a little similar. The threshold θNN\theta_{\text{NN}} must be set with this in mind.

Claim 4: the ensemble posterior is an average of empirical frequencies

For fern ff and code cc with pp positive and nn negative training counts, line L9 uses Pf(c)=p/(p+n)P_f(c) = p / (p + n) (0 if p+n=0p + n = 0), and the ensemble value is the mean over the ferns. Each Pf(c)∈[0,1]P_f(c) \in [0, 1], so the mean is in [0,1][0, 1]; a window is passed if the mean is above 1/21/2. This is the definition, and the tests check the counts. Whether the frequencies estimate a true posterior depends on the training samples, which is not claimed.

Claim 5: the stability condition of P-N learning

This is the analysis of Kalal, Mikolajczyk and Matas (Section 4.2). Let α(k)\alpha(k) and β(k)\beta(k) be the numbers of false positives and false negatives of the classifier after iteration kk. The P-expert outputs nc+(k)n^+_c(k) correct and nf+(k)n^+_f(k) false positive labels, the N-expert nc−(k)n^-_c(k) correct and nf−(k)n^-_f(k) false negative labels, and every label changes the classifier's decision on that example. Assume the four quality measures are constant:

P+=nc+nc++nf+,R+=nc+β,P−=nc−nc−+nf−,R−=nc−α.P^+ = \frac{n^+_c}{n^+_c + n^+_f}, \quad R^+ = \frac{n^+_c}{\beta}, \quad P^- = \frac{n^-_c}{n^-_c + n^-_f}, \quad R^- = \frac{n^-_c}{\alpha}.

Then x(k)=(α(k),β(k))Tx(k) = (\alpha(k), \beta(k))^{\mathsf T} obeys x(k+1)=Mx(k)x(k + 1) = M x(k) with

M=(1−R−1−P+P+R+1−P−P−R−1−R+),M = \begin{pmatrix} 1 - R^- & \frac{1 - P^+}{P^+} R^+ \\[2pt] \frac{1 - P^-}{P^-} R^- & 1 - R^+ \end{pmatrix},

and x(k)→0x(k) \to 0 for every start if and only if both eigenvalues of MM have absolute value below 1.

Proof. A correct positive label fixes a false negative and a false positive label creates a false positive, so α(k+1)=α(k)−nc−(k)+nf+(k)\alpha(k+1) = \alpha(k) - n^-_c(k) + n^+_f(k) and β(k+1)=β(k)−nc+(k)+nf−(k)\beta(k+1) = \beta(k) - n^+_c(k) + n^-_f(k). From the definitions, nc+=R+βn^+_c = R^+ \beta, nf+=nc+(1−P+)/P+=1−P+P+R+βn^+_f = n^+_c (1 - P^+) / P^+ = \frac{1 - P^+}{P^+} R^+ \beta, nc−=R−αn^-_c = R^- \alpha and nf−=1−P−P−R−αn^-_f = \frac{1 - P^-}{P^-} R^- \alpha. Substituting gives the two rows of MM. For a linear recursion x(k)=Mkx(0)x(k) = M^k x(0), and Mk→0M^k \to 0 if and only if the spectral radius of MM is below 1 (write MM in Jordan form: a block with eigenvalue λ\lambda has entries (kj)λk−j\binom{k}{j} \lambda^{k - j}, which go to 0 if and only if ∣λ∣<1|\lambda| < 1). □\square

The symmetric case. With P+=R+=P−=R−=1−εP^+ = R^+ = P^- = R^- = 1 - \varepsilon, every entry of MM is ε\varepsilon, so the eigenvalues are 00 and 2ε2\varepsilon (the all-ones 2×22 \times 2 matrix has eigenvectors (1,1)(1, 1) and (1,−1)(1, -1) with eigenvalues 2 and 0). The errors go to 0 if and only if ε<1/2\varepsilon < 1/2: experts that are right more often than wrong are enough, because the errors of the two experts partly cancel.

The real experts of TLD do not have constant quality, and their labels are not independent of the classifier, so this claim explains why the method can improve but does not prove that the implemented tracker does.

What is not claimed

The integrator (line L13) picks the candidate with the largest conservative similarity; nothing proves it is the object. The rule of line L14, which keeps a trajectory reliable while the tracker has not failed, can keep learning from an occluder for some frames. The failure tests of line L4 and line L6 can miss a failure and can stop on a good frame. All thresholds are heuristics.

Complexity

Building the two integral images costs Θ(P)\Theta(P) per frame. The variance test costs O(1)O(1) per window, so Θ(W)\Theta(W) in all. A window that reaches the ferns costs Θ(D)\Theta(D) for the comparisons, and a window that reaches the nearest neighbor stage costs Θ(MQ)\Theta(M Q) for the similarities to all model patches. Median flow costs Θ(G)\Theta(G) for the Lucas-Kanade steps (with a fixed number of iterations), plus the medians and the distance ratios of line L7 over all pairs of kept points; for KK points these cost O(K2)O(K^2), which is below GG when KK is at most the number of pixels in the window of a point, as for a 10×1010 \times 10 grid with 7×77 \times 7 windows. Learning visits every window once more, at the same cost per window. So a frame costs Θ(P+W(D+MQ)+G)\Theta(P + W (D + M Q) + G) in the worst case and Θ(P+W+G)\Theta(P + W + G) in the best case, when the variance test rejects every window. In practice the cascade leaves only tens of windows for the last stage, which is the reason for the cascade, but there is no bound on that. The space is Θ(P)\Theta(P) for the integral images, Θ(W)\Theta(W) for the window list, Θ(MQ)\Theta(M Q) for the model patches, and Θ(C)\Theta(C) for the fern tables, which hold two counters for each of the 2d2^d codes of each fern.

Properties

  • Long-term. It can find the object again after a full occlusion or after it left the view, which a pure tracker cannot.
  • Online and from one example. It starts from one box and learns all the rest during the run.
  • Randomized. The ferns and the warps are random; the code fixes the seed.
  • Fixed aspect ratio. The box changes its scale but not its shape, and in-plane rotation is not modeled.
  • Model growth is bounded by the update rule. Patches enter the model only when they are misclassified or near the decision boundary; the paper also forgets templates at random when there are too many.
  • Gray values only. The detector and the tracker use gray values; there is no color.

Variants and improvements

  • P-N learning alone. The same experts can train any detector from a video; the paper analyzes this before it describes the tracker.
  • Forward-backward error and median flow are used alone as a fast short-term tracker.
  • Other detectors. Later long-term trackers replace the fern cascade with a correlation filter (for example a kernelized correlation filter as the tracker and a separate detector for recovery) or with a learned network such as siamese tracking with a global search.
  • Tracking by detection. Tracking by detection with a pretrained detector replaces the online learning for known object classes.

When to use it

Use TLD when one object must be followed for a long time, can disappear and come back, and no detector for its class exists in advance. Its learned detector is what lets it recover. For short sequences without occlusion, a kernelized correlation filter or a KLT tracker is simpler and faster. For object classes that a pretrained detector knows, tracking by detection is usually more reliable.

Pitfalls

  • Learning from an occluder. The trajectory stays reliable until the tracker fails. If a partial occluder still gives a good median motion, the model learns the occluder for a few frames. A strong failure test, such as the median forward-backward error, reduces this.
  • Thresholds copied from the paper. The relative similarity of an exact match is 1/(1+S−)1 / (1 + S^-), so its scale depends on how similar the negatives are. Calibrate θNN\theta_{\text{NN}} and the core threshold on your data, as the example shows.
  • Similar distractors. The N-expert assumes one object. A second object of the same kind gives negatives that look like positives, and the detector can lose both.
  • Small objects. With few pixels, the fern comparisons and the 15×1515 \times 15 patches carry little information, and the variance test can reject the object itself after a change of light.
  • Number of windows. The scanning grid grows with the image size and the number of scales; on large frames the detector dominates the cost.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

tracking_learning_detection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tracking-learning-detection/. The authors are listed in prov/CCWPAB.jsonl.

"""Tracking-learning-detection (Kalal, Mikolajczyk and Matas), a compact
version: a median flow tracker, a cascaded detector (variance filter, fern
ensemble, nearest neighbor classifier), an integrator, and P-N learning.

Images are lists of rows of gray values, indexed img[v][u]; the center of
pixel (u, v) is the point (u, v). A box is (x1, y1, x2, y2) with x1 < x2 and
y1 < y2 in the same coordinates; an integer box holds the pixels with
x1 <= u < x2 and y1 <= v < y2.
"""

import math
import random

PATCH = 15  # side of the normalized patches of the nearest neighbor classifier


# ---------------------------------------------------------------- basics

def sample(img, u, v):
    """Bilinear sample at a real point, indices clamped."""
    h, w = len(img), len(img[0])
    u0, v0 = math.floor(u), math.floor(v)
    fu, fv = u - u0, v - v0

    def at(vv, uu):
        return img[min(max(vv, 0), h - 1)][min(max(uu, 0), w - 1)]

    return ((1 - fv) * ((1 - fu) * at(v0, u0) + fu * at(v0, u0 + 1))
            + fv * ((1 - fu) * at(v0 + 1, u0) + fu * at(v0 + 1, u0 + 1)))


def iou(a, b):
    """Intersection over union of two boxes."""
    w = min(a[2], b[2]) - max(a[0], b[0])
    h = min(a[3], b[3]) - max(a[1], b[1])
    if w <= 0 or h <= 0:
        return 0.0
    inter = w * h
    return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)


def median(xs):
    s = sorted(xs)
    n = len(s)
    return s[n // 2] if n % 2 else (s[n // 2 - 1] + s[n // 2]) / 2


def ncc(a, b):
    """Normalized cross-correlation of two equal-length vectors, in [-1, 1]."""
    ma, mb = sum(a) / len(a), sum(b) / len(b)
    da = [x - ma for x in a]
    db = [x - mb for x in b]
    na = math.sqrt(sum(x * x for x in da))
    nb = math.sqrt(sum(x * x for x in db))
    if na == 0 or nb == 0:
        return 0.0
    return sum(x * y for x, y in zip(da, db)) / (na * nb)


def patch(img, box, side=PATCH):
    """The box resampled to side x side values, then shifted to zero mean and
    scaled to unit norm, so that the dot product of two patches is their NCC."""
    x1, y1, x2, y2 = box
    sw, sh = (x2 - x1) / side, (y2 - y1) / side
    vals = [sample(img, x1 - 0.5 + (i + 0.5) * sw, y1 - 0.5 + (j + 0.5) * sh)
            for j in range(side) for i in range(side)]
    m = sum(vals) / len(vals)
    d = [x - m for x in vals]
    n = math.sqrt(sum(x * x for x in d))
    return [x / n for x in d] if n > 0 else [0.0] * len(d)


# ---------------------------------------------------------------- median flow

def lk(img_a, img_b, p, r=3, iters=15, tol=0.01):
    """Translation of the window of radius r around p from img_a to img_b,
    by Lucas-Kanade steps with the gradient of img_a. None if the window
    has no texture."""
    offs = [(i, j) for j in range(-r, r + 1) for i in range(-r, r + 1)]
    grads, vals = [], []
    gxx = gxy = gyy = 0.0
    for i, j in offs:
        u, v = p[0] + i, p[1] + j
        gx = (sample(img_a, u + 1, v) - sample(img_a, u - 1, v)) / 2
        gy = (sample(img_a, u, v + 1) - sample(img_a, u, v - 1)) / 2
        grads.append((gx, gy))
        vals.append(sample(img_a, u, v))
        gxx += gx * gx
        gxy += gx * gy
        gyy += gy * gy
    det = gxx * gyy - gxy * gxy
    if det <= 1e-9 * (gxx + gyy) ** 2 or gxx + gyy == 0:
        return None
    d = [0.0, 0.0]
    for _ in range(iters):
        bx = by = 0.0
        for (i, j), (gx, gy), a in zip(offs, grads, vals):
            e = a - sample(img_b, p[0] + i + d[0], p[1] + j + d[1])
            bx += gx * e
            by += gy * e
        sx = (gyy * bx - gxy * by) / det
        sy = (gxx * by - gxy * bx) / det
        d[0] += sx
        d[1] += sy
        if math.hypot(sx, sy) < tol:
            break
    return (d[0], d[1])


def median_flow(img_a, img_b, box, grid=10, fail=10.0, fb_max=5.0):
    """Move the box from img_a to img_b. Returns the new box, or None if the
    tracker fails: no point can be tracked, the median forward-backward error
    is above fb_max, or the median distance of the point displacements from
    the median displacement is above `fail`."""
    x1, y1, x2, y2 = box
    pts = [(x1 + (x2 - x1) * (i + 1) / (grid + 1) - 0.5, y1 + (y2 - y1) * (j + 1) / (grid + 1) - 0.5)
           for j in range(grid) for i in range(grid)]  # @line L1
    good = []
    for p in pts:
        d = lk(img_a, img_b, p)  # @line L2
        if d is None:
            continue
        q = (p[0] + d[0], p[1] + d[1])
        back = lk(img_b, img_a, q)
        if back is None:
            continue
        fb = math.hypot(d[0] + back[0], d[1] + back[1])  # @line L3
        pa = [sample(img_a, p[0] + i, p[1] + j) for j in range(-3, 4) for i in range(-3, 4)]
        pb = [sample(img_b, q[0] + i, q[1] + j) for j in range(-3, 4) for i in range(-3, 4)]
        good.append((p, q, fb, ncc(pa, pb)))
    if not good:
        return None
    mfb = median([g[2] for g in good])
    mncc = median([g[3] for g in good])
    kept = [g for g in good if g[2] <= mfb and g[3] >= mncc]  # @line L4
    if not kept or mfb > fb_max:
        return None
    dx = median([q[0] - p[0] for p, q, _, _ in kept])  # @line L5
    dy = median([q[1] - p[1] for p, q, _, _ in kept])
    residual = median([math.hypot(q[0] - p[0] - dx, q[1] - p[1] - dy) for p, q, _, _ in good])
    if residual > fail:  # @line L6
        return None
    ratios = []
    for i in range(len(kept)):
        for j in range(i + 1, len(kept)):
            da = math.dist(kept[i][0], kept[j][0])
            if da > 0:
                ratios.append(math.dist(kept[i][1], kept[j][1]) / da)
    s = median(ratios) if ratios else 1.0  # @line L7
    cx, cy = (x1 + x2) / 2 + dx, (y1 + y2) / 2 + dy
    hw, hh = (x2 - x1) * s / 2, (y2 - y1) * s / 2
    return (cx - hw, cy - hh, cx + hw, cy + hh)


# ---------------------------------------------------------------- detector

def integral_images(img):
    """Summed tables of the values and of their squares, of size (H+1) x (W+1)."""
    h, w = len(img), len(img[0])
    s = [[0.0] * (w + 1) for _ in range(h + 1)]
    s2 = [[0.0] * (w + 1) for _ in range(h + 1)]
    for v in range(h):
        row = row2 = 0.0
        for u in range(w):
            row += img[v][u]
            row2 += img[v][u] ** 2
            s[v + 1][u + 1] = s[v][u + 1] + row
            s2[v + 1][u + 1] = s2[v][u + 1] + row2
    return s, s2


def box_variance(tables, box):
    """The variance of the pixels of an integer box, in O(1)."""
    s, s2 = tables
    x1, y1, x2, y2 = box
    n = (x2 - x1) * (y2 - y1)
    t = s[y2][x2] - s[y1][x2] - s[y2][x1] + s[y1][x1]
    t2 = s2[y2][x2] - s2[y1][x2] - s2[y2][x1] + s2[y1][x1]
    return t2 / n - (t / n) ** 2


def scan_windows(width, height, bw, bh, scales=(1 / 1.2, 1.0, 1.2), step=0.1):
    """All integer boxes of the scaled sizes, shifted by a tenth of their size."""
    out = []
    for sc in scales:
        w, h = max(4, round(bw * sc)), max(4, round(bh * sc))
        su, sv = max(1, round(step * w)), max(1, round(step * h))
        for y in range(0, height - h + 1, sv):
            for x in range(0, width - w + 1, su):
                out.append((x, y, x + w, y + h))
    return out


class Ferns:
    """An ensemble of ferns; each fern compares `depth` pairs of points."""

    def __init__(self, count=10, depth=10, seed=0):
        rng = random.Random(seed)
        self.pairs = [[((rng.random(), rng.random()), (rng.random(), rng.random())) for _ in range(depth)]
                      for _ in range(count)]
        self.pos = [[0] * (1 << depth) for _ in range(count)]
        self.neg = [[0] * (1 << depth) for _ in range(count)]

    def codes(self, img, box, rng=None, noise=0.0):
        """One code per fern: bit k is 1 if the pixel nearest to the first point
        of pair k is brighter than the pixel nearest to the second point. With
        an rng, Gaussian noise of standard deviation `noise` is added to each
        value that is read."""
        x1, y1, x2, y2 = box
        w, h = x2 - x1 - 1, y2 - y1 - 1
        hi, wi = len(img) - 1, len(img[0]) - 1

        def px(fx, fy):
            u, v = math.floor(x1 + fx * w + 0.5), math.floor(y1 + fy * h + 0.5)
            value = img[min(max(v, 0), hi)][min(max(u, 0), wi)]
            return value + rng.gauss(0, noise) if rng else value

        out = []
        for fern in self.pairs:
            code = 0
            for (ax, ay), (bx, by) in fern:
                code = 2 * code + (1 if px(ax, ay) > px(bx, by) else 0)
            out.append(code)
        return out

    def posterior(self, codes):
        total = 0.0
        for f, c in enumerate(codes):
            p, n = self.pos[f][c], self.neg[f][c]
            total += p / (p + n) if p + n else 0.0
        return total / len(codes)

    def update(self, codes, label):
        for f, c in enumerate(codes):
            if label:
                self.pos[f][c] += 1
            else:
                self.neg[f][c] += 1


class NearestNeighbor:
    """Positive and negative patch sets with the similarities of TLD."""

    def __init__(self):
        self.pos, self.neg = [], []

    @staticmethod
    def sim(a, b):
        """0.5 (NCC + 1) of two normalized patches, in [0, 1]."""
        return 0.5 * (sum(x * y for x, y in zip(a, b)) + 1)

    def relative(self, p):
        """S+ / (S+ + S-) over all positives and negatives."""
        sp = max((self.sim(p, q) for q in self.pos), default=0.0)
        sn = max((self.sim(p, q) for q in self.neg), default=0.0)
        return sp / (sp + sn) if sp + sn else 0.0

    def conservative(self, p):
        """As relative, but S+ uses only the older half of the positives."""
        old = self.pos[:max(1, (len(self.pos) + 1) // 2)]
        sp = max((self.sim(p, q) for q in old), default=0.0)
        sn = max((self.sim(p, q) for q in self.neg), default=0.0)
        return sp / (sp + sn) if sp + sn else 0.0


# ---------------------------------------------------------------- TLD

class TLD:
    """The whole method. theta_nn is the threshold of the nearest neighbor
    classifier on the relative similarity, theta_core the threshold on the
    conservative similarity that makes the trajectory reliable, and margin the
    lambda of the model update."""

    def __init__(self, img, box, theta_nn=0.55, theta_core=0.55, margin=0.1, seed=0):
        self.theta_nn, self.theta_core, self.margin = theta_nn, theta_core, margin
        self.rng = random.Random(seed)
        self.box, self.valid = box, True
        b = tuple(int(round(t)) for t in box)
        self.windows = scan_windows(len(img[0]), len(img), b[2] - b[0], b[3] - b[1])
        self.var_min = 0.5 * box_variance(integral_images(img), b)
        self.ferns = Ferns(seed=seed)
        self.nn = NearestNeighbor()
        self.nn.pos.append(patch(img, box))
        self.learn(img, box, first=True)

    def detect(self, img):
        """The cascade: variance, ferns, nearest neighbor. Returns the boxes
        that pass all three stages."""
        tables = integral_images(img)
        found = []
        for w in self.windows:
            if box_variance(tables, w) < self.var_min:  # @line L8
                continue
            if self.ferns.posterior(self.ferns.codes(img, w)) <= 0.5:  # @line L9
                continue
            if self.nn.relative(patch(img, w)) > self.theta_nn:  # @line L10
                found.append(w)
        return found

    def warp(self, w):
        """A random small change of the box: shift up to 1 percent of its size
        and scale by up to 1 percent."""
        bw, bh = w[2] - w[0], w[3] - w[1]
        du, dv = self.rng.uniform(-0.01, 0.01) * bw, self.rng.uniform(-0.01, 0.01) * bh
        s = 1 + self.rng.uniform(-0.01, 0.01)
        cx, cy = (w[0] + w[2]) / 2 + du, (w[1] + w[3]) / 2 + dv
        return (cx - bw * s / 2, cy - bh * s / 2, cx + bw * s / 2, cy + bh * s / 2)

    def learn(self, img, box, first=False):
        """P-N learning around a reliable box."""
        tables = integral_images(img)
        near = sorted(self.windows, key=lambda w: -iou(w, box))[:10]
        for w in near:  # @line L16
            for _ in range(20 if first else 10):
                codes = self.ferns.codes(img, self.warp(w), self.rng, 5.0)
                if first or self.ferns.posterior(codes) <= 0.5:
                    self.ferns.update(codes, True)
        p = patch(img, box)
        if not first and self.nn.relative(p) - self.theta_nn < self.margin:  # @line L17
            self.nn.pos.append(p)
        for w in self.windows:  # @line L18
            if iou(w, box) >= 0.2 or box_variance(tables, w) < self.var_min:
                continue
            codes = self.ferns.codes(img, w)
            if first or self.ferns.posterior(codes) > 0.5:
                self.ferns.update(codes, False)
                q = patch(img, w)
                if self.nn.relative(q) > self.theta_nn - self.margin:  # @line L19
                    self.nn.neg.append(q)

    def update(self, prev, img):
        """Process the next frame. Returns the box, or None if the object is
        not visible."""
        tracked = median_flow(prev, img, self.box) if self.box else None  # @line L11
        clusters = []
        for w in self.detect(img):  # @line L12
            for c in clusters:
                if iou(c[0], w) > 0.5:
                    c.append(w)
                    break
            else:
                clusters.append([w])
        candidates = [tuple(sum(m[k] for m in c) / len(c) for k in range(4)) for c in clusters]
        if tracked is not None:
            candidates.append(tracked)
        if not candidates:
            self.box, self.valid = None, False
            return None
        conf = [self.nn.conservative(patch(img, c)) for c in candidates]
        best = max(range(len(candidates)), key=lambda i: conf[i])  # @line L13
        from_tracker = tracked is not None and best == len(candidates) - 1
        self.valid = (from_tracker and self.valid) or conf[best] > self.theta_core  # @line L14
        self.box = candidates[best]
        if self.valid:  # @line L15
            self.learn(img, self.box)
        return self.box
test_tracking_learning_detection.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tracking-learning-detection/. The authors are listed in prov/CCWPAB.jsonl.

import math
import random

from tracking_learning_detection import (
    TLD,
    Ferns,
    NearestNeighbor,
    box_variance,
    integral_images,
    iou,
    median_flow,
    patch,
)


def texture(seed, k, lo, hi):
    rng = random.Random(seed)
    blobs = [(rng.uniform(lo, hi), rng.uniform(lo, hi), rng.uniform(1.5, 3), rng.uniform(-80, 80))
             for _ in range(k)]

    def f(u, v):
        return 120 + sum(a * math.exp(-((u - x) ** 2 + (v - y) ** 2) / (2 * s * s)) for x, y, s, a in blobs)

    return f


def render(f, n, du=0.0, dv=0.0):
    return [[f(u - du, v - dv) for u in range(n)] for v in range(n)]


def test_iou():
    assert abs(iou((0, 0, 2, 2), (1, 1, 3, 3)) - 1 / 7) < 1e-12
    assert abs(iou((0, 0, 2, 2), (1, 0, 3, 2)) - 1 / 3) < 1e-12
    assert iou((0, 0, 2, 2), (2, 0, 4, 2)) == 0.0
    assert iou((1, 2, 5, 7), (1, 2, 5, 7)) == 1.0


def test_box_variance_by_integral_images():
    rng = random.Random(1)
    img = [[rng.randint(0, 255) for _ in range(13)] for _ in range(9)]
    tables = integral_images(img)
    for _ in range(50):
        x1, x2 = sorted(rng.sample(range(14), 2))
        y1, y2 = sorted(rng.sample(range(10), 2))
        vals = [img[v][u] for v in range(y1, y2) for u in range(x1, x2)]
        mean = sum(vals) / len(vals)
        want = sum((t - mean) ** 2 for t in vals) / len(vals)
        assert abs(box_variance(tables, (x1, y1, x2, y2)) - want) < 1e-6


def test_median_flow_follows_a_translation():
    f = texture(2, 60, -4, 40)
    a, b = render(f, 36), render(f, 36, 1.5, -1.0)
    box = (10, 12, 24, 26)
    got = median_flow(a, b, box)
    want = (11.5, 11.0, 25.5, 25.0)
    assert max(abs(s - t) for s, t in zip(got, want)) < 0.1


def test_median_flow_ignores_an_occluded_part():
    f = texture(3, 60, -4, 40)
    a, b = render(f, 36), render(f, 36, 1.0, 1.0)
    for v in range(10, 30):
        for u in range(8, 15):
            b[v][u] = 40.0  # a flat occluder over the left part of the box
    got = median_flow(a, b, (10, 12, 24, 26))
    want = (11.0, 13.0, 25.0, 27.0)
    assert max(abs(s - t) for s, t in zip(got, want)) < 0.3


def test_nearest_neighbor_similarities():
    rng = random.Random(4)
    img = [[rng.uniform(0, 255) for _ in range(20)] for _ in range(20)]
    p = patch(img, (2, 2, 12, 12))
    flipped = patch([[255 - t for t in row] for row in img], (2, 2, 12, 12))
    assert abs(NearestNeighbor.sim(p, p) - 1) < 1e-12
    assert abs(NearestNeighbor.sim(p, flipped)) < 1e-12
    nn = NearestNeighbor()
    nn.pos.append(p)
    assert nn.relative(patch(img, (8, 8, 18, 18))) == 1.0  # no negatives yet
    q = patch(img, (8, 8, 18, 18))
    nn.neg.append(q)
    assert abs(nn.relative(p) - 1 / (1 + NearestNeighbor.sim(p, q))) < 1e-12
    nn.pos.append(q)  # a newer positive is not used by the conservative similarity
    assert nn.relative(q) == 0.5
    assert nn.conservative(q) < 0.5


def test_fern_posterior_counts():
    ferns = Ferns(count=2, depth=2, seed=0)
    ferns.update([1, 3], True)
    ferns.update([1, 2], False)
    ferns.update([1, 3], True)
    assert ferns.posterior([1, 3]) == (2 / 3 + 1) / 2
    assert ferns.posterior([0, 2]) == 0.0


def test_tracks_loses_and_finds_the_target_again():
    n, side = 40, 10
    rng = random.Random(2)
    pix = [[rng.choice([30, 90, 160, 230]) for _ in range(side)] for _ in range(side)]
    back = render(texture(1, 12, 0, n), n)

    def frame(pos):
        img = [row[:] for row in back]
        for v in range(28, 38):  # two textured distractors
            for u in range(2, 14):
                img[v][u] = 40 if (u // 2 + v // 2) % 2 else 220
        for v in range(2, 14):
            for u in range(28, 38):
                img[v][u] = 40 if (u // 3) % 2 else 220
        if pos:
            for j in range(side):
                for i in range(side):
                    img[pos[1] + j][pos[0] + i] = pix[j][i]
        else:
            for v in range(3, 25):  # a flat occluder over the target
                for u in range(9, 31):
                    img[v][u] = 128.0
        return img

    truth = [(6 + 2 * t, 4 + t) for t in range(5)] + [None, None, (26, 22), (25, 24)]
    frames = [frame(p) for p in truth]
    tld = TLD(frames[0], (6, 4, 16, 14))
    for k in range(1, len(frames)):
        box = tld.update(frames[k - 1], frames[k])
        if truth[k] is None:
            assert box is None and not tld.valid
        else:
            x, y = truth[k]
            assert iou(box, (x, y, x + side, y + side)) > 0.85
            assert tld.valid

History

Kalal, Matas and Mikolajczyk introduced P-N learning, the training of a detector from positive and negative structural constraints, at CVPR 2010, and the forward-backward error with the median flow tracker at ICPR 2010. The full system, with the detector cascade of variance filter, random ferns (in the style of Özuysal and colleagues) and nearest neighbor classifier, and the analysis of P-N learning as a linear dynamical system, appeared in IEEE TPAMI in 2012. Early demonstrations of the system used the name Predator, which is why the name is still used for it. Its split into tracking, learning and detection shaped later long-term trackers, which often keep the idea of a short-term tracker plus a re-detector.

References

  1. Zdenek Kalal, Krystian Mikolajczyk and Jiri Matas, Tracking-learning-detection, IEEE Transactions on Pattern Analysis and Machine Intelligence 34(7), 2012, 1409 to 1422, Section 4.2 (stability of P-N learning, page 1413), Section 4.3 (simulated experts), Sections 5.1 to 5.6 (object model, detector cascade, median flow with failure detection, integrator, P-expert and N-expert, pages 1415 to 1418)
  2. Zdenek Kalal, Krystian Mikolajczyk and Jiri Matas, Forward-backward error, automatic detection of tracking failures, International Conference on Pattern Recognition (ICPR), 2010, 2756 to 2759, the whole paper (the forward-backward error and the median flow tracker)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example