Algorithm Search⌘K

Algorithmresearch

Semi-direct visual odometry

Also called SVO.

Track a camera by direct alignment of small patches around sparse map points, then refine the 2D features, the pose and the points by reprojection error.

Time
O(N (L k m + k m W + c (s + k) + P)) worst · averageO(N (L m + m W + c s + P)) best
Space
O(N P + m W + c) extra
Where
L = the number of pyramid levels; N = the number of frames; P = the number of pixels of an image; W = the number of keyframes; c = the number of seeds; k = the number of Gauss-Newton iterations; m = the number of visible map points; s = the number of steps of the epipolar search
Properties
deterministicnot exactiterativeonline
Origin
Christian Forster, Matia Pizzoli, Davide Scaramuzza, 2014

Semi-direct visual odometry (SVO) is the visual odometry method of Forster, Pizzoli and Scaramuzza that mixes a direct step and a feature step. The direct step finds the motion of a new frame by aligning small patches around projected map points with the photometric error, so it needs no feature matching. The feature step then moves each projected point a little in the image so that its patch matches a keyframe, and the pose and the points are refined with the reprojection error, as in bundle adjustment. New points come from a probabilistic depth filter on pixels of the keyframes. With one camera the scale is unknown and is fixed by the first depths.

In plain words

A camera moves, and you have a small set of 3D points that you already know. For a new picture, you first guess the motion by moving the old picture's small squares around the points until they look like the new picture. That gives a good pose quickly. Then, for each point, you take its square from a keyframe that saw it from a similar angle, and you slide it a little in the new picture until it fits best. These new 2D positions are more precise than the projections, so you fix the pose and the points with them. New points start as guesses of distance with a large uncertainty. Each new picture narrows the guess, and when the guess is narrow enough the point joins the map.

The problem

The input is a sequence of frames of a calibrated pinhole camera with intrinsics (fx,fy,cx,cy)(f_x, f_y, c_x, c_y), and the depths of some pixels of the first frame (the original system gets them from a homography between the first frames; here the caller gives them). A pose T=(R,t)T = (R, t) maps a world point into the camera, Xc=RX+tX_c = R X + t, and frame 0 is the world frame. The output is a pose for each frame and a sparse map of 3D points.

Sparse image alignment. Let k−1k-1 be the previous frame with pose Tk−1T_{k-1}. A map point XX projects to uu in it with depth zz. The relative pose Tk,k−1T_{k,k-1} minimizes

E(Tk,k−1)=∑points∑o∈P4(Ik(Π(Tk,k−1 Π−1(u+o,z)))−Ik−1(u+o))2,E(T_{k,k-1}) = \sum_{\text{points}} \sum_{o \in P_4} \Big(I_k\big(\Pi(T_{k,k-1}\, \Pi^{-1}(u + o, z))\big) - I_{k-1}(u + o)\Big)^2,

where P4P_4 is the set of 16 offsets of a 4×44 \times 4 patch and all pixels of a patch take the depth of its point.

Feature alignment. For a point seen in keyframe rr at uru_r, the new 2D position u′u' and an intensity offset β\beta minimize ∑o∈P8(Ik(u′+Ao)−Ir(ur+o)−β)2\sum_{o \in P_8} \big(I_k(u' + A o) - I_r(u_r + o) - \beta\big)^2 over an 8×88 \times 8 patch, where AA is the 2×22 \times 2 affine warp of the patch from keyframe rr to frame kk.

Depth filter. A seed is a pixel of a keyframe with an unknown inverse depth ZZ and an unknown inlier ratio π\pi. A measurement xx with variance τ2\tau^2 follows π N(x∣Z,τ2)+(1−π) U(x)\pi\, N(x \mid Z, \tau^2) + (1 - \pi)\, U(x), where UU is uniform over the range of inverse depths. The posterior is approximated by N(Z∣μ,σ2) Beta(π∣a,b)N(Z \mid \mu, \sigma^2)\, \mathrm{Beta}(\pi \mid a, b), as in Vogiatzis and Hernandez.

The algorithm

  1. SVO(frames F₀ … F_{N-1}, depths of selected pixels of F₀)
  2. 1keyframe 0 ← F₀ with pose (I, 0); map ← the selected pixels of F₀ back-projected with their depths
  3. 2for k ← 1 to N - 1 do
  4. 3T_k ← sparse image alignment of 4 x 4 patches against F_{k-1}, inverse compositional, coarse to fine, then composed with T_{k-1}
  5. 4for each visible map point do u' ← feature alignment of an affinely warped 8 x 8 patch from the keyframe with the closest viewing direction
  6. 5T_k ← motion-only bundle adjustment on the reprojection errors of the positions u'
  7. 6for each aligned point do X ← structure-only bundle adjustment over its keyframe observations and u'
  8. 7for each seed do search along the epipolar line in F_k, update the depth filter, and move the seed to the map if σ is small
  9. 8if the distance from F_k to every keyframe > 0.12 x the mean scene depth then
  10. 9add F_k as a keyframe, drop the farthest keyframe if there are too many, and start new seeds in empty cells
  11. 10return T₀ … T_{N-1}

Sparse image alignment (L3). The unknown is the relative pose from the previous frame. The inverse compositional form of Baker and Matthews (see inverse compositional alignment) moves the reference point instead of the current one: the residual is Ik(Π(T exp⁡(ξ) X))−Ik−1(u)I_k(\Pi(T\, \exp(\xi)\, X)) - I_{k-1}(u), linearized at ξ=0\xi = 0 on the reference side. Each patch pixel gives a Jacobian row J=∇Ik−1(u) ∂Π∂X [ −[X]×∣I ]J = \nabla I_{k-1}(u)\, \frac{\partial \Pi}{\partial X}\, [\,-[X]_\times \mid I\,] of size 1×61 \times 6, so a 4×44 \times 4 patch gives a 16×616 \times 6 block. These rows and H=∑JTJH = \sum J^{\mathsf T} J depend only on the reference image, so they are computed once per pyramid level. Each iteration solves Hξ=∑JTrH \xi = \sum J^{\mathsf T} r and updates T←Texp⁡(ξ)−1T \leftarrow T \exp(\xi)^{-1}. It runs from the coarsest level of an image pyramid to a fine level, from the identity. The paper uses 5 levels and stops at level 3, because the next step refines each feature at full resolution anyway. The code keeps a step only if the mean squared residual goes down.

Feature alignment (L4). For each map point that projects into the frame, the code takes the keyframe that saw it from the closest viewing direction. The warp AA is the derivative of the exact warp from that keyframe to the new frame for a patch on a plane parallel to the keyframe image at the depth of the point. Gauss-Newton on (u′,β)(u', \beta) then aligns the warped 8×88 \times 8 patch with the new frame, a 2D Lucas-Kanade step. The new positions do not have to agree with one pose: the paper calls this a relaxation and notes that it breaks the epipolar constraints on purpose. The reprojection error that remains is what the next two steps reduce.

Pose and structure refinement (L5, L6). Motion-only bundle adjustment is Gauss-Newton on the 6 pose parameters with the reprojection errors Π(RX+t)−u′\Pi(R X + t) - u' and a left update R←exp⁡([ω]×)RR \leftarrow \exp([\omega]_\times) R, t←exp⁡([ω]×)t+vt \leftarrow \exp([\omega]_\times) t + v. Structure-only bundle adjustment is Gauss-Newton on each point alone, with all its observations. Both keep a step only if the cost goes down.

Depth filter (L7). For each seed, the code searches the inverse depths in μ±2σ\mu \pm 2\sigma along the epipolar line, with the zero-mean sum of squared differences of an 8×88 \times 8 patch. It refines the best position by feature alignment and triangulates the depth along the ray of the seed. The variance τ2\tau^2 is the change of the inverse depth when the matched position moves by one pixel (a parameter) along the epipolar line. The update is the moment matching of Vogiatzis and Hernandez:

C1∝aa+b N(x∣μ,σ2+τ2),C2∝ba+b U(x),C1+C2=1,C_1 \propto \frac{a}{a + b}\, N(x \mid \mu, \sigma^2 + \tau^2), \quad C_2 \propto \frac{b}{a + b}\, U(x), \quad C_1 + C_2 = 1,
s2=(1σ2+1τ2)−1,m=s2(μσ2+xτ2),μ′=C1m+C2μ,σ′2=C1(s2+m2)+C2(σ2+μ2)−μ′2,s^2 = \Big(\frac{1}{\sigma^2} + \frac{1}{\tau^2}\Big)^{-1}, \quad m = s^2\Big(\frac{\mu}{\sigma^2} + \frac{x}{\tau^2}\Big), \quad \mu' = C_1 m + C_2 \mu, \quad \sigma'^2 = C_1 (s^2 + m^2) + C_2 (\sigma^2 + \mu^2) - \mu'^2,

and a′,b′a', b' are chosen so that Beta(a′,b′)\mathrm{Beta}(a', b') has the first two moments ff and ee of π\pi under the posterior: a′=(e−f)/(f−e/f)a' = (e - f)/(f - e/f), b′=a′(1−f)/fb' = a'(1 - f)/f. A seed whose σ\sigma is below a fraction of the range becomes a map point.

Keyframes (L8, L9). A frame becomes a keyframe when its camera center is farther than 12 percent of the mean scene depth from the centers of all keyframes. If there are too many keyframes, the one farthest from the new keyframe is removed. New seeds are placed in the cells of a grid that hold no point: in each cell, the pixel with the highest Shi-Tomasi score. The paper uses cells of 30×3030 \times 30 pixels and takes the FAST corner with the highest Shi-Tomasi score in each cell. These rules are heuristics; see keyframe selection.

Differences from the paper. The code leaves out the homography bootstrap, the FAST detector, the robust weights in the refinement steps, the separate mapping thread, edgelet features and the recovery after a tracking failure. The sparse alignment has no brightness offset. The parameters of the tests (cells of 8 pixels, a smaller convergence threshold, a smaller keyframe distance) fit 48×3648 \times 36 images and are not the paper's values.

Example

One depth filter update. A seed has μ=0.3\mu = 0.3, an inverse depth range of 0.50.5, so σ2=0.52/36=0.006944\sigma^2 = 0.5^2/36 = 0.006944, and a=b=10a = b = 10. A measurement x=0.25x = 0.25 arrives with τ=0.02\tau = 0.02. Then σ2+τ2=0.007344\sigma^2 + \tau^2 = 0.007344, and N(0.25∣0.3,0.007344)=e−0.1702/(0.08570⋅2.5066)=3.927N(0.25 \mid 0.3, 0.007344) = e^{-0.1702}/(0.08570 \cdot 2.5066) = 3.927. So C1∝0.5⋅3.927=1.963C_1 \propto 0.5 \cdot 3.927 = 1.963 and C2∝0.5/0.5=1C_2 \propto 0.5/0.5 = 1, which give C1=0.6626C_1 = 0.6626 and C2=0.3374C_2 = 0.3374. The Gaussian part has s2=1/(144+2500)=0.0003782s^2 = 1/(144 + 2500) = 0.0003782 and m=0.0003782⋅(43.2+625)=0.2527m = 0.0003782 \cdot (43.2 + 625) = 0.2527. The new mean is μ′=0.6626⋅0.2527+0.3374⋅0.3=0.2687\mu' = 0.6626 \cdot 0.2527 + 0.3374 \cdot 0.3 = 0.2687, and the new standard deviation is 0.05560.0556 (it was 0.08330.0833). The inlier ratio a/(a+b)a/(a + b) goes from 0.50.5 to 0.5080.508: the measurement is likely, but the prior is wide, so it is not certainly an inlier.

Keyframe rule. With a mean scene depth of 5, the threshold is 0.12⋅5=0.60.12 \cdot 5 = 0.6. A frame at (0.5,0,0)(0.5, 0, 0) with keyframes at the origin and at (1,0,0)(1, 0, 0) is 0.50.5 from both, so it is not a keyframe. A frame at (0.5,0.7,0)(0.5, 0.7, 0) is 0.860.86 from both, so it is.

One pixel in inverse depth. For a sideways move of length ∣t∣|t| and focal length ff, a point at inverse depth xx moves f∣t∣xf |t| x pixels. So one pixel of error is 1/(f∣t∣)1/(f |t|) in inverse depth. With f=40f = 40 and ∣t∣=0.354|t| = 0.354 this is 0.07070.0707: short baselines give poor depth, which is why a seed needs many frames.

A synthetic run. The tests render a textured slanted plane at depth about 5 into 48×3648 \times 36 pixel grids with fx=fy=40f_x = f_y = 40, for 8 frames along a path of length 0.880.88. The pipeline starts with 23 map points, makes keyframes 0, 2, 4 and 6, and turns 5 seeds into map points. The largest rotation error was 0.150.15 degrees and the largest position error 0.0110.011. On exact (analytic) images, the sparse alignment recovers a relative pose within 10−610^{-6} and the feature alignment recovers a position within 10−610^{-6}. These numbers are one synthetic run, not a property of the method.

Correctness

The full proof is in proofs/correctness.md. For exact images of a scene with known map points, it shows that the true relative pose makes every residual of the sparse alignment zero, so it is a global minimizer and a fixed point; that the true position is a fixed point of the feature alignment when the warp is exact; that the true pose and points are global minimizers and fixed points of the two refinement steps; and that every one of these steps never increases its cost, because a step is kept only when the cost goes down. It also proves that the depth filter update matches the mean and variance of ZZ and the first two moments of π\pi under the exact one-step posterior (this is a theorem about the update, not about convergence of the filter), and that the triangulation along the ray is exact for noise-free bearings. Convergence from a far start is not proved: the direct alignment works only within a few pixels at the coarsest level.

Proof: On exact images the true pose, positions and points are fixed points of every step, no step increases its cost, and the depth filter update matches the posterior momentsfull

Setting. Poses map world points into the camera, Xc=RX+tX_c = R X + t, and Π\Pi is the pinhole projection. Line L3 minimizes the mean of the squared residuals rq(T)=Ik(Π(TXq))−Ik−1(uq)r_q(T) = I_k(\Pi(T X_q)) - I_{k-1}(u_q) over the patch pixels qq whose sample lies in the image, where Xq=Π−1(uq,z)X_q = \Pi^{-1}(u_q, z) is the point of pixel uqu_q in the previous camera. Line L4 minimizes ∑o(Ik(u′+Ao)−Ir(ur+o)−β)2\sum_{o} (I_k(u' + A o) - I_r(u_r + o) - \beta)^2 over (u′,β)(u', \beta). Lines L5 and L6 minimize sums of squared reprojection errors ∣Π(RX+t)−u∣2|\Pi(R X + t) - u|^2.

Assumptions. (A1) Exact images: each image is Ij(u)=L(Xj(u))+βjI_j(u) = L(X_j(u)) + \beta_j, where Xj(u)X_j(u) is the scene point seen at pixel uu in frame jj, LL is the radiance and βj\beta_j is a constant offset; in L3 the offsets of the two frames are equal. (A2) The map points and the pose of the previous frame are true, and each patch lies on a plane parallel to the image in which its depth is given, so the depth of each patch pixel is the depth of its point. (A3) Every sample used is inside its image. These are the conditions of the exact tests; real images meet them only approximately.

Lemma 1 (sparse alignment: zero residuals). Let T∗T^* be the true relative pose. By (A2), XqX_q is the true point of pixel uqu_q in the previous camera, so T∗XqT^* X_q is the same scene point in the current camera, seen at Π(T∗Xq)\Pi(T^* X_q). By (A1) with equal offsets, Ik(Π(T∗Xq))=L(X)+β=Ik−1(uq)I_k(\Pi(T^* X_q)) = L(X) + \beta = I_{k-1}(u_q), so rq(T∗)=0r_q(T^*) = 0 for every qq. The cost is a mean of squares, so it is ≥0\ge 0 for every TT, and T∗T^* attains the value 0. So T∗T^* is a global minimizer.

Lemma 2 (sparse alignment: fixed point). The inverse compositional step solves Hξ=∑qJqTrqH \xi = \sum_q J_q^{\mathsf T} r_q with fixed JqJ_q and HH. At T∗T^* every rq=0r_q = 0 by Lemma 1, so the right-hand side is 0 and ξ=0\xi = 0 (or HH is singular and the loop stops). The update T∗exp⁡(0)−1=T∗T^* \exp(0)^{-1} = T^* gives the same cost, which is not smaller, so the loop stops at T∗T^*. The same holds at every pyramid level: each level is an exact image of the same scene with the scaled intrinsics, so Lemma 1 holds there too.

Lemma 3 (feature alignment: fixed point). Let u∗u^* be the true position of the point in frame kk and assume the warp AA is exact on the patch, that is, the pixel ur+ou_r + o of keyframe rr and the pixel u∗+Aou^* + A o of frame kk see the same scene point. This holds when the patch is planar and the warp between the two images is affine on the patch, for example for a fronto-parallel plane under a translation parallel to it, where A=IA = I, or a translation along the optical axis, where A=sIA = s I. Then by (A1) Ik(u∗+Ao)−Ir(ur+o)=βk−βrI_k(u^* + A o) - I_r(u_r + o) = \beta_k - \beta_r for every oo, so (u∗,βk−βr)(u^*, \beta_k - \beta_r) makes every residual zero. It is a global minimizer of the sum of squares, the right-hand side −∑JTr-\sum J^{\mathsf T} r of the Gauss-Newton system is 0 there, and the loop stops there by the argument of Lemma 2.

Lemma 4 (refinement: fixed point). In line L5 let the positions be ui=Π(R∗Xi+t∗)u_i = \Pi(R^* X_i + t^*) for the true pose and true points. Every reprojection error is zero at (R∗,t∗)(R^*, t^*), so it is a global minimizer of the cost, the gradient −∑JTe-\sum J^{\mathsf T} e is zero, the step is zero, and the loop stops there. Line L6 is the same with the point as the unknown and the poses fixed: if all observations are exact projections of X∗X^*, then X∗X^* has zero cost and is a fixed point.

Lemma 5 (monotone costs). Each of lines L3, L4, L5 and L6 computes the cost of a candidate step and keeps the step only if the cost is strictly smaller; otherwise it stops. So the costs of the kept iterates are strictly decreasing, and the returned cost is at most the starting cost. This holds for any data. In L3 the cost is the mean over the samples inside the image; the rule holds for that mean as computed.

Lemma 6 (exact triangulation along the ray). Let fr=(xr,yr,1)f_r = (x_r, y_r, 1) and fcf_c be the normalized coordinates of the seed in the reference and of its match in the current camera, and let (R,t)(R, t) be the relative pose. If the point zfrz f_r of the reference camera is seen along fcf_c, then zRfr+t=λfcz R f_r + t = \lambda f_c for some λ\lambda. Taking the cross product with fcf_c gives z a+c=0z\, a + c = 0 with a=(Rfr)×fca = (R f_r) \times f_c and c=t×fcc = t \times f_c. The least-squares solution over zz is z=−aTc/aTaz = -a^{\mathsf T} c / a^{\mathsf T} a, and when the equation holds exactly with a≠0a \ne 0 this equals the true zz. (a=0a = 0 means that the two rays are parallel, and then the depth is not defined.) So for an exact match the measurement x=1/zx = 1/z is the true inverse depth.

Lemma 7 (depth filter update). Let the prior be p(Z,π)=N(Z∣μ,σ2) Beta(π∣a,b)p(Z, \pi) = N(Z \mid \mu, \sigma^2)\, \mathrm{Beta}(\pi \mid a, b) and the likelihood of xx be πN(x∣Z,τ2)+(1−π)U\pi N(x \mid Z, \tau^2) + (1 - \pi) U, with the constant density UU. The exact posterior is proportional to

π N(x∣Z,τ2) N(Z∣μ,σ2) Beta(π∣a,b)+(1−π) U N(Z∣μ,σ2) Beta(π∣a,b).\pi\, N(x \mid Z, \tau^2)\, N(Z \mid \mu, \sigma^2)\, \mathrm{Beta}(\pi \mid a, b) + (1 - \pi)\, U\, N(Z \mid \mu, \sigma^2)\, \mathrm{Beta}(\pi \mid a, b).

For the first term, the product of the two Gaussians in ZZ is N(x∣μ,σ2+τ2) N(Z∣m,s2)N(x \mid \mu, \sigma^2 + \tau^2)\, N(Z \mid m, s^2) with s2=(σ−2+τ−2)−1s^2 = (\sigma^{-2} + \tau^{-2})^{-1} and m=s2(μ/σ2+x/τ2)m = s^2(\mu/\sigma^2 + x/\tau^2) (the standard identity for a product of Gaussian densities, found by completing the square). Also π Beta(π∣a,b)=aa+bBeta(π∣a+1,b)\pi\, \mathrm{Beta}(\pi \mid a, b) = \frac{a}{a + b} \mathrm{Beta}(\pi \mid a + 1, b) and (1−π) Beta(π∣a,b)=ba+bBeta(π∣a,b+1)(1 - \pi)\, \mathrm{Beta}(\pi \mid a, b) = \frac{b}{a + b} \mathrm{Beta}(\pi \mid a, b + 1), because B(a+1,b)=B(a,b) a/(a+b)B(a + 1, b) = B(a, b)\, a/(a + b). So the posterior is the mixture

C1 N(Z∣m,s2) Beta(π∣a+1,b)+C2 N(Z∣μ,σ2) Beta(π∣a,b+1),C_1\, N(Z \mid m, s^2)\, \mathrm{Beta}(\pi \mid a + 1, b) + C_2\, N(Z \mid \mu, \sigma^2)\, \mathrm{Beta}(\pi \mid a, b + 1),

with C1∝aa+bN(x∣μ,σ2+τ2)C_1 \propto \frac{a}{a + b} N(x \mid \mu, \sigma^2 + \tau^2), C2∝ba+bUC_2 \propto \frac{b}{a + b} U and C1+C2=1C_1 + C_2 = 1. These are the weights in the code. The mean of ZZ under the mixture is C1m+C2μC_1 m + C_2 \mu, and its second moment is C1(s2+m2)+C2(σ2+μ2)C_1(s^2 + m^2) + C_2(\sigma^2 + \mu^2), so the code's μ′\mu' and σ′2\sigma'^2 are the exact mean and variance. The first two moments of Beta(α,β)\mathrm{Beta}(\alpha, \beta) are α/(α+β)\alpha/(\alpha + \beta) and α(α+1)/((α+β)(α+β+1))\alpha(\alpha + 1)/((\alpha + \beta)(\alpha + \beta + 1)), which give the code's ff and ee for the mixture. Finally, Beta(a′,b′)\mathrm{Beta}(a', b') with a′=(e−f)/(f−e/f)=f(e−f)/(f2−e)a' = (e - f)/(f - e/f) = f(e - f)/(f^2 - e) and b′=a′(1−f)/fb' = a'(1 - f)/f has these moments. First, n=a′+b′=a′/fn = a' + b' = a'/f, so a′/n=fa'/n = f. Second, n=(e−f)/(f2−e)n = (e - f)/(f^2 - e), so a′+1=(ef−f2+f2−e)/(f2−e)=e(f−1)/(f2−e)a' + 1 = (e f - f^2 + f^2 - e)/(f^2 - e) = e(f - 1)/(f^2 - e) and n+1=(e−f+f2−e)/(f2−e)=f(f−1)/(f2−e)n + 1 = (e - f + f^2 - e)/(f^2 - e) = f(f - 1)/(f^2 - e). The second moment is then a′(a′+1)n(n+1)=f⋅e(f−1)f(f−1)=e\frac{a'(a' + 1)}{n(n + 1)} = f \cdot \frac{e(f - 1)}{f(f - 1)} = e. (Here 0<f<10 < f < 1 and e>f2e > f^2, because the variance of π\pi is positive, so all the quantities are positive.) So the update replaces the posterior by the product of a Gaussian and a Beta with the same first two moments of ZZ and of π\pi. The test checks these moments against a numerical integration of the exact posterior.

Conclusion. Under (A1) to (A3), the true relative pose is a global minimizer and a fixed point of the sparse alignment at every level (Lemmas 1 and 2), the true position is a fixed point of the feature alignment when the warp is exact (Lemma 3), and the true pose and points are fixed points of the two refinement steps (Lemma 4). On any data, no kept step increases its cost (Lemma 5). An exact match gives the true inverse depth (Lemma 6), and each depth filter update keeps the first two moments of the exact one-step posterior (Lemma 7). ■\blacksquare

What is not proved. Convergence from a far start: all steps are local Gauss-Newton methods on non-convex costs, and the pyramid and the high frame rate are there to keep the start close. The convergence of the depth filter to the true depth is not proved; the Gaussian times Beta form is an approximation that is made again after every update. The keyframe rule and the choice of cells are heuristics. On real images the brightness is not constant, the patches are not planar and parallel to the image, and the estimates drift.

Complexity

All counts are in the real RAM. Patch sizes are constants.

  • Sparse alignment. The setup of one level costs O(m)O(m), and one iteration costs O(m)O(m) for the residuals and a 6×66 \times 6 solve. With LL levels and kk iterations, O(Lkm)O(Lkm) per frame. The inverse compositional form saves the recomputation of JJ and HH in each iteration, not an order of growth.
  • Feature alignment. Choosing the keyframe costs O(W)O(W) per point and the alignment O(k)O(k), so O(m(W+k))O(m(W + k)).
  • Refinement. Motion-only bundle adjustment costs O(km)O(km). Structure-only bundle adjustment costs O(kW)O(kW) per point, so O(kmW)O(kmW).
  • Seeds. One epipolar search costs O(s)O(s) and the refinement O(k)O(k), so O(c(s+k))O(c(s + k)).
  • Images. Building the pyramid costs O(P)O(P) per frame, and the Shi-Tomasi scores O(P)O(P) per keyframe.

The cost per frame is O(Lkm+kmW+c(s+k)+P)O(Lkm + kmW + c(s + k) + P). These are costs per iteration times an iteration limit, not a convergence bound. The code keeps all pyramids, which takes O(NP)O(NP) space; a real system keeps only those of the keyframes and the last frame.

Properties

  • Deterministic. There are no random samples.
  • Not exact. All Gauss-Newton steps converge only locally, and the result depends on the start and the image content.
  • Online. Each frame costs a bounded amount of work for a bounded map.
  • Fast. The direct step uses few pixels and needs no descriptors or matching. The ICRA 2014 paper reports more than 300 frames per second on a laptop; this is a benchmark result for that implementation and hardware.
  • Scale. With one camera the scale comes from the first depths and drifts over long paths; see scale drift.
  • Outlier handling. The depth filter models outliers with the inlier ratio π\pi, so a seed that gets many bad measurements gets a low a/(a+b)a/(a + b) and can be dropped.

Variants and improvements

  • Several cameras and other models. The 2017 journal version handles several cameras, fisheye and catadioptric cameras, and adds edgelets for scenes with few corners.
  • Inertial data. Later systems add an inertial sensor for metric scale and robustness.
  • Fully direct methods. Direct sparse odometry keeps the photometric error also in the window optimization and models brightness changes.
  • Feature-based methods. Nister visual odometry and ORB-SLAM match features with descriptors and use RANSAC; they tolerate larger motion between frames.

When to use it

Use SVO when the frame rate is high, the motion between frames is small, the computer is small (an onboard computer of a drone was the original target), and the scene has texture. Prefer a feature-based method when the motion between frames is large or the brightness changes a lot, and a method with loop closure, such as ORB-SLAM, when the camera returns to places it saw before.

Pitfalls

  • Large motion. The sparse alignment starts from the identity. If a frame moves by more than a few pixels at the coarsest level, it can converge to a wrong pose.
  • Brightness change. The sparse alignment assumes constant brightness. A change of exposure biases the pose; the feature alignment has an offset β\beta, but the first step does not in the basic form.
  • Seeds on edges. On an edge parallel to the epipolar line, the search finds many equal minima. The filter then gets bad measurements and must reject them through π\pi.
  • Depth of a patch. All pixels of a patch take one depth, and the affine warp assumes a plane parallel to the keyframe image. On slanted surfaces close to the camera these are approximations.
  • Keyframe rule. A fixed fraction of the mean depth gives few keyframes for a camera that only rotates, and new seeds then have no baseline.
  • Bootstrap. The homography bootstrap assumes a mostly planar view of the first frames; see homography estimation.

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.

cvla.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.

A matrix is a list of rows. A vector is a flat list. The functions do not
change their arguments. Entries are floats, but zeros, eye, transpose, add,
sub, scale, mul, matvec, dot, cross, skew, solve, inv and det also work with
fractions.Fraction entries and then give exact results.

Tolerances:
- solve, inv and det raise ValueError only on an exact zero pivot. A matrix
  that is close to singular gives large entries; check the condition yourself.
- sym_eig and svd stop a Jacobi sweep when every off-diagonal term is below
  1e-15 times the size of its pair (at most 100 sweeps).
- polyroots_real keeps a root z when |Im z| <= imag_tol * max(1, |z|), with
  imag_tol = 1e-6 by default. Roots of multiplicity k are found with an error
  of about 1e-16^(1/k) relative, so a double root keeps an imaginary part near
  1e-8.

This module holds no algorithm of a computer vision page.
"""

from __future__ import annotations

import cmath
import math
from typing import List, Sequence, Tuple

Matrix = List[List[float]]
Vector = List[float]

_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100


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

def zeros(m: int, n: int) -> Matrix:
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n: int) -> Matrix:
    """The n x n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a) -> bool:
    return len(a) > 0 and isinstance(a[0], (list, tuple))


def transpose(a: Sequence[Sequence[float]]) -> Matrix:
    """The transpose of a matrix."""
    return [list(col) for col in zip(*a)]


def add(a, b):
    """a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, c):
    """c times a, for a vector or a matrix a and a number c."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
    """The matrix product a b."""
    if len(a[0]) != len(b):
        raise ValueError("mul: shapes do not match")
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
    """The product a x of a matrix and a vector."""
    if len(a[0]) != len(x):
        raise ValueError("matvec: shapes do not match")
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x: Sequence[float], y: Sequence[float]) -> float:
    """The inner product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(a) -> float:
    """The Euclidean norm of a vector, or the Frobenius norm of a matrix."""
    if _is_matrix(a):
        return math.sqrt(sum(float(x) * float(x) for row in a for x in row))
    return math.sqrt(sum(float(x) * float(x) for x in a))


def cross(a: Sequence[float], b: Sequence[float]) -> Vector:
    """The cross product a x b of two 3-vectors."""
    return [a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0]]


def skew(a: Sequence[float]) -> Matrix:
    """The skew matrix [a]_x, with skew(a) b = cross(a, b)."""
    z = a[0] - a[0]
    return [[z, -a[2], a[1]],
            [a[2], z, -a[0]],
            [-a[1], a[0], z]]


# ---------------------------------------------------- Gaussian elimination

def _eliminate(a: Matrix, b: Matrix) -> Tuple[Matrix, Matrix, int]:
    """Reduce [a | b] to upper triangular form with partial pivoting.

    Works in place on copies made by the caller. Returns a, b and the sign
    of the row permutation.
    """
    n = len(a)
    sign = 1
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("singular matrix")
        if p != k:
            a[k], a[p] = a[p], a[k]
            b[k], b[p] = b[p], b[k]
            sign = -sign
        piv = a[k][k]
        for i in range(k + 1, n):
            f = a[i][k] / piv
            if f == 0:
                continue
            ai, ak = a[i], a[k]
            for j in range(k, n):
                ai[j] = ai[j] - f * ak[j]
            bi, bk = b[i], b[k]
            for j in range(len(bi)):
                bi[j] = bi[j] - f * bk[j]
    return a, b, sign


def solve(a: Sequence[Sequence[float]], b):
    """Solve a x = b for a square a, by Gaussian elimination with partial
    pivoting. b is a vector or a matrix (several right-hand sides); the
    result has the same form. Raises ValueError on an exact zero pivot."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("solve: matrix is not square")
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: shapes do not match")
    u, c, _ = _eliminate([list(row) for row in a], rhs)
    m = len(c[0]) if n else 0
    x = [[0.0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = c[i][j]
            for k in range(i + 1, n):
                s = s - u[i][k] * x[k][j]
            x[i][j] = s / u[i][i]
    return [row[0] for row in x] if vec else x


def inv(a: Sequence[Sequence[float]]) -> Matrix:
    """The inverse of a square matrix. Raises ValueError if it is singular."""
    n = len(a)
    one = a[0][0] - a[0][0] + 1 if n else 1.0
    ident = [[one if i == j else one - one for j in range(n)] for i in range(n)]
    return solve(a, ident)


def det(a: Sequence[Sequence[float]]) -> float:
    """The determinant of a square matrix, by Gaussian elimination."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("det: matrix is not square")
    if n == 0:
        return 1.0
    try:
        u, _, sign = _eliminate([list(row) for row in a], [[] for _ in range(n)])
    except ValueError:
        return a[0][0] - a[0][0]
    d = u[0][0] - u[0][0] + sign
    for i in range(n):
        d = d * u[i][i]
    return d


# ------------------------------------------------------- Jacobi methods

def sym_eig(a: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix]:
    """Eigenvalues and eigenvectors of a real symmetric matrix by the cyclic
    Jacobi method. Returns (w, V): w ascending, and column j of V is a unit
    eigenvector for w[j], so a = V diag(w) V^T. Only the upper triangle of
    a is read (the lower triangle is taken as its mirror)."""
    n = len(a)
    s = [[float(a[min(i, j)][max(i, j)]) for j in range(n)] for i in range(n)]
    v = eye(n)
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                apq = s[p][q]
                if apq == 0.0:
                    continue
                app, aqq = s[p][p], s[q][q]
                if abs(apq) <= _JACOBI_EPS * math.sqrt(abs(app * aqq)) or \
                        abs(apq) < 1e-300:
                    s[p][q] = s[q][p] = 0.0
                    continue
                rotated = True
                theta = (aqq - app) / (2.0 * apq)
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    skp, skq = s[k][p], s[k][q]
                    s[k][p] = c * skp - sn * skq
                    s[k][q] = sn * skp + c * skq
                for k in range(n):
                    spk, sqk = s[p][k], s[q][k]
                    s[p][k] = c * spk - sn * sqk
                    s[q][k] = sn * spk + c * sqk
                s[p][q] = s[q][p] = 0.0
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - sn * vkq
                    v[k][q] = sn * vkp + c * vkq
        if not rotated:
            break
    order = sorted(range(n), key=lambda i: s[i][i])
    w = [s[i][i] for i in order]
    vs = [[v[k][i] for i in order] for k in range(n)]
    return w, vs


def _complete_basis(cols: List[Vector], m: int, need: List[int]) -> None:
    """Replace the columns with index in need by unit vectors orthogonal to
    all other columns (Gram-Schmidt on the standard basis)."""
    keep = [c for i, c in enumerate(cols) if i not in need]
    for i in need:
        best, best_norm = None, -1.0
        for e in range(m):
            x = [0.0] * m
            x[e] = 1.0
            for _ in range(2):
                for c in keep:
                    d = dot(c, x)
                    x = [xi - d * ci for xi, ci in zip(x, c)]
            nx = norm(x)
            if nx > best_norm:
                best, best_norm = x, nx
        u = [xi / best_norm for xi in best]
        cols[i] = u
        keep.append(u)


def _svd_tall(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    m, n = len(a), len(a[0])
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(_MAX_SWEEPS):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                cp, cq = cols[p], cols[q]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cq)
                gamma = sum(x * y for x, y in zip(cp, cq))
                if gamma == 0.0 or abs(gamma) <= _JACOBI_EPS * math.sqrt(alpha * beta):
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                c = 1.0 / math.sqrt(1.0 + t * t)
                s = c * t
                cols[p] = [c * x - s * y for x, y in zip(cp, cq)]
                cols[q] = [s * x + c * y for x, y in zip(cp, cq)]
                vp, vq = vcols[p], vcols[q]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vq)]
                vcols[q] = [s * x + c * y for x, y in zip(vp, vq)]
        if not rotated:
            break
    sv = [norm(c) for c in cols]
    order = sorted(range(n), key=lambda i: -sv[i])
    sv = [sv[i] for i in order]
    cols = [cols[i] for i in order]
    vcols = [vcols[i] for i in order]
    smax = sv[0] if sv else 0.0
    ucols: List[Vector] = []
    need: List[int] = []
    for i, c in enumerate(cols):
        if sv[i] > 1e-13 * smax and sv[i] > 1e-300:
            ucols.append([x / sv[i] for x in c])
        else:
            ucols.append([0.0] * m)
            need.append(i)
    if need:
        _complete_basis(ucols, m, need)
    return transpose(ucols), sv, transpose(vcols)


def svd(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
    """Thin singular value decomposition by the one-sided Jacobi method.

    For an m x n matrix a with k = min(m, n), returns (U, S, V) with U of
    size m x k, S a list of k values in descending order and V of size
    n x k, such that a = U diag(S) V^T. U and V have orthonormal columns.
    For m >= n, V is square (n x n)."""
    m, n = len(a), len(a[0])
    if m >= n:
        return _svd_tall(a)
    u, s, v = _svd_tall(transpose(a))
    return v, s, u


def nullvec(a: Sequence[Sequence[float]]) -> Vector:
    """A unit vector x that minimizes ||a x||: the right singular vector of
    the smallest singular value. If a has fewer rows than columns, zero rows
    are added first, so the result is in the null space. The sign is not
    fixed."""
    m, n = len(a), len(a[0])
    rows = [list(map(float, r)) for r in a] + [[0.0] * n for _ in range(n - m)]
    _, _, v = _svd_tall(rows)
    return [v[i][n - 1] for i in range(n)]


# ---------------------------------------------- orthogonal factorizations

def qr(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """QR factorization by Householder reflections. For an m x n matrix a,
    returns Q (m x m, orthogonal) and R (m x n, upper triangular) with
    a = Q R. The signs are chosen so that the diagonal of R is >= 0."""
    m, n = len(a), len(a[0])
    r = [[float(x) for x in row] for row in a]
    q = eye(m)
    for k in range(min(m - 1, n)):
        x = [r[i][k] for i in range(k, m)]
        nx = norm(x)
        if nx == 0.0:
            continue
        alpha = -nx if x[0] >= 0 else nx
        v = list(x)
        v[0] -= alpha
        nv = norm(v)
        if nv == 0.0:
            continue
        v = [vi / nv for vi in v]
        for j in range(n):
            d = sum(v[i - k] * r[i][j] for i in range(k, m))
            if d != 0.0:
                for i in range(k, m):
                    r[i][j] -= 2.0 * v[i - k] * d
        for i in range(m):
            d = sum(q[i][l] * v[l - k] for l in range(k, m))
            if d != 0.0:
                for l in range(k, m):
                    q[i][l] -= 2.0 * d * v[l - k]
    for k in range(min(m, n)):
        if r[k][k] < 0:
            r[k] = [-x for x in r[k]]
            for i in range(m):
                q[i][k] = -q[i][k]
    for i in range(m):
        for j in range(min(i, n)):
            r[i][j] = 0.0
    return q, r


def rq(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
    """RQ factorization of a square matrix: returns R (upper triangular,
    with a diagonal >= 0) and Q (orthogonal) with a = R Q. It is computed
    from the QR factorization of the transpose of the row-reversed matrix."""
    n = len(a)
    if any(len(row) != n for row in a):
        raise ValueError("rq: matrix is not square")
    flipped = transpose([list(row) for row in reversed(a)])
    q1, r1 = qr(flipped)
    rt = transpose(r1)
    r = [list(reversed(row)) for row in reversed(rt)]
    q = [list(row) for row in reversed(transpose(q1))]
    return r, q


def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
    """The lower triangular L with a = L L^T, for a symmetric positive
    definite a. Raises ValueError if a pivot is not positive."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
        if d <= 0:
            raise ValueError("cholesky: matrix is not positive definite")
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return low


# ---------------------------------------------------------- polynomials

def _horner(c: Sequence[complex], x):
    p = 0.0
    for ci in c:
        p = p * x + ci
    return p


def polyroots_real(coeffs: Sequence[float], imag_tol: float = 1e-6) -> Vector:
    """Real roots of the polynomial with the given coefficients, highest
    power first. All complex roots are found by the Durand-Kerner method.
    A root z is kept as real when |Im z| <= imag_tol * max(1, |z|); its real
    part is then polished by Newton steps on the real polynomial. Returns
    the real roots in ascending order, with repeats for multiple roots."""
    c = [float(x) for x in coeffs]
    while c and c[0] == 0.0:
        c.pop(0)
    n = len(c) - 1
    if n < 1:
        return []
    c = [x / c[0] for x in c]
    rho = max([abs(c[i]) ** (1.0 / i) for i in range(1, n + 1)] + [0.0])
    if rho == 0.0:
        return [0.0] * n
    z = [rho * cmath.exp(1j * (2.0 * math.pi * k / n + 0.4)) for k in range(n)]
    for _ in range(2000):
        moved = 0.0
        for k in range(n):
            den = 1.0 + 0j
            for j in range(n):
                if j != k:
                    den *= z[k] - z[j]
            if den == 0:
                den = 1e-12 * rho
            step = _horner(c, z[k]) / den
            z[k] -= step
            moved = max(moved, abs(step) / max(1.0, abs(z[k])))
        if moved <= 1e-15:
            break
    deriv = [c[i] * (n - i) for i in range(n)]
    roots = []
    for zk in z:
        if abs(zk.imag) > imag_tol * max(1.0, abs(zk)):
            continue
        x = zk.real
        px = _horner(c, x)
        for _ in range(8):
            dp = _horner(deriv, x)
            if dp == 0.0 or px == 0.0:
                break
            xn = x - px / dp
            pn = _horner(c, xn)
            if abs(pn) >= abs(px):
                break
            x, px = xn, pn
        roots.append(x)
    return sorted(roots)


# ------------------------------------------------------------ self-test

def self_test() -> None:
    """Check svd, sym_eig and polyroots_real. Raises AssertionError."""
    import random
    rng = random.Random(7)
    for _ in range(3):
        a = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(5)]
        u, s, v = svd(a)
        rec = mul(mul(u, [[s[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(v))
        assert norm(sub(rec, a)) <= 1e-10
        assert all(s[i] >= s[i + 1] for i in range(4))
        sym = add(a, transpose(a))
        w, vv = sym_eig(sym)
        rec = mul(mul(vv, [[w[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(vv))
        assert norm(sub(rec, sym)) <= 1e-10
        assert all(w[i] <= w[i + 1] for i in range(4))
    r = polyroots_real([1.0, -6.0, 11.0, -6.0])
    assert len(r) == 3
    assert all(abs(x - y) <= 1e-10 for x, y in zip(r, [1.0, 2.0, 3.0]))


if __name__ == "__main__":
    self_test()
semi_direct_visual_odometry.py 601 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/semi-direct-visual-odometry/. The authors are listed in prov/BR51JE.jsonl.
"""Semi-direct visual odometry (Forster, Pizzoli and Scaramuzza, ICRA 2014),
small form.

Motion thread, for each new frame:
1. Sparse model-based image alignment: the relative pose to the previous
   frame minimizes the photometric error of 4 x 4 patches around the
   projected map points, by inverse compositional Gauss-Newton, coarse to
   fine.
2. Feature alignment (relaxation): each visible map point gets a 2D
   position by aligning an affinely warped 8 x 8 patch of a keyframe with
   the new frame. This step breaks the epipolar constraints on purpose.
3. Motion-only bundle adjustment: Gauss-Newton on the pose with the
   reprojection errors of the aligned positions.
4. Structure-only bundle adjustment: Gauss-Newton on each point.

Mapping: a seed (a pixel of a keyframe) has a depth filter on its inverse
depth with the Gaussian times Beta model of Vogiatzis and Hernandez. Each
new frame gives one measurement by a search along the epipolar line. A
converged seed becomes a map point. A new keyframe is made when the frame is
far from all keyframes compared with the mean scene depth.

What is left out: the homography bootstrap (the caller gives the depths of
the first frame), FAST corners (a Shi-Tomasi score per cell is used), the
robust weights, the brightness offset in sparse alignment, and the
threads. Images are objects with sample(u, v) -> (value, d/du, d/dv) or
None near the border. Poses map world points into the camera: X_c = R X + t.
"""

from __future__ import annotations

import math
from typing import Dict, List, Optional, Sequence, Tuple

from cvla import cross, dot, eye, matvec, mul, norm, skew, solve, transpose

Matrix = List[List[float]]
Vector = List[float]
Pose = Tuple[Matrix, Vector]

PATCH4 = [(du - 1.5, dv - 1.5) for dv in range(4) for du in range(4)]
PATCH8 = [(du - 3.5, dv - 3.5) for dv in range(8) for du in range(8)]


# ------------------------------------------------------------------ images

class GridImage:
    """A gray image img[v][u], read with bilinear interpolation of the values
    and of central-difference gradients. None within one pixel of the border."""

    def __init__(self, rows: Sequence[Sequence[float]]):
        self.h, self.w = len(rows), len(rows[0])
        self.val = [[float(x) for x in row] for row in rows]
        self.gx = [[0.0] * self.w for _ in range(self.h)]
        self.gy = [[0.0] * self.w for _ in range(self.h)]
        for v in range(1, self.h - 1):
            for u in range(1, self.w - 1):
                self.gx[v][u] = 0.5 * (self.val[v][u + 1] - self.val[v][u - 1])
                self.gy[v][u] = 0.5 * (self.val[v + 1][u] - self.val[v - 1][u])

    def sample(self, u: float, v: float) -> Optional[Tuple[float, float, float]]:
        if not (1.0 <= u <= self.w - 2.0 and 1.0 <= v <= self.h - 2.0):
            return None
        u0, v0 = min(int(u), self.w - 3), min(int(v), self.h - 3)
        fu, fv = u - u0, v - v0
        w00, w01, w10, w11 = (1 - fu) * (1 - fv), fu * (1 - fv), (1 - fu) * fv, fu * fv
        out = []
        for a in (self.val, self.gx, self.gy):
            out.append(w00 * a[v0][u0] + w01 * a[v0][u0 + 1] + w10 * a[v0 + 1][u0] + w11 * a[v0 + 1][u0 + 1])
        return out[0], out[1], out[2]

    def half(self) -> "GridImage":
        return GridImage([[0.25 * (self.val[2 * v][2 * u] + self.val[2 * v][2 * u + 1] +
                                   self.val[2 * v + 1][2 * u] + self.val[2 * v + 1][2 * u + 1])
                           for u in range(self.w // 2)] for v in range(self.h // 2)])


def pyramid(img: GridImage, levels: int) -> List[GridImage]:
    out = [img]
    for _ in range(levels - 1):
        out.append(out[-1].half())
    return out


def level_K(K: Sequence[float], level: int) -> Tuple[float, float, float, float]:
    """(fx, fy, cx, cy) at a pyramid level made by 2 x 2 means."""
    fx, fy, cx, cy = K
    for _ in range(level):
        fx, fy, cx, cy = fx / 2.0, fy / 2.0, (cx - 0.5) / 2.0, (cy - 0.5) / 2.0
    return fx, fy, cx, cy


# ------------------------------------------------------------ rigid motion

def so3_exp(w: Sequence[float]) -> Matrix:
    th = norm(w)
    k = skew(w)
    kk = mul(k, k)
    if th < 1e-12:
        a, b = 1.0, 0.5
    else:
        a, b = math.sin(th) / th, (1.0 - math.cos(th)) / (th * th)
    i3 = eye(3)
    return [[i3[r][c] + a * k[r][c] + b * kk[r][c] for c in range(3)] for r in range(3)]


def transform(pose: Pose, X: Sequence[float]) -> Vector:
    R, t = pose
    return [R[r][0] * X[0] + R[r][1] * X[1] + R[r][2] * X[2] + t[r] for r in range(3)]


def compose(a: Pose, b: Pose) -> Pose:
    """a after b."""
    return mul(a[0], b[0]), [x + y for x, y in zip(matvec(a[0], b[1]), a[1])]


def inverse(p: Pose) -> Pose:
    Rt = transpose(p[0])
    return Rt, [-x for x in matvec(Rt, p[1])]


def increment(delta: Sequence[float]) -> Pose:
    """The small motion X -> exp(w) X + v for delta = (w, v)."""
    return so3_exp(delta[:3]), list(delta[3:6])


def center(pose: Pose) -> Vector:
    return [-x for x in matvec(transpose(pose[0]), pose[1])]


def project(K, Xc: Sequence[float]) -> Optional[Tuple[float, float]]:
    if Xc[2] <= 1e-9:
        return None
    fx, fy, cx, cy = K
    return fx * Xc[0] / Xc[2] + cx, fy * Xc[1] / Xc[2] + cy


def backproject(K, u: float, v: float, z: float) -> Vector:
    fx, fy, cx, cy = K
    return [(u - cx) / fx * z, (v - cy) / fy * z, z]


def proj_jacobian(K, Xc: Sequence[float]) -> Tuple[Vector, Vector]:
    """Rows of d pi / d X_c."""
    fx, fy = K[0], K[1]
    z = Xc[2]
    return [fx / z, 0.0, -fx * Xc[0] / (z * z)], [0.0, fy / z, -fy * Xc[1] / (z * z)]


def point_motion_rows(X: Sequence[float]) -> List[Vector]:
    """d(exp(w) X + v)/d(w, v) at 0: [-[X]_x | I], as 3 rows of 6."""
    s = skew(X)
    return [[-s[r][0], -s[r][1], -s[r][2]] + [1.0 if c == r else 0.0 for c in range(3)] for r in range(3)]


# ------------------------------------------- 1. sparse image alignment

def sparse_alignment_setup(ref_img, K, feats):
    """The fixed data of inverse compositional alignment at one level: for
    each patch pixel the 3D point in the reference camera (all pixels of a
    patch take the depth of its feature), the reference value and the
    Jacobian row with respect to a motion of the reference point."""
    rows = []
    for (u, v, z) in feats:
        for o in PATCH4:
            q = (u + o[0], v + o[1])
            s = ref_img.sample(q[0], q[1])
            if s is None:
                continue
            X = backproject(K, q[0], q[1], z)
            gu, gv = proj_jacobian(K, X)
            gX = [s[1] * gu[k] + s[2] * gv[k] for k in range(3)]
            M = point_motion_rows(X)
            J = [sum(gX[r] * M[r][c] for r in range(3)) for c in range(6)]
            rows.append((X, s[0], J))
    return rows


def sparse_image_alignment(ref_pyr, cur_pyr, K, feats, init: Pose, min_level: int = 0, iters: int = 30):
    """The relative pose T (reference camera -> current camera) that
    minimizes sum (I_cur(pi(T X)) - I_ref(u))^2 over the 4 x 4 patches.
    feats are (u, v, depth) at level 0 of the reference. Inverse
    compositional: the Jacobian and H come from the reference image and are
    computed once per level; the update is T <- T exp(xi)^-1."""
    T = init
    for lev in range(len(cur_pyr) - 1, min_level - 1, -1):
        Kl = level_K(K, lev)
        f = 0.5 ** lev
        lf = [((u + 0.5) * f - 0.5, (v + 0.5) * f - 0.5, z) for (u, v, z) in feats]
        rows = sparse_alignment_setup(ref_pyr[lev], Kl, lf)

        def residuals(Tc):
            out = []
            for X, iref, J in rows:
                p = project(Kl, transform(Tc, X))
                s = cur_pyr[lev].sample(p[0], p[1]) if p else None
                out.append(None if s is None else s[0] - iref)
            return out

        def cost(rs):
            vals = [r for r in rs if r is not None]
            return sum(r * r for r in vals) / max(1, len(vals))

        rs = residuals(T)
        c0 = cost(rs)
        for _ in range(iters):
            H = [[0.0] * 6 for _ in range(6)]
            g = [0.0] * 6
            for (X, iref, J), r in zip(rows, rs):
                if r is None:
                    continue
                for a in range(6):
                    g[a] += J[a] * r
                    for b in range(6):
                        H[a][b] += J[a] * J[b]
            try:
                xi = solve(H, g)
            except ValueError:
                break
            cand = compose(T, inverse(increment(xi)))
            rs1 = residuals(cand)
            c1 = cost(rs1)
            if not c1 < c0:
                break
            T, rs, c0 = cand, rs1, c1
            if norm(xi) < 1e-12:
                break
    return T


# ---------------------------------------------------- 2. feature alignment

def affine_warp(K, ref_pose: Pose, cur_pose: Pose, u: Sequence[float], z: float, h: float = 2.0) -> Matrix:
    """The 2 x 2 matrix A that maps a small offset of pixel u in the
    reference keyframe to the offset in the current frame, for a patch on a
    plane parallel to the reference image at depth z (finite differences of
    the exact warp with step h)."""
    rel = compose(cur_pose, inverse(ref_pose))

    def warp(du, dv):
        return project(K, transform(rel, backproject(K, u[0] + du, u[1] + dv, z)))
    pu1, pu0, pv1, pv0 = warp(h, 0), warp(-h, 0), warp(0, h), warp(0, -h)
    return [[(pu1[0] - pu0[0]) / (2 * h), (pv1[0] - pv0[0]) / (2 * h)],
            [(pu1[1] - pu0[1]) / (2 * h), (pv1[1] - pv0[1]) / (2 * h)]]


def feature_alignment(cur_img, ref_img, u_ref: Sequence[float], A: Matrix, u0: Sequence[float],
                      iters: int = 20) -> Optional[Tuple[Tuple[float, float], float]]:
    """Gauss-Newton on (u, v, beta) for sum (I_cur(u + A o) - I_ref(u_ref + o) - beta)^2
    over the 8 x 8 patch. Returns the position and the RMS residual, or None."""
    ref = []
    for o in PATCH8:
        s = ref_img.sample(u_ref[0] + o[0], u_ref[1] + o[1])
        if s is None:
            return None
        ref.append((A[0][0] * o[0] + A[0][1] * o[1], A[1][0] * o[0] + A[1][1] * o[1], s[0]))

    def evaluate(p, with_j):
        out = []
        for du, dv, iv in ref:
            s = cur_img.sample(p[0] + du, p[1] + dv)
            if s is None:
                return None
            out.append((s[0] - iv - p[2], s[1], s[2]) if with_j else s[0] - iv - p[2])
        return out

    p = [u0[0], u0[1], 0.0]
    res = evaluate(p, True)
    if res is None:
        return None
    c0 = sum(r[0] ** 2 for r in res)
    for _ in range(iters):
        H = [[0.0] * 3 for _ in range(3)]
        g = [0.0] * 3
        for r, gx, gy in res:
            J = (gx, gy, -1.0)
            for a in range(3):
                g[a] -= J[a] * r
                for b in range(3):
                    H[a][b] += J[a] * J[b]
        try:
            step = solve(H, g)
        except ValueError:
            break
        cand = [p[k] + step[k] for k in range(3)]
        r1 = evaluate(cand, True)
        if r1 is None:
            break
        c1 = sum(r[0] ** 2 for r in r1)
        if not c1 < c0:
            break
        p, res, c0 = cand, r1, c1
        if norm(step) < 1e-12:
            break
    return (p[0], p[1]), math.sqrt(c0 / len(ref))


# ------------------------------------------- 3 and 4. bundle adjustment steps

def reprojection(K, pose: Pose, X, u) -> Optional[Vector]:
    p = project(K, transform(pose, X))
    return None if p is None else [p[0] - u[0], p[1] - u[1]]


def motion_only_ba(K, pose: Pose, obs, iters: int = 10) -> Tuple[Pose, List[float]]:
    """Gauss-Newton on the pose, with left updates, for the reprojection
    errors of obs = [(X world, u)]. A step is kept only if the cost goes
    down. Returns the pose and the costs of the kept steps."""
    def cost(p):
        s = 0.0
        for X, u in obs:
            e = reprojection(K, p, X, u)
            s += 1e18 if e is None else e[0] ** 2 + e[1] ** 2
        return s
    hist = [cost(pose)]
    for _ in range(iters):
        H = [[0.0] * 6 for _ in range(6)]
        g = [0.0] * 6
        for X, u in obs:
            Xc = transform(pose, X)
            e = reprojection(K, pose, X, u)
            gu, gv = proj_jacobian(K, Xc)
            M = point_motion_rows(Xc)
            for row, ei in ((gu, e[0]), (gv, e[1])):
                J = [sum(row[r] * M[r][c] for r in range(3)) for c in range(6)]
                for a in range(6):
                    g[a] -= J[a] * ei
                    for b in range(6):
                        H[a][b] += J[a] * J[b]
        try:
            step = solve(H, g)
        except ValueError:
            break
        cand = compose(increment(step), pose)
        c = cost(cand)
        if not c < hist[-1]:
            break
        pose = cand
        hist.append(c)
    return pose, hist


def structure_only_ba(K, X: Sequence[float], obs, iters: int = 5) -> Vector:
    """Gauss-Newton on one point for its observations [(pose, u)]."""
    X = list(X)

    def cost(P):
        s = 0.0
        for pose, u in obs:
            e = reprojection(K, pose, P, u)
            s += 1e18 if e is None else e[0] ** 2 + e[1] ** 2
        return s
    c0 = cost(X)
    for _ in range(iters):
        H = [[0.0] * 3 for _ in range(3)]
        g = [0.0] * 3
        for pose, u in obs:
            e = reprojection(K, pose, X, u)
            gu, gv = proj_jacobian(K, transform(pose, X))
            for row, ei in ((gu, e[0]), (gv, e[1])):
                J = [sum(row[r] * pose[0][r][c] for r in range(3)) for c in range(3)]
                for a in range(3):
                    g[a] -= J[a] * ei
                    for b in range(3):
                        H[a][b] += J[a] * J[b]
        try:
            step = solve(H, g)
        except ValueError:
            break
        cand = [X[k] + step[k] for k in range(3)]
        c1 = cost(cand)
        if not c1 < c0:
            break
        X, c0 = cand, c1
    return X


# ------------------------------------------------------------ depth filter

def gauss_pdf(x: float, mu: float, s: float) -> float:
    return math.exp(-0.5 * ((x - mu) / s) ** 2) / (s * math.sqrt(2.0 * math.pi))


class Seed:
    """The posterior of the inverse depth Z and the inlier ratio pi of one
    pixel, approximated by N(Z | mu, sigma2) Beta(pi | a, b)."""

    def __init__(self, kf: int, u: float, v: float, mu: float, z_range: float, a: float = 10.0, b: float = 10.0):
        self.kf, self.u, self.v = kf, u, v
        self.mu, self.sigma2, self.a, self.b = mu, z_range * z_range / 36.0, a, b
        self.z_range = z_range

    def update(self, x: float, tau2: float) -> None:
        """One measurement x with variance tau2, from the model
        pi N(x | Z, tau2) + (1 - pi) U(x). The new parameters match the first
        and second moments of Z and of pi under the exact posterior."""
        a, b, mu, s2 = self.a, self.b, self.mu, self.sigma2
        sn = 1.0 / (1.0 / s2 + 1.0 / tau2)
        m = sn * (mu / s2 + x / tau2)
        c1 = a / (a + b) * gauss_pdf(x, mu, math.sqrt(s2 + tau2))
        c2 = b / (a + b) / self.z_range
        c1, c2 = c1 / (c1 + c2), c2 / (c1 + c2)
        f = c1 * (a + 1.0) / (a + b + 1.0) + c2 * a / (a + b + 1.0)
        e = (c1 * (a + 1.0) * (a + 2.0) / ((a + b + 1.0) * (a + b + 2.0))
             + c2 * a * (a + 1.0) / ((a + b + 1.0) * (a + b + 2.0)))
        mu_new = c1 * m + c2 * mu
        self.sigma2 = c1 * (sn + m * m) + c2 * (s2 + mu * mu) - mu_new * mu_new
        self.mu = mu_new
        self.a = (e - f) / (f - e / f)
        self.b = self.a * (1.0 - f) / f


def depth_along_ray(f_ref: Sequence[float], f_cur: Sequence[float], rel: Pose) -> float:
    """The depth z of the reference point z f_ref (f with third entry 1)
    whose image in the current camera lies along f_cur: least squares on
    (R z f_ref + t) x f_cur = 0."""
    a = cross(matvec(rel[0], f_ref), f_cur)
    c = cross(rel[1], f_cur)
    return -dot(a, c) / dot(a, a)


def epipolar_measurement(K, ref_img, cur_img, ref_pose: Pose, cur_pose: Pose, seed: Seed, steps: int = 25,
                         px_sigma: float = 1.0):
    """Search the inverse depths in mu +- 2 sigma for the best zero-mean SSD of
    an 8 x 8 patch, refine the position by feature alignment, and
    triangulate. Returns (inverse depth, tau2) or None. tau is the change of
    the inverse depth for px_sigma pixels of error along the epipolar line."""
    rel = compose(cur_pose, inverse(ref_pose))
    sig = math.sqrt(seed.sigma2)
    lo, hi = max(1e-3, seed.mu - 2.0 * sig), seed.mu + 2.0 * sig
    ref = []
    for o in PATCH8:
        s = ref_img.sample(seed.u + o[0], seed.v + o[1])
        if s is None:
            return None
        ref.append(s[0])
    mref = sum(ref) / len(ref)
    best, best_c = None, math.inf
    for k in range(steps):
        x = lo + (hi - lo) * k / (steps - 1)
        p = project(K, transform(rel, backproject(K, seed.u, seed.v, 1.0 / x)))
        if p is None:
            continue
        vals = []
        for o in PATCH8:
            s = cur_img.sample(p[0] + o[0], p[1] + o[1])
            if s is None:
                break
            vals.append(s[0])
        if len(vals) < len(PATCH8):
            continue
        mv = sum(vals) / len(vals)
        c = sum((q - mv - r + mref) ** 2 for q, r in zip(vals, ref))
        if c < best_c:
            best, best_c = (x, p), c
    if best is None:
        return None
    x, p = best
    A = affine_warp(K, ref_pose, cur_pose, (seed.u, seed.v), 1.0 / x)
    got = feature_alignment(cur_img, ref_img, (seed.u, seed.v), A, p)
    if got is None:
        return None
    q = got[0]
    fx, fy, cx, cy = K
    f_ref = [(seed.u - cx) / fx, (seed.v - cy) / fy, 1.0]
    z = depth_along_ray(f_ref, [(q[0] - cx) / fx, (q[1] - cy) / fy, 1.0], rel)
    if z <= 0:
        return None
    # one pixel along the epipolar direction
    p_far = project(K, transform(rel, backproject(K, seed.u, seed.v, 1e6)))
    d = [q[0] - p_far[0], q[1] - p_far[1]] if p_far else [1.0, 0.0]
    nd = math.hypot(d[0], d[1]) or 1.0
    q1 = (q[0] + px_sigma * d[0] / nd, q[1] + px_sigma * d[1] / nd)
    z1 = depth_along_ray(f_ref, [(q1[0] - cx) / fx, (q1[1] - cy) / fy, 1.0], rel)
    tau = abs(1.0 / z - 1.0 / z1) if z1 > 0 else 1.0 / z
    return 1.0 / z, tau * tau


# -------------------------------------------------------- feature selection

def shi_tomasi_cells(img: GridImage, cell: int, min_score: float, margin: int = 5,
                     taken: Sequence[Tuple[float, float]] = ()) -> List[Tuple[int, int]]:
    """In each cell of size cell, the pixel with the highest Shi-Tomasi score
    (the smaller eigenvalue of the 3 x 3 structure tensor), if it is above
    min_score. Cells that already hold a point of taken are skipped."""
    busy = {(int(u) // cell, int(v) // cell) for u, v in taken}
    best: Dict[Tuple[int, int], Tuple[float, int, int]] = {}
    for v in range(margin, img.h - margin):
        for u in range(margin, img.w - margin):
            key = (u // cell, v // cell)
            if key in busy:
                continue
            sxx = syy = sxy = 0.0
            for dv in (-1, 0, 1):
                for du in (-1, 0, 1):
                    gx, gy = img.gx[v + dv][u + du], img.gy[v + dv][u + du]
                    sxx += gx * gx
                    syy += gy * gy
                    sxy += gx * gy
            tr, dt = sxx + syy, sxx * syy - sxy * sxy
            score = 0.5 * tr - math.sqrt(max(0.0, 0.25 * tr * tr - dt))
            if score > min_score and (key not in best or score > best[key][0]):
                best[key] = (score, u, v)
    return [(u, v) for _, u, v in sorted(best.values(), key=lambda t: (t[2], t[1]))]


def needs_keyframe(cur_pose: Pose, kf_poses: Sequence[Pose], mean_depth: float, ratio: float = 0.12) -> bool:
    """True if the camera center is farther than ratio * mean_depth from the
    center of every keyframe."""
    c = center(cur_pose)
    return all(norm([a - b for a, b in zip(c, center(p))]) > ratio * mean_depth for p in kf_poses)


# ------------------------------------------------------------------ system

class MapPoint:
    def __init__(self, X: Vector, obs: List[Tuple[int, Tuple[float, float]]]):
        self.X, self.obs = X, obs  # obs: (keyframe id, pixel)


def run_svo(frames: Sequence[GridImage], K, first_depth, levels: int = 2, cell: int = 8,
            min_score: float = 20.0, max_kfs: int = 4, kf_ratio: float = 0.12,
            converge: float = 200.0, d_range: Tuple[float, float] = (0.1, 0.5), px_sigma: float = 1.0) -> Dict:
    """Run the pipeline. first_depth(u, v) gives the depth of a pixel of
    frame 0 (the bootstrap). Returns the poses, the keyframe ids and the map."""
    poses: List[Pose] = [(eye(3), [0.0, 0.0, 0.0])]
    kfs: Dict[int, Pose] = {0: poses[0]}  # @line L1
    pyrs = [pyramid(frames[0], levels)]
    points: List[MapPoint] = []
    for (u, v) in shi_tomasi_cells(frames[0], cell, min_score):
        points.append(MapPoint(backproject(K, u, v, first_depth(u, v)), [(0, (float(u), float(v)))]))  # @line L1
    seeds: List[Seed] = []
    added = 0
    for k in range(1, len(frames)):  # @line L2
        pyrs.append(pyramid(frames[k], levels))
        prev = poses[-1]
        feats = []
        for P in points:
            Xc = transform(prev, P.X)
            p = project(K, Xc)
            if p and 5 <= p[0] <= frames[0].w - 6 and 5 <= p[1] <= frames[0].h - 6:
                feats.append((p[0], p[1], Xc[2]))
        rel = sparse_image_alignment(pyrs[k - 1], pyrs[k], K, feats, (eye(3), [0.0, 0.0, 0.0]))  # @line L3
        pose = compose(rel, prev)  # @line L3
        obs, used = [], []
        for P in points:  # @line L4
            p = project(K, transform(pose, P.X))
            if not p or not (5 <= p[0] <= frames[k].w - 6 and 5 <= p[1] <= frames[k].h - 6):
                continue
            cdir = center(pose)
            view = [a - b for a, b in zip(P.X, cdir)]
            best = None
            for fid, uref in P.obs:  # the keyframe with the closest viewing direction
                kdir = [a - b for a, b in zip(P.X, center(kfs[fid]))]
                ang = dot(view, kdir) / (norm(view) * norm(kdir))
                if best is None or ang > best[0]:
                    best = (ang, fid, uref)
            _, fid, uref = best
            z = transform(kfs[fid], P.X)[2]
            A = affine_warp(K, kfs[fid], pose, uref, z)
            got = feature_alignment(frames[k], frames[fid], uref, A, p)  # @line L4
            if got is None or got[1] > 10.0:
                continue
            obs.append((P.X, got[0]))
            used.append((P, got[0]))
        if len(obs) >= 6:
            pose, _ = motion_only_ba(K, pose, obs)  # @line L5
        for P, u in used:  # @line L6
            P.X = structure_only_ba(K, P.X, [(kfs[f], q) for f, q in P.obs] + [(pose, u)])  # @line L6
        poses.append(pose)
        keep = []
        for s in seeds:  # @line L7
            m = epipolar_measurement(K, frames[s.kf], frames[k], kfs[s.kf], pose, s, px_sigma=px_sigma)  # @line L7
            if m is not None:
                s.update(*m)  # @line L7
            if math.sqrt(s.sigma2) < s.z_range / converge:  # @line L7
                X = transform(inverse(kfs[s.kf]), backproject(K, s.u, s.v, 1.0 / s.mu))
                points.append(MapPoint(X, [(s.kf, (s.u, s.v))]))
                added += 1
            else:
                keep.append(s)
        seeds = keep
        depths = [transform(pose, P.X)[2] for P, _ in used] or [1.0]
        if needs_keyframe(pose, list(kfs.values()), sum(depths) / len(depths), kf_ratio):  # @line L8
            kfs[k] = pose  # @line L9
            for P, u in used:
                P.obs.append((k, u))
            if len(kfs) > max_kfs:  # @line L9
                c = center(pose)
                far = max((f for f in kfs if f != k), key=lambda f: norm([a - b for a, b in zip(center(kfs[f]), c)]))
                del kfs[far]
                for P in points:
                    P.obs = [o for o in P.obs if o[0] != far]
                points = [P for P in points if P.obs]
                seeds = [s for s in seeds if s.kf != far]
            taken = [u for _, u in used] + [(s.u, s.v) for s in seeds if s.kf == k]
            mu0 = 0.5 * (d_range[0] + d_range[1])
            for (u, v) in shi_tomasi_cells(frames[k], cell, min_score, taken=taken):  # @line L9
                seeds.append(Seed(k, float(u), float(v), mu0, d_range[1]))
    return {"poses": poses, "keyframes": sorted(kfs), "points": points, "added": added}  # @line L10
test_semi_direct_visual_odometry.py 268 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/semi-direct-visual-odometry/. The authors are listed in prov/BR51JE.jsonl.
"""Tests for semi_direct_visual_odometry.

Most tests use an analytic image: the exact image of a textured plane, so
the steps can be checked to high accuracy. The depth filter update is
compared with moments computed by numerical integration. The last test runs
the whole pipeline on pixel grids.
"""

import math
import os
import random
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import semi_direct_visual_odometry as svo  # noqa: E402
from cvla import matvec, mul, norm, transpose  # noqa: E402

K = (40.0, 40.0, 23.5, 17.5)
W, H = 48, 36
IDENT = (svo.eye(3), [0.0, 0.0, 0.0])


def radiance(x, y):
    return (120.0 + 35.0 * math.sin(1.3 * x + 0.5 * y) + 30.0 * math.cos(0.7 * x - 1.6 * y)
            + 25.0 * math.sin(2.1 * x + 1.5 * y) + 20.0 * math.cos(1.9 * x - 2.4 * y))


class Plane:
    """The world plane Z = z0 + sx X with the texture radiance(X, Y)."""

    def __init__(self, z0, sx=0.0):
        self.z0, self.sx = z0, sx

    def depth(self, pose, u, v, Kl=K):
        fx, fy, cx, cy = Kl
        c = svo.center(pose)
        ray = matvec(transpose(pose[0]), [(u - cx) / fx, (v - cy) / fy, 1.0])
        return (self.z0 + self.sx * c[0] - c[2]) / (ray[2] - self.sx * ray[0])


class AnalyticImage:
    """The exact image L + b of a plane seen by a camera, with
    central-difference gradients and the border rule of GridImage."""

    def __init__(self, plane, pose, b=0.0, Kl=K, w=W, h=H):
        self.plane, self.Kl, self.w, self.h, self.b = plane, Kl, w, h, b
        self.rt, self.c = transpose(pose[0]), svo.center(pose)

    def value(self, u, v):
        fx, fy, cx, cy = self.Kl
        x, y = (u - cx) / fx, (v - cy) / fy
        rt, c, pl = self.rt, self.c, self.plane
        ray = [rt[i][0] * x + rt[i][1] * y + rt[i][2] for i in range(3)]
        s = (pl.z0 + pl.sx * c[0] - c[2]) / (ray[2] - pl.sx * ray[0])
        return radiance(c[0] + s * ray[0], c[1] + s * ray[1]) + self.b

    def sample(self, u, v):
        if not (1.0 <= u <= self.w - 2.0 and 1.0 <= v <= self.h - 2.0):
            return None
        e = 1e-4
        return (self.value(u, v), (self.value(u + e, v) - self.value(u - e, v)) / (2 * e),
                (self.value(u, v + e) - self.value(u, v - e)) / (2 * e))


def analytic_pyramid(plane, pose, levels):
    return [AnalyticImage(plane, pose, 0.0, svo.level_K(K, l), W >> l, H >> l) for l in range(levels)]


def make_pose(w, c):
    R = svo.so3_exp(w)
    return R, [-x for x in matvec(R, c)]


def pose_err(p, q):
    rd = mul(p[0], transpose(q[0]))
    ang = 2.0 * math.asin(min(1.0, norm([[rd[i][j] - (i == j) for j in range(3)] for i in range(3)]) / math.sqrt(8)))
    return ang, norm([a - b for a, b in zip(p[1], q[1])])


def grid(step, margin=7):
    return [(float(u), float(v)) for v in range(margin, H - margin, step) for u in range(margin, W - margin, step)]


def test_inverse_compositional_jacobian():
    plane = Plane(5.0)
    img = AnalyticImage(plane, IDENT)
    feats = [(17.3, 12.6, 5.0), (30.2, 21.4, 5.0)]
    rows = svo.sparse_alignment_setup(img, K, feats)
    assert len(rows) == 2 * 16
    e = 1e-6
    for X, iref, J in rows[::7]:
        p = svo.project(K, X)
        assert abs(img.sample(*p)[0] - iref) < 1e-9
        for k in range(6):
            d = [0.0] * 6
            d[k] = e
            hi = img.sample(*svo.project(K, svo.transform(svo.increment(d), X)))[0]
            d[k] = -e
            lo = img.sample(*svo.project(K, svo.transform(svo.increment(d), X)))[0]
            num = (hi - lo) / (2 * e)
            assert abs(num - J[k]) <= 1e-4 * (1.0 + abs(num))


def test_sparse_image_alignment_recovers_motion():
    plane = Plane(5.0)
    truth = make_pose([0.004, -0.007, 0.003], [0.1, -0.05, 0.12])
    rp, cp = analytic_pyramid(plane, IDENT, 2), analytic_pyramid(plane, truth, 2)
    feats = [(u, v, 5.0) for u, v in grid(6)]
    T = svo.sparse_image_alignment(rp, cp, K, feats, IDENT)
    ang, dt = pose_err(T, truth)
    assert ang < 1e-7 and dt < 1e-6


def test_affine_warp_and_feature_alignment():
    plane = Plane(5.0)
    # moving toward a fronto-parallel plane scales the image by z / (z - 1)
    A = svo.affine_warp(K, IDENT, make_pose([0, 0, 0], [0.0, 0.0, 1.0]), (20.0, 15.0), 5.0)
    assert abs(A[0][0] - 1.25) < 1e-9 and abs(A[1][1] - 1.25) < 1e-9
    assert abs(A[0][1]) < 1e-9 and abs(A[1][0]) < 1e-9
    # a sideways move shifts the image by f t / z; the 2D alignment finds it
    # from a start 1.3 pixels away, with a brightness offset of 6
    cur = make_pose([0, 0, 0], [0.3, -0.2, 0.0])
    ref_img, cur_img = AnalyticImage(plane, IDENT), AnalyticImage(plane, cur, 6.0)
    A = svo.affine_warp(K, IDENT, cur, (20.0, 15.0), 5.0)
    assert abs(A[0][0] - 1) < 1e-9 and abs(A[1][1] - 1) < 1e-9
    want = (20.0 - 40.0 * 0.3 / 5.0, 15.0 + 40.0 * 0.2 / 5.0)
    (u, v), rms = svo.feature_alignment(cur_img, ref_img, (20.0, 15.0), A, (want[0] + 1.0, want[1] - 0.8))
    assert abs(u - want[0]) < 1e-6 and abs(v - want[1]) < 1e-6
    assert rms < 1e-6


def test_motion_only_ba():
    rng = random.Random(4)
    truth = make_pose([0.02, -0.03, 0.01], [0.3, 0.1, -0.2])
    obs = []
    for _ in range(20):
        X = [rng.uniform(-2, 2), rng.uniform(-1.5, 1.5), rng.uniform(4, 8)]
        obs.append((X, svo.project(K, svo.transform(truth, X))))
    start = (mul(svo.so3_exp([0.02, 0.01, -0.015]), truth[0]), [a + b for a, b in zip(truth[1], [0.05, -0.04, 0.06])])
    pose, hist = svo.motion_only_ba(K, start, obs)
    assert all(x > y for x, y in zip(hist, hist[1:]))
    ang, dt = pose_err(pose, truth)
    assert ang < 1e-9 and dt < 1e-9


def test_structure_only_ba():
    X = [0.4, -0.3, 5.5]
    poses = [IDENT, make_pose([0, 0.02, 0], [0.3, 0, 0]), make_pose([0.01, 0, 0], [0.5, 0.1, 0.05])]
    obs = [(p, svo.project(K, svo.transform(p, X))) for p in poses]
    got = svo.structure_only_ba(K, [0.5, -0.2, 6.0], obs, iters=10)
    assert norm([a - b for a, b in zip(got, X)]) < 1e-9


def simpson(f, a, b, n=2000):
    h = (b - a) / n
    s = f(a) + f(b)
    for i in range(1, n):
        s += (4 if i % 2 else 2) * f(a + i * h)
    return s * h / 3


def test_depth_filter_update_matches_numerical_moments():
    seed = svo.Seed(0, 10.0, 10.0, mu=0.25, z_range=0.5, a=6.0, b=3.0)
    seed.sigma2 = 0.04 ** 2
    a, b, mu, s2, zr = seed.a, seed.b, seed.mu, seed.sigma2, seed.z_range
    x, tau2 = 0.28, 0.03 ** 2
    seed.update(x, tau2)
    # posterior p(Z, pi) ~ (pi N(x | Z, tau2) + (1 - pi) / zr) N(Z | mu, s2) Beta(pi | a, b)
    beta = math.gamma(a + b) / (math.gamma(a) * math.gamma(b))

    def bpdf(p):
        return beta * p ** (a - 1) * (1 - p) ** (b - 1)

    def zpdf(z):
        return svo.gauss_pdf(z, mu, math.sqrt(s2))

    lo, hi = mu - 12 * math.sqrt(s2), mu + 12 * math.sqrt(s2)
    zin = [simpson(lambda z, k=k: z ** k * svo.gauss_pdf(x, z, math.sqrt(tau2)) * zpdf(z), lo, hi) for k in range(3)]
    zout = [simpson(lambda z, k=k: z ** k * zpdf(z) / zr, lo, hi) for k in range(3)]
    pin = [simpson(lambda p, k=k: p ** (k + 1) * bpdf(p), 0, 1) for k in range(3)]
    pout = [simpson(lambda p, k=k: p ** k * (1 - p) * bpdf(p), 0, 1) for k in range(3)]
    norm0 = zin[0] * pin[0] + zout[0] * pout[0]
    ez = (zin[1] * pin[0] + zout[1] * pout[0]) / norm0
    ez2 = (zin[2] * pin[0] + zout[2] * pout[0]) / norm0
    ep = (zin[0] * pin[1] + zout[0] * pout[1]) / norm0
    ep2 = (zin[0] * pin[2] + zout[0] * pout[2]) / norm0
    assert abs(seed.mu - ez) < 1e-9
    assert abs(seed.sigma2 - (ez2 - ez * ez)) < 1e-9
    fa, fb = seed.a, seed.b
    assert abs(fa / (fa + fb) - ep) < 1e-8
    assert abs(fa * (fa + 1) / ((fa + fb) * (fa + fb + 1)) - ep2) < 1e-8


def test_depth_filter_converges_and_rejects_outliers():
    rng = random.Random(11)
    seed = svo.Seed(0, 10.0, 10.0, mu=0.3, z_range=0.5)
    for k in range(40):
        if k % 4 == 3:
            seed.update(rng.uniform(0.0, 0.5), 0.01 ** 2)
        else:
            seed.update(rng.gauss(0.2, 0.01), 0.01 ** 2)
    assert abs(seed.mu - 0.2) < 0.005
    assert math.sqrt(seed.sigma2) < 0.003
    assert 0.6 < seed.a / (seed.a + seed.b) < 0.9
    bad = svo.Seed(0, 10.0, 10.0, mu=0.3, z_range=0.5)
    for _ in range(20):
        bad.update(rng.uniform(0.0, 0.5), 0.01 ** 2)
    # pure outliers push the inlier ratio down from its start of 0.5
    assert bad.a / (bad.a + bad.b) < 0.4


def test_epipolar_measurement_and_depth_along_ray():
    rel = make_pose([0.01, -0.02, 0.005], [0.4, 0.1, -0.1])
    Xr = [0.3, -0.2, 4.0]
    fr = [Xr[0] / Xr[2], Xr[1] / Xr[2], 1.0]
    Xc = svo.transform(rel, Xr)
    assert abs(svo.depth_along_ray(fr, [Xc[0] / Xc[2], Xc[1] / Xc[2], 1.0], rel) - 4.0) < 1e-12
    plane = Plane(4.0)
    cur = make_pose([0, 0, 0], [0.35, 0.05, 0.0])
    seed = svo.Seed(0, 22.0, 16.0, mu=0.3, z_range=0.5)
    x, tau2 = svo.epipolar_measurement(K, AnalyticImage(plane, IDENT), AnalyticImage(plane, cur, 4.0), IDENT, cur, seed)
    assert abs(x - 0.25) < 1e-6
    # one pixel along the epipolar line is 1 / (f |t|) in inverse depth for this motion
    assert abs(math.sqrt(tau2) - 1.0 / (40.0 * math.hypot(0.35, 0.05))) < 1e-9


def test_needs_keyframe_by_hand():
    kfs = [IDENT, make_pose([0, 0, 0], [1.0, 0.0, 0.0])]
    assert not svo.needs_keyframe(make_pose([0, 0, 0], [0.5, 0.0, 0.0]), kfs, 5.0)  # 0.5 < 0.6
    assert svo.needs_keyframe(make_pose([0, 0, 0], [0.5, 0.7, 0.0]), kfs, 5.0)


def test_shi_tomasi_cells():
    flat = svo.GridImage([[80.0] * 32 for _ in range(32)])
    assert svo.shi_tomasi_cells(flat, 16, 1.0) == []
    # a bright square with one corner in each 16 x 16 cell; straight edges
    # have a zero smaller eigenvalue, so only the corners are found
    sq = svo.GridImage([[200.0 if 8 <= u < 24 and 8 <= v < 24 else 0.0 for u in range(32)] for v in range(32)])
    got = svo.shi_tomasi_cells(sq, 16, 1.0)
    assert len(got) == 4 and len({(u // 16, v // 16) for u, v in got}) == 4
    for u, v in got:
        assert min(abs(u - 7.5), abs(u - 23.5)) <= 1.5 and min(abs(v - 7.5), abs(v - 23.5)) <= 1.5
    assert svo.shi_tomasi_cells(sq, 16, 1.0, taken=[(20.0, 20.0)]) == [p for p in got if (p[0] // 16, p[1] // 16) != (1, 1)]


def test_run_svo_on_pixel_grids():
    # Bilinear sampling of a pixel grid is not the true image, so the
    # estimates are not exact here; the bounds are loose on purpose.
    plane = Plane(5.0, 0.1)
    n = 8
    truth = [make_pose([0.0, 0.003 * k, 0.001 * k], [0.12 * k, 0.02 * k, 0.03 * k]) for k in range(n)]
    frames = []
    for pose in truth:
        img = AnalyticImage(plane, pose)
        frames.append(svo.GridImage([[img.value(u, v) for u in range(W)] for v in range(H)]))
    out = svo.run_svo(frames, K, lambda u, v: plane.depth(IDENT, u, v), levels=2, cell=8, kf_ratio=0.05,
                      converge=50.0, px_sigma=0.2)
    assert len(out["keyframes"]) >= 3
    assert out["added"] > 0  # some seeds converged and became map points
    path = sum(norm([a - b for a, b in zip(svo.center(truth[k]), svo.center(truth[k - 1]))]) for k in range(1, n))
    for k in range(n):
        ang, _ = pose_err(out["poses"][k], truth[k])
        dc = norm([a - b for a, b in zip(svo.center(out["poses"][k]), svo.center(truth[k]))])
        assert ang < math.radians(1.0)
        assert dc < 0.1 * path

History

Feature-based visual odometry, such as the system of Nister, Naroditsky and Bergen (2004), matched corners and estimated the motion from the matches. Direct methods, such as DTAM (2011), aligned image intensities and were slow on small computers. Forster, Pizzoli and Scaramuzza combined the two at ICRA 2014: a direct sparse alignment for the motion, a feature step for precision, and the depth filter of Vogiatzis and Hernandez (2011) for new points, with the tracking and mapping split into two threads as in PTAM. The extended version of Forster, Zhang, Gassner, Werlberger and Scaramuzza in IEEE Transactions on Robotics (2017) added several cameras, other camera models and edgelets.

References

  1. Christian Forster, Matia Pizzoli and Davide Scaramuzza, SVO: Fast semi-direct monocular visual odometry, IEEE International Conference on Robotics and Automation (ICRA), 2014, 15-22, the motion estimation (sparse model-based image alignment, feature alignment, pose and structure refinement) and the mapping with the depth filter
  2. Christian Forster, Zichao Zhang, Michael Gassner, Manuel Werlberger and Davide Scaramuzza, SVO: Semidirect visual odometry for monocular and multicamera systems, IEEE Transactions on Robotics 33(2), 2017, 249-265, the extended system for several cameras and other camera models
  3. George Vogiatzis and Carlos Hernandez, Video-based, real-time multi-view stereo, Image and Vision Computing 29(7), 2011, 434-441, the Gaussian times Beta depth filter and its moment-matching update
  4. Simon Baker and Iain Matthews, Lucas-Kanade 20 years on: a unifying framework, International Journal of Computer Vision 56(3), 2004, 221-255, the inverse compositional algorithm used by the sparse image alignment

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