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.
- Solves
- Visual object tracking
- 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
- Model
- Real RAM
- Properties
- randomizednot exactnot iterativenot localonline
- Evidence
- Proof sketchCode in 1 languages
- 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 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 has its center at the point .
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 pixels. The similarity of two patches is , 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 , let and be its largest similarity to a positive and to a negative patch, and its largest similarity to the older half of the positives. The relative similarity is and the conservative similarity is .
The algorithm
MEDIAN-FLOW(F_prev, F, B)- 1
place a grid of points in B - 2
track each point from F_prev to F with Lucas-Kanade, and back again - 3
e_i ← the forward-backward error of point i; c_i ← the NCC of the windows around it - 4
keep the points with e_i ≤ median(e) and c_i ≥ median(c); fail if none or median(e) > e_max - 5
d ← the median displacement of the kept points - 6
fail if the median distance of all displacements from d is above 10 pixels - 7
s ← the median ratio of point distances after and before; return B moved by d and scaled by s DETECT(F)- 8
reject each scanning window whose gray value variance is below half that of B₀ - 9
reject each remaining window whose mean fern posterior is not above 1/2 - 10
return the remaining windows with S^r > θ_NN TLD-FRAME(F_prev, F)- 11
T ← MEDIAN-FLOW(F_prev, F, B) if B exists - 12
group the windows of DETECT(F) into clusters of overlap above 1/2, one box per cluster - 13
B ← the candidate (T or a cluster box) with the largest S^c, or NONE if there is no candidate - 14
reliable ← (B = T and reliable) or S^c(B) > θ_core - 15
if reliable then LEARN(F, B) LEARN(F, B)- 16
for the 10 windows closest to B: train the ferns on warped copies labeled positive - 17
add the patch of B to the positives if S^r - θ_NN < λ - 18
for each window with overlap below 0.2 that passes the variance test and the ferns: train the ferns on it labeled negative - 19
add 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 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 pixel pairs inside the window, which gives a -bit code. It stores, for each code, the number of positive and of negative training windows with that code, and its posterior is . 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 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 is smaller than , so the model stays small. The paper uses and reports similar results from 0.5 to 0.7.
Integrator and reliability. The integrator outputs the most confident candidate by , or nothing if neither the tracker nor the detector gives a box. A trajectory becomes reliable when 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 grid of points, 10 ferns of 10 comparisons on unblurred pixels, warps by shift, scale and noise only (no rotation), , 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 , and . Then and . A patch identical to a positive has , but if one negative has , its relative similarity is only . 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 , , , and ; the last one is on an occluder. The medians of the coordinates are and , so the box moves by 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 . The background is smooth, with two textured distractors, a checkerboard and vertical stripes. The object is a square of random gray values from , first at , moving by per frame. There are 2,891 scanning windows at the three scales , 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 | reliable | |
|---|---|---|---|---|---|
| 1 | 0.999 | 0.618 | yes | ||
| 4 | 0.995 | 0.618 | yes | ||
| 5 | hidden | none | no | ||
| 6 | hidden | none | no | ||
| 7 | 0.907 | 0.617 | yes | ||
| 8 | 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. , and are in , grows with and falls with , and .
- 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 , and they go to 0 if and only if both eigenvalues of are below 1 in absolute value. If all four qualities equal , this holds exactly when .
- 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 and the same sum of , with . For the integer box with pixels,
and the same holds for . Then the variance of the pixels of is with both means read from these sums.
Proof. counts every pixel with and . Subtracting and removes the pixels with or , but removes the pixels with and twice, and adding restores them once. So each pixel of is counted once and every other pixel zero times. The variance identity is with . Four reads from each table and a few operations give the value, so line L8 costs per window after work to build the tables.
Claim 2: median flow is exact for a translation and robust to a minority of bad points
Let the points of line L1 move to , and let be the median (taken coordinate by coordinate) of the displacements of the kept points of line L4.
(a) If every kept point has , then line L5 gives , and every distance ratio of line L7 is 1, so the box moves by and keeps its size.
(b) If the points obey a similarity, with a rotation and , then every ratio equals , so line L7 gives exactly .
(c) If more than half of the kept displacements have their first coordinate in an interval , then the first coordinate of is in ; the same holds for the second coordinate.
Proof. (a) The median of equal numbers is that number, and . (b) because a rotation keeps lengths. (c) Sort the values as . Fewer than values are outside , so fewer than are below , and therefore for every . In the same way fewer than are above , so for every . The median is for odd , or the mean of and for even ; in both cases the values used have indices in , so they are in , and so is their mean.
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 , (zero mean, unit norm), by the Cauchy-Schwarz inequality, so , with 1 only for and 0 only for . Let and be the largest similarities to a positive and to a negative patch. Then grows with and falls with , and .
Proof. The first part is Cauchy-Schwarz, with equality only for parallel vectors; unit norm leaves . has the derivative in and in . The conservative similarity uses , the largest similarity to the older half of the positives, which is a subset, so and by monotony .
A consequence that the example on the page shows: a patch identical to a positive has , so can be well below 1 when one negative is a little similar. The threshold must be set with this in mind.
Claim 4: the ensemble posterior is an average of empirical frequencies
For fern and code with positive and negative training counts, line L9 uses (0 if ), and the ensemble value is the mean over the ferns. Each , so the mean is in ; a window is passed if the mean is above . 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 and be the numbers of false positives and false negatives of the classifier after iteration . The P-expert outputs correct and false positive labels, the N-expert correct and false negative labels, and every label changes the classifier's decision on that example. Assume the four quality measures are constant:
Then obeys with
and for every start if and only if both eigenvalues of have absolute value below 1.
Proof. A correct positive label fixes a false negative and a false positive label creates a false positive, so and . From the definitions, , , and . Substituting gives the two rows of . For a linear recursion , and if and only if the spectral radius of is below 1 (write in Jordan form: a block with eigenvalue has entries , which go to 0 if and only if ).
The symmetric case. With , every entry of is , so the eigenvalues are and (the all-ones matrix has eigenvectors and with eigenvalues 2 and 0). The errors go to 0 if and only if : 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 per frame. The variance test costs per window, so in all. A window that reaches the ferns costs for the comparisons, and a window that reaches the nearest neighbor stage costs for the similarities to all model patches. Median flow costs 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 points these cost , which is below when is at most the number of pixels in the window of a point, as for a grid with windows. Learning visits every window once more, at the same cost per window. So a frame costs in the worst case and 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 for the integral images, for the window list, for the model patches, and for the fern tables, which hold two counters for each of the 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 , so its scale depends on how similar the negatives are. Calibrate 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 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.
# 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag CCWPAB Edit this page History Report an error Markdown