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.
- Solves
- Visual object tracking
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactnot iterativelocalonline
- Evidence
- Proof sketchCode in 1 languages
- 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 , 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 around the target, output a box in each later frame (the visual object tracking problem). Pixel has its center at the point .
The method learns a function that is high when the exemplar image and a candidate image of the same size show the same object. It takes the form
where maps an image to feature maps, is the cross-correlation summed over the channels, and is a real bias. When is larger than , the output is not one number but a score map: entry is the similarity of to the sub-window of at offset , where is the total stride of . This holds when is fully convolutional, which means that it commutes with translation:
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 frames away. A cell of the score map gets the label if , where is the center of the map, and otherwise. The loss of one cell with score is the logistic loss
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 and are found by stochastic gradient descent on this loss.
Crops include context. If the target has size , let ; the exemplar is the square with the area of , rescaled to a fixed size, and the search crop is a larger square with the same center and the same scale factor.
The algorithm
TRAIN(pairs (z, x) from labelled videos)- 1
y ← the label map: +1 within radius R of the center, -1 elsewhere - 2
L ← the weighted mean of ℓ(y[u], v[u]) with v = φ(z) ⋆ φ(x) + b - 3
take one step of stochastic gradient descent on L for the weights of φ and b TRACK(frames, box)- 4
φz ← φ(the exemplar crop of the first frame) ▷ computed once - 5
for each scale factor s_i do x_i ← the search crop at the old center, side scaled by s · s_i - 6
v_i ← φz ⋆ φ(x_i) - 7
multiply the peak of v_i by the scale penalty if s_i ≠ 1 - 8
i* ← the scale with the largest penalized peak; V ← v_{i*} upsampled by U - 9
(j, k) ← the maximum of (1 - λ) V' + λ H, with V' = V scaled to [0, 1] and H a cosine window - 10
move the center by the offset of (j, k) from the center of V, times the stride and the pixel size - 11
s ← s · ((1 - γ) + γ s_{i*}) ▷ damped scale update - 12
return the box with the new center and size
The settings of Bertinetto and colleagues are these. The exemplar crop is and the search crop pixels, and the context is chosen so that . The parts of a crop outside the image are filled with the mean color. 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 map for the exemplar and for the search crop, so the score map is . 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 to with bicubic interpolation, search 5 scales (or 3 in a faster version), and update the scale by linear interpolation with the factor . 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 and the penalty value are not given in the text.
Example
One correlation by hand. Take one channel in one dimension, , and . The score map has entries:
The maximum is at offset 1, where the window of is , the same as the exemplar. Each entry is the inner product of with one window of , which is what Claim 1 of the proof says in general. Now extend the search map to . The window scores and wins, although it does not look like . A plain inner product prefers strong features. A trained has to make background features small, and a fixed does not.
The loss. On the map with stride 8 and , the positive cells are those within 2 cells of the center: 13 cells. With all scores 0 the balanced loss is . A score costs on a positive cell and on a negative cell.
Tracking with fixed features. The implementation uses four gradient filters with a ReLU as (stride 1, no padding), an exemplar crop of , a search crop of , a score map, 3 scales with the penalty 0.97, , and bicubic upsampling by . These are this page's choices. The frames are , with a smooth background and a target of random gray levels that moves by pixels per frame, rendered at subpixel positions. The first box is , 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 , and million for the scales , 1 and , and beats ), 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 is a local operation with no padding and a stride, then entry of equals , where is the sub-window at offset . Padding breaks this.
- Theorem: the logistic loss. is strictly convex in , decreasing in the margin , equal to at , with derivative . 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 be a stack of layers, each of the form
where is a finite window of offsets, is the stride of the layer, is applied point by point, and runs over the positions where is inside the input for every (no padding). Let be the product of the strides. For an exemplar and a search image , let be the sub-window of with the size of whose top left corner is at . Then for every position of the score map of line L6,
where is the cross-correlation summed over channels and is the sum of all products of matching entries.
Proof. First one layer. Let be the input shifted by . Then , for every that is valid for ; these are valid for , because the window of is inside . So shifting the input by shifts the output by , and cutting a sub-window of the input cuts the matching sub-window of the output. By induction over the layers, a shift of at the input is a shift of at the output of , so is the part of that starts at and has the size of . The cross-correlation at is , which is the inner product of with that part.
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 .
Why padding breaks it. With zero padding, the output of near its border uses zeros, while the matching part of 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 , the score map is shifted by 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 sub-windows one by one costs evaluations of on a window of the size of . The cross-correlation costs one evaluation of on , in which every overlapping part is computed once, and for the products, with channels and cells in .
Claim 2: the logistic loss is convex, has the stated gradient, and rewards the right sign
For and real , satisfies:
(a) and ;
(b) , which has the sign of and absolute value below 1;
(c) , so is strictly convex in ;
(d) is strictly decreasing in the margin , goes to 0 as , and is at least .
Proof. (a) is direct. (b) . (c) Differentiate again: and . (d) The function has derivative , and .
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 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 as for , the same value without overflow.
The label map of line L1. With stride and radius , a cell is positive if . For the map, and , the positive cells are the lattice points with : the center, 4 at distance 1, 4 at distance 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 , the weights of the four taps at for a point are
and they satisfy , , . 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 , is affine in , so its maximum over is at or . On each of those two edges is affine in , so the maximum is at a corner. (b) The weights follow from for and for , evaluated at , , and and expanded. Adding the four polynomials, the coefficients of , and cancel and the constant is 1. For the first moment, . For the second, . At the weights are , 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.
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 cells per side and the exemplar crop , both centered on the old position, with crop pixels of size image pixels, and let the score map be upsampled by the factor to positions . A map position (in each coordinate) puts the exemplar window at search offset , whose center is at in the crop, while the old center is at . So the displacement of line L10 is
and is the center of the map when the map has cells per side. With this is the formula in the code.
For line L11, if the chosen scale factor is and the damping is , the size is multiplied by , which lies between 1 and . A constant true scale change per frame is then followed with a lag; the size never jumps by more than the largest scale factor in one frame.
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 be the cost of on one search crop, the number of channels, the number of cells of , of , and of the score map. One scale costs for the features and for the correlation. The upsampling and the window cost . A frame costs , and frames cost times that. The exemplar features are computed once. The extra space is for the feature maps, for the score maps and for the upsampled map. For a trained network, dominates. The cost of the network is outside this page and depends on its layers. Scoring the sub-windows one by one would cost 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 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 is implemented, since every score has the derivative 1 in . 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.
# 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
- 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)
- 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)
- 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.
| 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 RDHCZ9 Edit this page History Report an error Markdown