Algorithm Search⌘K

Algorithmresearch

Siamese fully convolutional tracking

Also called SiamFC.

Track by cross-correlating features of the target exemplar with features of a larger search region, both from one network trained offline.

Time
Θ(N (S (F + C Z M) + U² M)) worst · average · best
Space
Θ(C (X + Z) + S M + U² M) extra
Where
C = the number of feature channels; F = the cost of the features of one search crop; M = the number of cells of the score map; N = the number of frames; S = the number of scales searched; U = the upsampling factor; X = the number of cells of the search feature map; Z = the number of cells of the exemplar feature map
Properties
deterministicnot exactnot iterativelocalonline
Origin
Luca Bertinetto, Jack Valmadre, João F. Henriques, Andrea Vedaldi, Philip H. S. Torr, 2016

Siamese fully convolutional tracking follows one object through a video by comparing a picture of the object, the exemplar, with every position of a larger search region in each new frame. Both pictures go through the same function φ\varphi, a network trained in advance on many videos, and the comparison is a cross-correlation of the two feature maps. The result is a score map, and the tracker moves to its maximum. Because the network has no padding and only shifts and local operations, one correlation gives exactly the similarity of every shifted sub-window, so the search costs about as much as one pass of the network over the search region. Bertinetto, Valmadre, Henriques, Vedaldi and Torr published the method in 2016. They never updated the exemplar during tracking, and they reported 86 frames per second with 3 scales on one GPU. The network is outside this page: the page implements the correlation, the loss and the steps from the score map to the new box, with a small fixed embedding in place of the trained one.

In plain words

Take a photo of the object in the first frame. In each new frame, cut a larger piece around where the object was. Now slide the photo over that piece and, at each position, measure how much the two agree. The position with the best agreement is where the object went. Doing this on raw pixels fails when the light or the pose changes, so both pictures are first turned into feature maps by a network that has learned, from thousands of videos, what makes two views of one object look alike. The trick is that the sliding can be done after the network, on the feature maps, so the network looks at the search piece only once. A gentle preference for small moves and a few zoom levels finish the tracker.

The problem

Given the first frame and a box (x1,y1,x2,y2)(x_1, y_1, x_2, y_2) around the target, output a box in each later frame (the visual object tracking problem). Pixel (u,v)(u, v) has its center at the point (u,v)(u, v).

The method learns a function f(z,x)f(z, x) that is high when the exemplar image zz and a candidate image xx of the same size show the same object. It takes the form

f(z,x)=φ(z)⋆φ(x)+b,f(z, x) = \varphi(z) \star \varphi(x) + b,

where φ\varphi maps an image to CC feature maps, ⋆\star is the cross-correlation summed over the channels, and bb is a real bias. When xx is larger than zz, the output is not one number but a score map: entry τ\tau is the similarity of zz to the sub-window of xx at offset kφτk_\varphi \tau, where kφk_\varphi is the total stride of φ\varphi. This holds when φ\varphi is fully convolutional, which means that it commutes with translation:

φ(Lkφτx)=Lτ φ(x),(Lτx)[u]=x[u−τ].\varphi(L_{k_\varphi \tau} x) = L_\tau\, \varphi(x), \qquad (L_\tau x)[u] = x[u - \tau].

Training uses pairs of crops from labelled videos: an exemplar centered on the target and a search image centered on the target in another frame at most TT frames away. A cell uu of the score map gets the label y[u]=+1y[u] = +1 if kφ∣u−c∣≤Rk_\varphi |u - c| \le R, where cc is the center of the map, and −1-1 otherwise. The loss of one cell with score vv is the logistic loss

ℓ(y,v)=log⁡(1+e−yv),\ell(y, v) = \log\big(1 + e^{-y v}\big),

and the loss of a map is the mean over its cells, with the positive and the negative cells weighted so that each class has the same total weight. The weights of φ\varphi and bb are found by stochastic gradient descent on this loss.

Crops include context. If the target has size w×hw \times h, let p=(w+h)/4p = (w + h) / 4; the exemplar is the square with the area of (w+2p)×(h+2p)(w + 2p) \times (h + 2p), rescaled to a fixed size, and the search crop is a larger square with the same center and the same scale factor.

The algorithm

  1. TRAIN(pairs (z, x) from labelled videos)
  2. 1y ← the label map: +1 within radius R of the center, -1 elsewhere
  3. 2L ← the weighted mean of ℓ(y[u], v[u]) with v = φ(z) ⋆ φ(x) + b
  4. 3take one step of stochastic gradient descent on L for the weights of φ and b
  5. TRACK(frames, box)
  6. 4φz ← φ(the exemplar crop of the first frame) ▷ computed once
  7. 5for each scale factor s_i do x_i ← the search crop at the old center, side scaled by s · s_i
  8. 6v_i ← φz ⋆ φ(x_i)
  9. 7multiply the peak of v_i by the scale penalty if s_i ≠ 1
  10. 8i* ← the scale with the largest penalized peak; V ← v_{i*} upsampled by U
  11. 9(j, k) ← the maximum of (1 - λ) V' + λ H, with V' = V scaled to [0, 1] and H a cosine window
  12. 10move the center by the offset of (j, k) from the center of V, times the stride and the pixel size
  13. 11s ← s · ((1 - γ) + γ s_{i*}) ▷ damped scale update
  14. 12return the box with the new center and size

The settings of Bertinetto and colleagues are these. The exemplar crop is 127×127127 \times 127 and the search crop 255×255255 \times 255 pixels, and the context is chosen so that s(w+2p)×s(h+2p)=1272s(w + 2p) \times s(h + 2p) = 127^2. The parts of a crop outside the image are filled with the mean color. φ\varphi has five convolutional layers similar to the first part of the network of Krizhevsky and colleagues, with max pooling after the first two, ReLU after all but the last, no padding, and a total stride of 8. It gives a 6×6×1286 \times 6 \times 128 map for the exemplar and 22×22×12822 \times 22 \times 128 for the search crop, so the score map is 17×1717 \times 17. They train on the ImageNet Video data, 4417 videos with more than 2 million boxes, for 50 epochs of 50,000 pairs. During tracking they upsample the score map from 17×1717 \times 17 to 272×272272 \times 272 with bicubic interpolation, search 5 scales 1.025{−2,−1,0,1,2}1.025^{\{-2, -1, 0, 1, 2\}} (or 3 in a faster version), and update the scale by linear interpolation with the factor γ=0.35\gamma = 0.35. The search region is about four times the previous size of the target. The paper adds the cosine window and penalizes changes of scale; the weight λ\lambda and the penalty value are not given in the text.

Example

One correlation by hand. Take one channel in one dimension, φ(z)=(1,2)\varphi(z) = (1, 2), φ(x)=(0,1,2,1,0)\varphi(x) = (0, 1, 2, 1, 0) and b=0b = 0. The score map has 5−2+1=45 - 2 + 1 = 4 entries:

v=(1⋅0+2⋅1,  1⋅1+2⋅2,  1⋅2+2⋅1,  1⋅1+2⋅0)=(2,5,4,1).v = (1 \cdot 0 + 2 \cdot 1,\; 1 \cdot 1 + 2 \cdot 2,\; 1 \cdot 2 + 2 \cdot 1,\; 1 \cdot 1 + 2 \cdot 0) = (2, 5, 4, 1).

The maximum is at offset 1, where the window of xx is (1,2)(1, 2), the same as the exemplar. Each entry is the inner product of φ(z)\varphi(z) with one window of φ(x)\varphi(x), which is what Claim 1 of the proof says in general. Now extend the search map to (0,1,2,1,0,5,5)(0, 1, 2, 1, 0, 5, 5). The window (5,5)(5, 5) scores 1⋅5+2⋅5=151 \cdot 5 + 2 \cdot 5 = 15 and wins, although it does not look like (1,2)(1, 2). A plain inner product prefers strong features. A trained φ\varphi has to make background features small, and a fixed φ\varphi does not.

The loss. On the 17×1717 \times 17 map with stride 8 and R=16R = 16, the positive cells are those within 2 cells of the center: 13 cells. With all scores 0 the balanced loss is log⁡2≈0.693\log 2 \approx 0.693. A score v=2v = 2 costs log⁡(1+e−2)≈0.127\log(1 + e^{-2}) \approx 0.127 on a positive cell and log⁡(1+e2)≈2.127\log(1 + e^{2}) \approx 2.127 on a negative cell.

Tracking with fixed features. The implementation uses four 3×33 \times 3 gradient filters with a ReLU as φ\varphi (stride 1, no padding), an exemplar crop of 20×2020 \times 20, a search crop of 44×4444 \times 44, a 25×2525 \times 25 score map, 3 scales 1.025{−1,0,1}1.025^{\{-1, 0, 1\}} with the penalty 0.97, γ=0.35\gamma = 0.35, λ=0.25\lambda = 0.25 and bicubic upsampling by U=4U = 4. These are this page's choices. The frames are 48×4848 \times 48, with a smooth background and a 10×1010 \times 10 target of random gray levels that moves by (2.3,1.6)(2.3, 1.6) pixels per frame, rendered at subpixel positions. The first box is (10,12,20,22)(10, 12, 20, 22), so the context side is 20 and one crop pixel is one image pixel. Over 7 frames the center errors are 0.34, 0.25, 0.25, 0.25, 0.21, 0.08 and 0.37 pixel. The size is not stable: in frames 5 and 6 the smaller scale wins after the penalty (in frame 5 the peaks are 13.0113.01, 12.5812.58 and 11.5111.51 million for the scales 1/1.0251/1.025, 1 and 1.0251.025, and 13.01×0.97=12.6213.01 \times 0.97 = 12.62 beats 12.5812.58), and the width goes from 10 to 9.92 and 9.83, then back to 9.92. With a target that shrinks by 4% per frame, the width goes 10, 10, 9.83, 9.67, 9.51, 9.35, 9.19 while the true width goes down to 7.51. The scale search moves the right way but lags, because gradient features change little with a small zoom. A trained embedding is what makes the scores sensitive to scale.

Correctness

The full proof is in proofs/correctness.md. It shows these facts.

  • Theorem: one correlation scores every sub-window. If every layer of φ\varphi is a local operation with no padding and a stride, then entry τ\tau of φ(z)⋆φ(x)+b\varphi(z) \star \varphi(x) + b equals ⟨φ(z),φ(xτ)⟩+b\langle \varphi(z), \varphi(x_\tau) \rangle + b, where xτx_\tau is the sub-window at offset kφτk_\varphi \tau. Padding breaks this.
  • Theorem: the logistic loss. ℓ(y,v)\ell(y, v) is strictly convex in vv, decreasing in the margin yvy v, equal to log⁡2\log 2 at v=0v = 0, with derivative −y/(1+eyv)-y / (1 + e^{y v}). It is convex in the scores, not in the weights of the network.
  • Theorem: upsampling. The maximum of a bilinear upsampling is always at a node of the original map, so it gives no finer position; bicubic interpolation with the Keys kernel keeps the nodes, reproduces quadratics, and can put the peak between nodes.
  • Theorem: the step from the map to the box. The offset of the peak from the center of the map, times the stride and the pixel size, is the displacement of the exemplar window, and the damped scale update multiplies the size by a factor between 1 and the chosen scale.

Nothing proves that the maximum of the score map is on the target. That depends on the learned embedding, and the accuracy figures of the paper are benchmark results, not theorems.

Proof: Why one cross-correlation of feature maps scores every sub-window, why the logistic loss is a sound training target, and why bicubic upsampling can move the peak between grid nodesfull

Notation as on the page. Siamese tracking as a whole is a heuristic: nothing proves that the maximum of the score map is on the target, because that depends on what the network learned. What can be proved is that the score map computes what the method says it computes, that the loss has the stated properties, and that the steps from the map to the new box are exact. The claims below do that.

Claim 1: the score map equals the similarity of every translated sub-window

Let φ\varphi be a stack of layers, each of the form

yc[p]=σ(∑c′∑q∈QKcc′[q] xc′[kp+q]+bc),y_c[p] = \sigma\Big( \sum_{c'} \sum_{q \in Q} K_{c c'}[q]\, x_{c'}[k p + q] + b_c \Big),

where QQ is a finite window of offsets, k≥1k \ge 1 is the stride of the layer, σ\sigma is applied point by point, and pp runs over the positions where kp+qk p + q is inside the input for every q∈Qq \in Q (no padding). Let kφk_\varphi be the product of the strides. For an exemplar zz and a search image xx, let xτx_\tau be the sub-window of xx with the size of zz whose top left corner is at kφτk_\varphi \tau. Then for every position τ\tau of the score map of line L6,

(φ(z)⋆φ(x)+b)[τ]=⟨φ(z),φ(xτ)⟩+b,\big(\varphi(z) \star \varphi(x) + b\big)[\tau] = \langle \varphi(z), \varphi(x_\tau) \rangle + b,

where ⋆\star is the cross-correlation summed over channels and ⟨⋅,⋅⟩\langle \cdot, \cdot \rangle is the sum of all products of matching entries.

Proof. First one layer. Let x′=x[ ⋅+kτ ]x' = x[\,\cdot + k \tau\,] be the input shifted by kτk \tau. Then y′[p]=σ(∑K[q] x[kp+kτ+q]+b)=y[p+τ]y'[p] = \sigma(\sum K[q]\, x[k p + k \tau + q] + b) = y[p + \tau], for every pp that is valid for x′x'; these p+τp + \tau are valid for xx, because the window of x′x' is inside xx. So shifting the input by kτk \tau shifts the output by τ\tau, and cutting a sub-window of the input cuts the matching sub-window of the output. By induction over the layers, a shift of kφτk_\varphi \tau at the input is a shift of τ\tau at the output of φ\varphi, so φ(xτ)\varphi(x_\tau) is the part of φ(x)\varphi(x) that starts at τ\tau and has the size of φ(z)\varphi(z). The cross-correlation at τ\tau is ∑c∑aφ(z)c[a] φ(x)c[a+τ]\sum_c \sum_a \varphi(z)_c[a]\, \varphi(x)_c[a + \tau], which is the inner product of φ(z)\varphi(z) with that part. □\square

This is equation (1) of Bertinetto and colleagues, a function that commutes with translation by multiples of its stride, applied to the score. The test test_score_map_equals_every_sub_window checks it entry by entry with the fixed features of the implementation, where kφ=1k_\varphi = 1.

Why padding breaks it. With zero padding, the output of φ(xτ)\varphi(x_\tau) near its border uses zeros, while the matching part of φ(x)\varphi(x) uses the real pixels around the sub-window. The two differ, so the map is no longer the similarity of the sub-windows. This is why the network has no padding.

Translation of the search image. A corollary: if the search image is shifted by kφτk_\varphi \tau, the score map is shifted by τ\tau on the positions where both maps are defined. The test test_shift_of_the_search_image_shifts_the_score_map checks this.

Cost. Scoring the MM sub-windows one by one costs MM evaluations of φ\varphi on a window of the size of zz. The cross-correlation costs one evaluation of φ\varphi on xx, in which every overlapping part is computed once, and Θ(CZM)\Theta(C Z M) for the products, with CC channels and ZZ cells in φ(z)\varphi(z).

Claim 2: the logistic loss is convex, has the stated gradient, and rewards the right sign

For y∈{+1,−1}y \in \{+1, -1\} and real vv, ℓ(y,v)=log⁡(1+e−yv)\ell(y, v) = \log(1 + e^{-y v}) satisfies:

(a) ℓ(y,0)=log⁡2\ell(y, 0) = \log 2 and ℓ(y,v)=ℓ(−y,−v)\ell(y, v) = \ell(-y, -v);

(b) ∂ℓ/∂v=−y/(1+eyv)\partial \ell / \partial v = -y / (1 + e^{y v}), which has the sign of −y-y and absolute value below 1;

(c) ∂2ℓ/∂v2=eyv/(1+eyv)2>0\partial^2 \ell / \partial v^2 = e^{y v} / (1 + e^{y v})^2 > 0, so ℓ\ell is strictly convex in vv;

(d) ℓ\ell is strictly decreasing in the margin yvy v, goes to 0 as yv→∞y v \to \infty, and is at least −yv-y v.

Proof. (a) is direct. (b) ddvlog⁡(1+e−yv)=−ye−yv1+e−yv=−yeyv+1\frac{d}{dv} \log(1 + e^{-y v}) = \frac{-y e^{-y v}}{1 + e^{-y v}} = \frac{-y}{e^{y v} + 1}. (c) Differentiate again: ddv−y1+eyv=y2eyv(1+eyv)2\frac{d}{dv} \frac{-y}{1 + e^{y v}} = \frac{y^2 e^{y v}}{(1 + e^{y v})^2} and y2=1y^2 = 1. (d) The function m↦log⁡(1+e−m)m \mapsto \log(1 + e^{-m}) has derivative −1/(1+em)<0-1/(1 + e^m) < 0, and log⁡(1+e−m)≥log⁡(e−m)=−m\log(1 + e^{-m}) \ge \log(e^{-m}) = -m. □\square

The map loss of line L2 is a weighted mean of such terms with positive weights, so it is also convex in the scores; with the balanced weights (half of the weight on the positive cells, half on the negative cells) it equals log⁡2\log 2 when all scores are 0. The loss is convex in the scores, not in the weights of the network, so training finds a local minimum at best. The implementation computes ℓ\ell as m+log⁡(1+e−m)m + \log(1 + e^{-m}) for m=−yv>0m = -y v > 0, the same value without overflow.

The label map of line L1. With stride kk and radius RR, a cell uu is positive if k∣u−c∣≤Rk |u - c| \le R. For the 17×1717 \times 17 map, k=8k = 8 and R=16R = 16, the positive cells are the lattice points with ∣u−c∣≤2|u - c| \le 2: the center, 4 at distance 1, 4 at distance 2\sqrt 2 and 4 at distance 2, so 13 cells. The test checks this count.

Claim 3: bilinear upsampling cannot move the peak; bicubic upsampling can

(a) On a grid cell, the bilinear interpolant attains its maximum at a corner, so the maximum of a bilinear upsampling of a map is a value of the map at a node.

(b) With the cubic convolution kernel of Keys with a=−12a = -\frac12, the weights of the four taps at −1,0,1,2-1, 0, 1, 2 for a point t∈[0,1)t \in [0, 1) are

w−1=−12t(1−t)2,w0=32t3−52t2+1,w1=12t+2t2−32t3,w2=−12t2(1−t),w_{-1} = -\tfrac12 t (1 - t)^2, \quad w_0 = \tfrac32 t^3 - \tfrac52 t^2 + 1, \quad w_1 = \tfrac12 t + 2 t^2 - \tfrac32 t^3, \quad w_2 = -\tfrac12 t^2 (1 - t),

and they satisfy ∑dwd=1\sum_d w_d = 1, ∑dwd d=t\sum_d w_d\, d = t, ∑dwd d2=t2\sum_d w_d\, d^2 = t^2. So the interpolant is equal to the map at the nodes and reproduces every polynomial of degree at most 2 in each coordinate, away from the border where the taps are clamped.

Proof. (a) For fixed bb, f(a,b)f(a, b) is affine in aa, so its maximum over a∈[0,1]a \in [0, 1] is at a=0a = 0 or a=1a = 1. On each of those two edges ff is affine in bb, so the maximum is at a corner. (b) The weights follow from k(s)=32∣s∣3−52∣s∣2+1k(s) = \frac32 |s|^3 - \frac52 |s|^2 + 1 for ∣s∣≤1|s| \le 1 and k(s)=−12∣s∣3+52∣s∣2−4∣s∣+2k(s) = -\frac12 |s|^3 + \frac52 |s|^2 - 4 |s| + 2 for 1<∣s∣<21 < |s| < 2, evaluated at t+1t + 1, tt, 1−t1 - t and 2−t2 - t and expanded. Adding the four polynomials, the coefficients of t3t^3, t2t^2 and tt cancel and the constant is 1. For the first moment, −w−1+w1+2w2=(12t−t2+12t3)+(12t+2t2−32t3)+(−t2+t3)=t-w_{-1} + w_1 + 2 w_2 = (\frac12 t - t^2 + \frac12 t^3) + (\frac12 t + 2 t^2 - \frac32 t^3) + (-t^2 + t^3) = t. For the second, w−1+w1+4w2=(−12t+t2−12t3)+(12t+2t2−32t3)+(−2t2+2t3)=t2w_{-1} + w_1 + 4 w_2 = (-\frac12 t + t^2 - \frac12 t^3) + (\frac12 t + 2 t^2 - \frac32 t^3) + (-2 t^2 + 2 t^3) = t^2. At t=0t = 0 the weights are (0,1,0,0)(0, 1, 0, 0), so nodes are kept. In two dimensions the interpolant is the product of two such one-dimensional rules, so it reproduces products of such polynomials. □\square

So the bicubic map can have its maximum between nodes, which gives a position finer than one cell; the test test_bicubic_upsampling_keeps_nodes_and_quadratics checks the nodes, a quadratic and a peak that moves toward a large neighbor. That the finer position is closer to the truth is a heuristic: it holds when the score is smooth near its peak.

Claim 4: the map position gives the displacement, and the scale update is a damped step

Let the search crop have nxn_x cells per side and the exemplar crop nzn_z, both centered on the old position, with crop pixels of size ρ\rho image pixels, and let the score map be upsampled by the factor UU to positions j/Uj / U. A map position j/Uj / U (in each coordinate) puts the exemplar window at search offset kφj/Uk_\varphi j / U, whose center is at kφj/U+(nz−1)/2k_\varphi j / U + (n_z - 1) / 2 in the crop, while the old center is at (nx−1)/2(n_x - 1) / 2. So the displacement of line L10 is

d=ρ(kφjU−nx−nz2)=ρ kφ(jU−c),c=nx−nz2kφ,d = \rho \Big( k_\varphi \frac{j}{U} - \frac{n_x - n_z}{2} \Big) = \rho\, k_\varphi \Big( \frac{j}{U} - c \Big), \qquad c = \frac{n_x - n_z}{2 k_\varphi},

and cc is the center of the map when the map has (nx−nz)/kφ+1(n_x - n_z) / k_\varphi + 1 cells per side. With kφ=1k_\varphi = 1 this is the formula in the code.

For line L11, if the chosen scale factor is ss and the damping is γ\gamma, the size is multiplied by (1−γ)+γs(1 - \gamma) + \gamma s, which lies between 1 and ss. A constant true scale change gg per frame is then followed with a lag; the size never jumps by more than the largest scale factor in one frame. □\square

What is not claimed

The score map is a correct similarity of every sub-window, but nothing proves that the largest similarity is the target. A fixed embedding, like the gradient features of the implementation, gives high scores to any region with strong edges, as the example on the page shows. The learned embedding is trained to avoid this on the training videos, which is an empirical result. The cosine window and the scale penalty are heuristics that prefer small changes. The exemplar is never updated, so a target that changes its appearance can be lost.

Complexity

Let FF be the cost of φ\varphi on one search crop, CC the number of channels, ZZ the number of cells of φ(z)\varphi(z), XX of φ(x)\varphi(x), and MM of the score map. One scale costs FF for the features and Θ(CZM)\Theta(C Z M) for the correlation. The upsampling and the window cost Θ(U2M)\Theta(U^2 M). A frame costs Θ(S(F+CZM)+U2M)\Theta(S (F + C Z M) + U^2 M), and NN frames cost NN times that. The exemplar features are computed once. The extra space is Θ(C(X+Z))\Theta(C (X + Z)) for the feature maps, Θ(SM)\Theta(S M) for the score maps and Θ(U2M)\Theta(U^2 M) for the upsampled map. For a trained network, FF dominates. The cost of the network is outside this page and depends on its layers. Scoring the MM sub-windows one by one would cost MM passes of the network over an exemplar-sized window, and the fully convolutional form removes that factor.

Properties

  • No update online. The exemplar features of the first frame are kept for the whole video. The tracker cannot drift by learning the background, and it cannot adapt to a new appearance either.
  • Fully convolutional. The score map is exact for every shifted window, and the search region can have any size.
  • Translation equivariant. A shift of the search image by a multiple of the stride shifts the score map. There is no learned bias toward the center of the crop. The cosine window adds one by design.
  • Deterministic. Tracking has no random steps.
  • Coarse grid. The score map has one cell per stride of the network, 8 pixels in the paper. The upsampling makes the position finer.
  • Fixed aspect ratio. The size changes only by a common factor, so the box keeps its first aspect ratio.

Variants and improvements

  • Correlation filter layer. Valmadre and colleagues put a differentiable correlation filter on the exemplar features and trained through it (2017). The exemplar can then be updated online cheaply.
  • Region proposals. Later Siamese trackers add a second branch that predicts box offsets and sizes at each cell, as in object detection. This replaces the scale search and gives any aspect ratio.
  • Deeper backbones. Deeper networks need padding, which breaks the exact equivariance. One fix is to vary the position of the target during training so that the network does not learn a bias toward the center.
  • Distractor-aware training. Add hard negative pairs from other objects of the same class, so that similar objects score lower.
  • Masks. A third branch can output a segmentation mask of the target for each cell.
  • Templates updated online. Keep a small set of exemplars, or a running mean of the exemplar features, to follow changes of appearance.

When to use it

Use a Siamese tracker when you track one object of any class in real time, and a GPU and a trained network are available. It suits short-term tracking where the object changes slowly and does not leave the frame for long. For a tracker with no trained network, use the kernelized correlation filter. It learns online and runs on a CPU. For long sequences where the object leaves and comes back, add a detector, as tracking-learning-detection does. For many objects of known classes, use tracking by detection.

Pitfalls

  • Padding in the network. With zero padding the score map is not the similarity of the sub-windows, and the network can learn to prefer the center of the crop. Without padding, every layer shrinks the map.
  • Wrong map-to-image scale. The displacement is the map offset times the stride times the size of a crop pixel in the image. Forgetting either factor moves the box by the wrong amount.
  • Bilinear upsampling. It never moves the maximum off a node, so it adds cost and no accuracy. Use bicubic interpolation or fit a parabola around the peak.
  • Unnormalized scores. The plain inner product grows with the strength of the features, so a bright or highly textured region can win, as the example shows. A trained network learns to avoid this only for scenes like its training data.
  • Training data from the benchmark. If the network is trained on videos from the test benchmark, the results are not fair. The VOT rules forbid this, and Bertinetto and colleagues trained on ImageNet Video for this reason.
  • Scale drift. Small wrong scale choices add up. The penalty and the damping slow this down but do not stop it, and the example shows the size moving on a target of constant size.

Implementations

The trained network is outside this page, and no page trains a network. The Python code implements the cross-correlation of feature maps of line L6 with a fixed embedding: four 3×33 \times 3 gradient filters with a ReLU, stride 1 and no padding. Any function with the same signature can replace features. The code also gives the label map and the balanced logistic loss of lines L1 and L2, the crop with context, the scale search with the penalty, bicubic upsampling, the cosine window and the damped scale update. Of line L3, only the step for the bias bb is implemented, since every score has the derivative 1 in bb. The step for the weights of the network is not. The tests check the equality of the score map with the similarity of every sub-window, the shift of the score map, the loss and its gradient, the 13 positive cells, the upsampling, and tracking a moving and a shrinking target.

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.

siamese_tracking.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/siamese-tracking/. The authors are listed in prov/RDHCZ9.jsonl.
"""Siamese tracking by cross-correlation of feature maps.

The embedding here is fixed: four 3 x 3 gradient filters with a ReLU, stride 1
and no padding. A trained network is outside this page; any function with the
same signature (image in, list of channel maps out, no padding) can replace
`features`, and the rest of the code does not change.

Images are lists of rows, img[v][u], and pixel (u, v) has its center at (u, v).
"""

import math

KERNELS = [
    [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]],  # horizontal gradient
    [[1, 0, -1], [2, 0, -2], [1, 0, -1]],
    [[-1, -2, -1], [0, 0, 0], [1, 2, 1]],  # vertical gradient
    [[1, 2, 1], [0, 0, 0], [-1, -2, -1]],
]


def features(img):
    """phi(img): valid 3 x 3 correlation with each kernel, then ReLU. Stride 1."""
    h, w = len(img), len(img[0])
    out = []
    for k in KERNELS:
        ch = []
        for v in range(h - 2):
            r0, r1, r2 = img[v], img[v + 1], img[v + 2]
            row = []
            for u in range(w - 2):
                s = (k[0][0] * r0[u] + k[0][1] * r0[u + 1] + k[0][2] * r0[u + 2]
                     + k[1][0] * r1[u] + k[1][1] * r1[u + 1] + k[1][2] * r1[u + 2]
                     + k[2][0] * r2[u] + k[2][1] * r2[u + 1] + k[2][2] * r2[u + 2])
                row.append(s if s > 0 else 0.0)
            ch.append(row)
        out.append(ch)
    return out


def xcorr(fz, fx, bias=0.0):
    """Score map v[i][j] = sum over c, a, b of fz[c][a][b] * fx[c][i + a][j + b] + bias."""
    hz, wz = len(fz[0]), len(fz[0][0])
    hx, wx = len(fx[0]), len(fx[0][0])
    out = [[bias] * (wx - wz + 1) for _ in range(hx - hz + 1)]
    for cz, cx in zip(fz, fx):
        for a in range(hz):
            zrow = cz[a]
            terms = [(b, t) for b, t in enumerate(zrow) if t != 0.0]
            for i in range(hx - hz + 1):
                xrow = cx[i + a]
                orow = out[i]
                for j in range(wx - wz + 1):
                    s = 0.0
                    for b, t in terms:
                        s += t * xrow[j + b]
                    orow[j] += s
    return out


def score(z, x, bias=0.0):
    """f(z, x) = phi(z) * phi(x) + b, one value per translated sub-window of x."""
    return xcorr(features(z), features(x), bias)


def logistic_loss(y, v):
    """l(y, v) = log(1 + exp(-y v)), computed without overflow."""
    m = -y * v
    return m + math.log1p(math.exp(-m)) if m > 0 else math.log1p(math.exp(m))


def logistic_grad(y, v):
    """d l / d v = -y / (1 + exp(y v))."""
    m = y * v
    if m >= 0:
        e = math.exp(-m)
        return -y * e / (1 + e)
    return -y / (1 + math.exp(m))


def label_map(size, radius, stride):
    """y[u] = +1 if stride * |u - c| <= radius, else -1, on a size x size map."""
    c = (size - 1) / 2
    return [[1 if stride * math.hypot(i - c, j - c) <= radius else -1  # @line L1
             for j in range(size)] for i in range(size)]


def map_loss(y, v, balance=True):
    """Mean logistic loss over the map; with balance, positives and negatives weigh half each."""
    cells = [(a, b) for ra, rb in zip(y, v) for a, b in zip(ra, rb)]
    npos = sum(1 for a, _ in cells if a > 0)
    nneg = len(cells) - npos
    total = 0.0
    for a, b in cells:  # @line L2
        if balance:
            wgt = 0.5 / npos if a > 0 else 0.5 / nneg
        else:
            wgt = 1.0 / len(cells)
        total += wgt * logistic_loss(a, b)
    return total


def bias_step(y, v, bias, rate):
    """One gradient step of line L3 for the bias alone; dv[u]/db = 1 for every cell.

    The step for the weights of phi needs the network and is outside this page.
    """
    cells = [(a, b) for ra, rb in zip(y, v) for a, b in zip(ra, rb)]
    npos = sum(1 for a, _ in cells if a > 0)
    nneg = len(cells) - npos
    grad = sum((0.5 / npos if a > 0 else 0.5 / nneg) * logistic_grad(a, b) for a, b in cells)
    return bias - rate * grad, grad  # @line L3


def bilinear(img, x, y, fill):
    h, w = len(img), len(img[0])
    if x < 0 or y < 0 or x > w - 1 or y > h - 1:
        return fill
    u0, v0 = min(int(x), w - 2), min(int(y), h - 2)
    a, b = x - u0, y - v0
    r0, r1 = img[v0], img[v0 + 1]
    return ((1 - a) * (1 - b) * r0[u0] + a * (1 - b) * r0[u0 + 1]
            + (1 - a) * b * r1[u0] + a * b * r1[u0 + 1])


def crop(img, center, side, out, fill):
    """Resample the square of the given side around center to out x out pixels."""
    step = side / out
    cx, cy = center
    h = (out - 1) / 2
    return [[bilinear(img, cx + (j - h) * step, cy + (i - h) * step, fill)
             for j in range(out)] for i in range(out)]


def cubic_weights(t):
    """Keys cubic convolution weights (a = -0.5) for the taps at -1, 0, 1, 2, with 0 <= t < 1."""
    a = -0.5

    def k(s):
        s = abs(s)
        if s <= 1:
            return (a + 2) * s ** 3 - (a + 3) * s ** 2 + 1
        if s < 2:
            return a * s ** 3 - 5 * a * s ** 2 + 8 * a * s - 4 * a
        return 0.0

    return [k(t + 1), k(t), k(1 - t), k(2 - t)]


def upsample(m, factor):
    """Bicubic upsampling of a square map; output pixel k sits at k / factor.

    Bilinear upsampling would be useless here: its maximum is always at a node
    of the original grid, so it cannot move the peak by less than one cell.
    """
    n = len(m)
    size = (n - 1) * factor + 1
    taps = []
    for k in range(size):
        i0 = min(k // factor, n - 1)
        wts = cubic_weights(k / factor - i0)
        taps.append([(min(max(i0 + d, 0), n - 1), w) for d, w in zip((-1, 0, 1, 2), wts)])
    rows = [[sum(w * row[j] for j, w in tj) for tj in taps] for row in m]
    return [[sum(w * rows[i][c] for i, w in ti) for c in range(size)] for ti in taps]


def hann(n):
    if n == 1:
        return [[1.0]]
    """Outer product of two Hann windows; 1 at the center, 0 at the border."""
    h = [0.5 - 0.5 * math.cos(2 * math.pi * k / (n - 1)) for k in range(n)]
    return [[a * b for b in h] for a in h]


def context_side(w, h):
    """Side of the square with the area of (w + 2p) x (h + 2p), p = (w + h) / 4."""
    p = (w + h) / 4
    return math.sqrt((w + 2 * p) * (h + 2 * p))


class SiameseTracker:
    def __init__(self, img, box, exemplar=20, search=44, scales=(1 / 1.025, 1.0, 1.025),
                 scale_penalty=0.97, damping=0.35, window=0.25, up=4):
        x1, y1, x2, y2 = box
        self.center = ((x1 + x2) / 2 - 0.5, (y1 + y2) / 2 - 0.5)  # pixel centers at integers
        self.size = (x2 - x1, y2 - y1)
        self.ez, self.ex = exemplar, search
        self.scales, self.penalty, self.damping = scales, scale_penalty, damping
        self.window, self.up = window, up
        side = context_side(*self.size)
        fill = sum(map(sum, img)) / (len(img) * len(img[0]))
        self.fz = features(crop(img, self.center, side, exemplar, fill))  # @line L4
        self.side = side
        n = search - exemplar + 1
        self.cos = hann((n - 1) * up + 1)

    def update(self, img):
        fill = sum(map(sum, img)) / (len(img) * len(img[0]))
        maps = []
        for s in self.scales:  # @line L5
            side = self.side * s * self.ex / self.ez
            x = crop(img, self.center, side, self.ex, fill)
            v = xcorr(self.fz, features(x))  # @line L6
            peak = max(map(max, v))
            maps.append((peak * (1.0 if s == 1.0 else self.penalty), s, v, side))  # @line L7
        _, s_best, v, side = max(maps, key=lambda t: t[0])  # @line L8
        big = upsample(v, self.up)
        lo = min(map(min, big))
        hi = max(map(max, big))
        span = hi - lo if hi > lo else 1.0
        best, bi, bj = -1.0, 0, 0
        for i, (row, crow) in enumerate(zip(big, self.cos)):  # @line L9
            for j, (t, c) in enumerate(zip(row, crow)):
                val = (1 - self.window) * (t - lo) / span + self.window * c
                if val > best:
                    best, bi, bj = val, i, j
        c = (len(big) - 1) / 2
        px = side / self.ex  # image pixels per search-crop pixel; the stride is 1
        du, dv = (bj - c) / self.up * px, (bi - c) / self.up * px  # @line L10
        self.center = (self.center[0] + du, self.center[1] + dv)
        f = (1 - self.damping) + self.damping * s_best  # @line L11
        self.side *= f
        self.size = (self.size[0] * f, self.size[1] * f)
        w, h = self.size
        cx, cy = self.center[0] + 0.5, self.center[1] + 0.5
        return (cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2)  # @line L12
test_siamese_tracking.py 176 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/siamese-tracking/. The authors are listed in prov/RDHCZ9.jsonl.

import math
import random

from siamese_tracking import (
    SiameseTracker,
    bias_step,
    context_side,
    features,
    label_map,
    logistic_grad,
    logistic_loss,
    map_loss,
    score,
    upsample,
    xcorr,
)


def random_image(seed, h, w):
    rng = random.Random(seed)
    return [[rng.uniform(0, 255) for _ in range(w)] for _ in range(h)]


def test_score_map_equals_every_sub_window():
    z = random_image(1, 6, 6)
    x = random_image(2, 11, 13)
    v = score(z, x, bias=0.5)
    assert (len(v), len(v[0])) == (6, 8)
    for i in range(6):
        for j in range(8):
            sub = [row[j:j + 6] for row in x[i:i + 6]]
            one = score(z, sub, bias=0.5)
            assert len(one) == 1 and len(one[0]) == 1
            assert abs(one[0][0] - v[i][j]) < 1e-6 * max(1.0, abs(v[i][j]))


def test_shift_of_the_search_image_shifts_the_score_map():
    z = random_image(3, 5, 5)
    big = random_image(4, 16, 16)
    x = [row[0:12] for row in big[0:12]]
    shifted = [row[3:15] for row in big[2:14]]  # x moved by (-3, -2)
    v, w = score(z, x), score(z, shifted)
    for i in range(len(w) - 2):
        for j in range(len(w[0]) - 3):
            assert abs(w[i][j] - v[i + 2][j + 3]) < 1e-6 * max(1.0, abs(w[i][j]))


def test_features_are_nonnegative_and_valid_size():
    img = random_image(5, 7, 9)
    f = features(img)
    assert len(f) == 4 and len(f[0]) == 5 and len(f[0][0]) == 7
    assert min(t for ch in f for row in ch for t in row) >= 0.0


def test_self_match_peaks_at_the_true_offset():
    big = random_image(6, 20, 20)
    z = [row[7:14] for row in big[5:12]]
    v = xcorr(features(z), features(big))
    best = max((t, i, j) for i, row in enumerate(v) for j, t in enumerate(row))
    assert best[1:] == (5, 7)


def test_logistic_loss_and_gradient():
    assert abs(logistic_loss(1, 0.0) - math.log(2)) < 1e-15
    assert abs(logistic_loss(1, 2.0) - logistic_loss(-1, -2.0)) < 1e-15
    assert abs(logistic_loss(1, 800.0)) < 1e-300 + 1e-12
    assert abs(logistic_loss(-1, 800.0) - 800.0) < 1e-9
    for y in (1, -1):
        for v in (-3.0, -0.2, 0.0, 0.7, 4.0):
            h = 1e-6
            num = (logistic_loss(y, v + h) - logistic_loss(y, v - h)) / (2 * h)
            assert abs(num - logistic_grad(y, v)) < 1e-6


def test_label_map_and_balanced_loss():
    y = label_map(17, 16, 8)  # positive within 2 cells of the center
    assert sum(t > 0 for row in y for t in row) == 13
    assert y[8][8] == 1 and y[8][10] == 1 and y[9][10] == -1
    zero = [[0.0] * 17 for _ in range(17)]
    assert abs(map_loss(y, zero) - math.log(2)) < 1e-12
    good = [[3.0 * t for t in row] for row in y]
    assert map_loss(y, good) < map_loss(y, zero) < map_loss(y, [[-t for t in row] for row in good])
    rng = random.Random(9)
    v = [[rng.uniform(-2, 2) for _ in range(17)] for _ in range(17)]
    b, grad = bias_step(y, v, 0.0, 0.5)
    h = 1e-6
    num = (map_loss(y, [[t + h for t in row] for row in v]) - map_loss(y, [[t - h for t in row] for row in v])) / (2 * h)
    assert abs(num - grad) < 1e-6
    assert map_loss(y, [[t + b for t in row] for row in v]) < map_loss(y, v)


def test_bicubic_upsampling_keeps_nodes_and_quadratics():
    m = [[2 * i + 3 * j + 0.5 * i * i for j in range(7)] for i in range(7)]
    u = upsample(m, 4)
    assert len(u) == 25
    assert max(abs(u[4 * a][4 * b] - m[a][b]) for a in range(7) for b in range(7)) < 1e-12
    inner = range(4, 21)  # away from the clamped border
    assert max(abs(u[a][b] - (a / 2 + 3 * b / 4 + 0.5 * (a / 4) ** 2)) for a in inner for b in inner) < 1e-9
    peak = [[0.0, 0.0, 0.0], [0.0, 1.0, 0.8], [0.0, 0.0, 0.0]]
    big = upsample(peak, 8)
    best = max((t, i, j) for i, row in enumerate(big) for j, t in enumerate(row))
    assert best[1] == 8 and 8 < best[2] < 16  # the peak moves between the nodes


def test_context_side():
    assert context_side(10, 10) == 20.0
    assert abs(context_side(8, 4) - math.sqrt(14 * 10)) < 1e-12


def blobs(seed, k, lo, hi, amp):
    rng = random.Random(seed)
    return [(rng.uniform(lo, hi), rng.uniform(lo, hi), rng.uniform(2, 4), rng.uniform(-amp, amp))
            for _ in range(k)]


def test_tracks_a_moving_target():
    n, side = 48, 10
    rng = random.Random(7)
    pix = [[rng.choice([40, 110, 180, 250]) for _ in range(side)] for _ in range(side)]
    back = blobs(8, 15, 0, n, 25)
    base = [[120 + sum(a * math.exp(-((u - x) ** 2 + (v - y) ** 2) / (2 * s * s)) for x, y, s, a in back)
             for u in range(n)] for v in range(n)]

    def frame(px, py):
        img = [row[:] for row in base]
        for v in range(n):
            for u in range(n):
                a, b = u - px, v - py  # target pixel coordinates, bilinear
                if -1 < a < side and -1 < b < side:
                    i0, j0 = math.floor(b), math.floor(a)
                    fa, fb = a - j0, b - i0
                    tot = 0.0
                    for di, wi in ((0, 1 - fb), (1, fb)):
                        for dj, wj in ((0, 1 - fa), (1, fa)):
                            ii, jj = i0 + di, j0 + dj
                            t = pix[ii][jj] if 0 <= ii < side and 0 <= jj < side else img[v][u]
                            tot += wi * wj * t
                    img[v][u] = tot
        return img

    path = [(10 + 2.3 * t, 12 + 1.6 * t) for t in range(8)]
    tracker = SiameseTracker(frame(*path[0]), (10, 12, 20, 22))
    for px, py in path[1:]:
        box = tracker.update(frame(px, py))
        cx, cy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2
        assert math.hypot(cx - (px + side / 2), cy - (py + side / 2)) < 0.6
        assert 9.0 < box[2] - box[0] < 11.0


def test_scale_search_follows_a_shrinking_target():
    n, side = 48, 10
    rng = random.Random(7)
    pix = [[rng.choice([40, 110, 180, 250]) for _ in range(side)] for _ in range(side)]

    def frame(cx, cy, size):  # nearest-pixel rendering of the target, scaled about its center
        img = [[120.0] * n for _ in range(n)]
        for v in range(n):
            for u in range(n):
                a = (u - cx) / size * side + side / 2 - 0.5
                b = (v - cy) / size * side + side / 2 - 0.5
                if -0.5 <= a < side - 0.5 and -0.5 <= b < side - 0.5:
                    img[v][u] = pix[min(side - 1, int(b + 0.5))][min(side - 1, int(a + 0.5))]
        return img

    tracker = SiameseTracker(frame(20, 20, 10), (15, 15, 25, 25), scales=(1 / 1.05, 1.0, 1.05))
    widths = [10.0]
    for t in range(1, 8):
        cx, cy = 20 + 0.7 * t, 20 + 0.5 * t
        box = tracker.update(frame(cx, cy, 10 * 0.96 ** t))
        widths.append(box[2] - box[0])
        assert math.hypot((box[0] + box[2]) / 2 - (cx + 0.5), (box[1] + box[3]) / 2 - (cy + 0.5)) < 1.0
    assert all(b <= a + 1e-12 for a, b in zip(widths, widths[1:]))
    assert widths[-1] < 9.5

History

Siamese networks, two copies of one network with shared weights whose outputs are compared, go back to the signature verification work of Bromley and colleagues in the early 1990s. They were later used for face verification, for patch descriptors and for one-shot recognition. In tracking, the usual approach before 2016 was to learn a model online from the video itself, as in tracking-learning-detection and the kernelized correlation filter, or to fine-tune a pretrained network during tracking, which was slow. In 2016 Bertinetto, Valmadre, Henriques, Vedaldi and Torr trained a fully convolutional Siamese network offline on ImageNet Video and tracked with no online learning. They reported results competitive with the best trackers of the time on the OTB and VOT benchmarks at more than real-time speed. The same year Held, Thrun and Savarese regressed the box directly with a network, and Tao, Gavves and Smeulders matched sampled candidate boxes with a Siamese network. Later Siamese trackers added correlation filter layers, region proposal branches, deeper backbones and masks.

References

  1. Luca Bertinetto, Jack Valmadre, João F. Henriques, Andrea Vedaldi and Philip H. S. Torr, Fully-convolutional Siamese networks for object tracking, ECCV 2016 Workshops, Lecture Notes in Computer Science 9914, 2016, 850 to 865 (also arXiv 1606.09549), Sections 2.1, 2.2, 2.4 and 4.1 of the arXiv version (equations 1 to 7, Table 1, the tracking settings and the frame rates)
  2. Yi Wu, Jongwoo Lim and Ming-Hsuan Yang, Object tracking benchmark, IEEE Transactions on Pattern Analysis and Machine Intelligence 37(9), 2015, 1834 to 1848, the whole paper (the benchmark sequences and the success plot built from the overlap of boxes)
  3. Matej Kristan, Jiri Matas, Aleš Leonardis, Tomáš Vojíř, Roman Pflugfelder, Gustavo Fernández, Georg Nebehay, Fatih Porikli and Luka Čehovin, A novel performance evaluation methodology for single-target trackers, IEEE Transactions on Pattern Analysis and Machine Intelligence 38(11), 2016, 2137 to 2155, the whole paper (the VOT evaluation with accuracy and robustness)

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
  • a scene preset for the example