Algorithm Search⌘K

Algorithmresearch

Direct sparse odometry

Also called DSO.

Track a camera by minimizing the photometric error of sparse high-gradient pixels, and optimize poses, inverse depths and affine brightness jointly over a window of keyframes.

Time
O(N (L k m + c s + k n W^2 + k W^3)) worst · averageO(N (L m + c s)) best
Space
O(n W + W^2) extra
Where
L = the number of pyramid levels; N = the number of frames; W = the number of keyframes in the window; c = the number of candidate points; k = the number of Gauss-Newton iterations; m = the number of points of the newest keyframe; n = the number of active points in the window; s = the number of steps of the depth search
Properties
deterministicnot exactiterativeonline
Origin
Jakob Engel, Vladlen Koltun, Daniel Cremers, 2016

Direct sparse odometry (DSO) is the visual odometry method of Engel, Koltun and Cremers that works on pixel intensities instead of matched features. It uses a sparse set of pixels with a large gradient, and gives each pixel one inverse depth in the keyframe where it was first seen. The cost is the photometric error of small pixel patterns between keyframes, with an affine brightness change per frame. All poses, brightness terms and inverse depths of a small window of keyframes are optimized together by Gauss-Newton, and old keyframes leave the window by marginalization with the Schur complement. New frames are tracked against the newest keyframe by direct image alignment. With one camera the result has an unknown scale, which the first depths fix.

In plain words

A camera moves, and you want its path. You do not look for corners and match them. You pick pixels where the brightness changes fast, and you guess how far away each one is. If the guesses for the motion and the distances are right, each pixel has the same brightness in the next picture, up to a change of exposure. So you change the motion, the distances and two brightness numbers per picture until the brightness values agree as well as possible. You do this for a few recent key pictures at the same time. When a key picture gets old, you remove it, but you keep what it told you about the others as a summary.

The problem

The input is a sequence of frames of a calibrated camera with pinhole intrinsics (fx,fy,cx,cy)(f_x, f_y, c_x, c_y), and the inverse depths of the points of the first frame (they fix the scale). 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 and an affine brightness pair (a,b)(a, b) for each frame.

Points and residuals. A point pp lives in a host keyframe ii with an inverse depth dpd_p. For a pattern of 8 pixel offsets oo around pp, each pattern pixel q=p+oq = p + o is moved into a target keyframe jj by

q′=Π(Rji Π−1(q,dp)+tji),(Rji,tji)=TjTi−1,q' = \Pi\big(R_{ji}\, \Pi^{-1}(q, d_p) + t_{ji}\big), \qquad (R_{ji}, t_{ji}) = T_j T_i^{-1},

with Π−1(q,d)=((qx−cx)/(fxd), (qy−cy)/(fyd), 1/d)\Pi^{-1}(q, d) = \big((q_x - c_x)/(f_x d),\ (q_y - c_y)/(f_y d),\ 1/d\big). All 8 pixels share the same inverse depth. The residual is

rq=(Ij[q′]−bj)−eaj−ai(Ii[q]−bi),r_q = \big(I_j[q'] - b_j\big) - e^{a_j - a_i}\big(I_i[q] - b_i\big),

and the energy of the window is

E=∑i∑p∈Pi∑j≠i∑qwq ρk(rq),wq=c2c2+∣∇Ii(q)∣2,E = \sum_{i} \sum_{p \in P_i} \sum_{j \ne i} \sum_{q} w_q\, \rho_k(r_q), \qquad w_q = \frac{c^2}{c^2 + |\nabla I_i(q)|^2},

where ρk\rho_k is the Huber function with threshold kk (see Huber M-estimator) and wqw_q lowers the weight of pixels with a very large gradient. The paper also has the exposure times tit_i in the brightness factor and priors λaa2+λbb2\lambda_a a^2 + \lambda_b b^2 on the affine terms; the code takes all exposure times as 1 and has no such priors.

The algorithm

  1. DSO(frames F₀ … F_{N-1}, inverse depths of the points of F₀, window size W, threshold T_kf)
  2. 1keyframe 0 ← F₀ with pose (I, 0), a = b = 0, held fixed; active points ← selected pixels of F₀ with their inverse depths, one depth held fixed
  3. 2for j ← 1 to N - 1 do
  4. 3(T_j, a_j, b_j) ← direct alignment of F_j against the newest keyframe, coarse to fine, from a constant motion guess
  5. 4for each candidate pixel of the newest keyframe do inverse depth ← search along the epipolar line in F_j, then Gauss-Newton on that depth
  6. 5if w_f f + w_ft f_t + w_a a ≤ T_kf then continue ▷ not a keyframe
  7. 6make the candidates with an inverse depth active points of the newest keyframe
  8. 7add F_j to the window as a keyframe with the pose and affine terms from L3
  9. 8build the Gauss-Newton system of E over all free poses, affine terms and inverse depths
  10. 9remove the inverse depths by the Schur complement, solve, back-substitute; keep the step only if E goes down; repeat up to the limit
  11. 10m ← the keyframe chosen by the marginalization rule, if any
  12. 11marginalize m and its points into the prior by the Schur complement; drop the residuals of other points in m
  13. 12select new candidate pixels in F_j
  14. 13return the poses and affine terms of all frames

Tracking (L3). For a new frame, the energy has only the residuals from the points of the newest keyframe into the new frame. The unknowns are the 6 pose parameters and (aj,bj)(a_j, b_j) of the new frame; the keyframe and the depths stay fixed. This is Gauss-Newton on an 8-parameter problem with the weights wqw_q times the Huber weights, as in iteratively reweighted least squares. It runs from the coarsest level of an image pyramid to the finest. The start is the last pose times the last motion (a constant velocity guess). The pose update is on the left: R←exp⁡([ω]×)RR \leftarrow \exp([\omega]_\times) R, t←exp⁡([ω]×)t+vt \leftarrow \exp([\omega]_\times) t + v.

Candidates (L4, L6, L12). Points are chosen by a gradient threshold per region: in each block the threshold is the median gradient of the block plus a constant gthg_{th}, and the strongest pixel above it is kept. Later passes use blocks of twice and four times the size and a lower threshold, so that some points are found in weak regions too. A candidate gets its inverse depth from a discrete search along the epipolar line in the new frame and a few Gauss-Newton steps on the depth alone.

Keyframes (L5). ff is the root mean square of the pixel shift of the points from the keyframe to the new frame, ftf_t is the same shift with the rotation set to the identity, and a=∣aj−ai∣a = |a_j - a_i| measures the change in exposure. The paper uses this rule with weights that it chose; it is a heuristic (see keyframe selection).

Window optimization (L8, L9). Each residual depends on one inverse depth only, so the depth block of the Gauss-Newton matrix is diagonal. With the unknowns split into keyframe blocks xαx_\alpha (8 per keyframe) and depths xβx_\beta,

(HααHαβHβαHββ)(xαxβ)=(bαbβ),\begin{pmatrix} H_{\alpha\alpha} & H_{\alpha\beta} \\ H_{\beta\alpha} & H_{\beta\beta} \end{pmatrix} \begin{pmatrix} x_\alpha \\ x_\beta \end{pmatrix} = \begin{pmatrix} b_\alpha \\ b_\beta \end{pmatrix},

the code solves (Hαα−HαβHββ−1Hβα) xα=bα−HαβHββ−1bβ(H_{\alpha\alpha} - H_{\alpha\beta} H_{\beta\beta}^{-1} H_{\beta\alpha})\, x_\alpha = b_\alpha - H_{\alpha\beta} H_{\beta\beta}^{-1} b_\beta and then xβ=Hββ−1(bβ−Hβαxα)x_\beta = H_{\beta\beta}^{-1}(b_\beta - H_{\beta\alpha} x_\alpha), the same structure as the reduced camera system of bundle adjustment. A step is kept only if the energy goes down. The first keyframe (pose and affine terms) and one inverse depth are held fixed; they remove the 7 degrees of freedom of a similarity of the scene and the 2 of the brightness, see gauge freedom.

Marginalization (L10, L11). The window keeps the two newest keyframes. A keyframe with less than 5 percent of its points visible in the newest frame leaves first. Otherwise, if the window is too large, the keyframe ii that maximizes d(i,1)∑j(d(i,j)+ϵ)−1\sqrt{d(i, 1)} \sum_{j} (d(i, j) + \epsilon)^{-1} leaves, where dd is the distance between camera centers and keyframe 1 is the newest. This keeps keyframes spread out in space and close to the newest one; it is a heuristic. To remove keyframe mm, the code drops the residuals of other points into mm, builds the Gauss-Newton system, and takes the Schur complement over the block of mm and the depths of its points. The result H^,b^\hat H, \hat b is a quadratic prior −b^Tx+12xTH^x-\hat b^{\mathsf T} x + \frac{1}{2} x^{\mathsf T} \hat H x on the remaining keyframes, where xx is their change from the state at the time of marginalization.

Differences from the paper. The code leaves out the photometric calibration (response function and vignetting), the First Estimate Jacobians (the paper evaluates the Jacobians of variables connected to the prior at their linearization point, to keep the prior consistent), the outlier rules, the recovery after a tracking failure, the activation rule for candidates by their distance to other points, and the initialization from the first frames. A candidate is searched only in the frame just before the keyframe decision, not tracked over many frames. The 8 pattern offsets are this code's choice. The paper uses a window of 7 keyframes and about 2000 active points; the tests use 3 keyframes and about 50 points.

Example

One residual. A pattern pixel has Ii[q]=100I_i[q] = 100 in its host, with ai=0.1a_i = 0.1, bi=3b_i = 3, and the target has aj=−0.2a_j = -0.2, bj=7b_j = 7. The predicted target value is 7+e−0.3(100−3)=7+0.740818⋅97=78.8597 + e^{-0.3}(100 - 3) = 7 + 0.740818 \cdot 97 = 78.859. If the target image has Ij[q′]=80I_j[q'] = 80, the residual is r=1.141r = 1.141. With ∣∇Ii(q)∣=30|\nabla I_i(q)| = 30 and c=50c = 50, the weight is 2500/3400=0.73532500 / 3400 = 0.7353. With the Huber threshold k=9k = 9 the residual is in the quadratic part, so its energy is 12⋅1.1412⋅0.7353=0.478\frac{1}{2} \cdot 1.141^2 \cdot 0.7353 = 0.478. A residual of 20 would cost 0.7353⋅9⋅(20−4.5)=102.60.7353 \cdot 9 \cdot (20 - 4.5) = 102.6 instead of 147.1147.1.

Keyframe score. Take a point at the principal point with inverse depth 0.20.2 (depth 5), fx=40f_x = 40, and a new frame that moved 0.50.5 sideways without rotation. The point moves 40⋅0.5/5=440 \cdot 0.5 / 5 = 4 pixels, so f=ft=4f = f_t = 4. With ai=0.1a_i = 0.1 and aj=0.4a_j = 0.4, a=0.3a = 0.3. With wf=1w_f = 1, wft=2w_{ft} = 2, wa=10w_a = 10 the score is 4+8+3=154 + 8 + 3 = 15. For a pure rotation by 0.010.01 radians about the vertical axis the shift is 40tan⁡0.01=0.440 \tan 0.01 = 0.4 pixels for ff and 0 for ftf_t. The ftf_t term grows only with translation, which is what makes new depths observable.

A synthetic run. The tests render a textured slanted plane at depth about 5 into 48×3648 \times 36 images with fx=fy=40f_x = f_y = 40. The exact (analytic) images make every residual zero at the truth: from a start at the identity, tracking recovers a pose and (a,b)(a, b) within 10−610^{-6}, and a window of three keyframes recovers poses and depths within 10−610^{-6} from a perturbed start, also after one keyframe is marginalized. On pixel grids, with 7 frames, 2 pyramid levels and a window of 3 keyframes, the largest rotation error was 0.490.49 degrees and the largest position error 0.0450.045 on a path of length 0.750.75. Bilinear sampling of the grid is not the true image, and a small rotation about the vertical axis looks like a sideways move, so the errors grow along the path. These numbers are one synthetic run, not a property of the method.

Correctness

The full proof is in proofs/correctness.md. It covers exact data: the images are exact images of the scene under the affine brightness model, and the pattern of each point lies on a plane parallel to its host image (so one inverse depth fits all 8 pixels). Under these assumptions it shows that the true state makes every residual zero and is a global minimizer of the tracking energy, of the window energy and of the window energy with the prior after any number of marginalizations; that the true state is a fixed point of every Gauss-Newton step; that the Schur steps solve the full linear system exactly; and that the window energy never goes up, because a step is kept only when it decreases the energy. It does not prove convergence from a far start. Gauss-Newton on the photometric error converges only locally, roughly within the range where the image is close to linear (the paper uses a rule of thumb of 1 to 2 pixels at the finest level), which is the reason for the pyramid and the constant motion guess.

Proof: On exact images the true state is a global minimizer and a fixed point of every step, the Schur steps are exact, and the window energy never goes upfull

Setting. A state is the list of keyframe poses TiT_i, affine terms (ai,bi)(a_i, b_i) and inverse depths dpd_p. The residual of a pattern pixel qq of a point pp hosted in keyframe ii and seen in target jj is rq=(Ij[q′]−bj)−eaj−ai(Ii[q]−bi)r_q = (I_j[q'] - b_j) - e^{a_j - a_i}(I_i[q] - b_i) with q′=Π(RjiΠ−1(q,dp)+tji)q' = \Pi(R_{ji} \Pi^{-1}(q, d_p) + t_{ji}). The tracking energy (line L3) and the window energy (lines L8 and L9) are sums of wqρk(rq)w_q \rho_k(r_q), with wq=c2/(c2+∣∇Ii(q)∣2)>0w_q = c^2/(c^2 + |\nabla I_i(q)|^2) > 0 and the Huber function ρk≥0\rho_k \ge 0, ρk(r)=0\rho_k(r) = 0 only for r=0r = 0. After a marginalization (line L11), a prior P(x)=−b^Tx+12xTH^xP(x) = -\hat b^{\mathsf T} x + \frac{1}{2} x^{\mathsf T} \hat H x is added, where xx is the change of the remaining keyframes from their values at that time.

Assumptions. (B1) Exact images: there is a true state such that every image is Ij[u]=eajL(X(u))+bjI_j[u] = e^{a_j} L(X(u)) + b_j, where X(u)X(u) is the scene point seen at pixel uu in frame jj and LL is its radiance. (B2) Each point's pattern lies on a plane parallel to the image plane of its host, so the true inverse depth of all 8 pattern pixels is dpd_p. (B3) Every sample used is inside its image. (B4) At line L11 the state is the true state. The first keyframe and one inverse depth are held at their true values, as the algorithm does.

Lemma 1 (zero residuals). At the true state every residual is zero. By (B2), Π−1(q,dp)\Pi^{-1}(q, d_p) is the true host camera point of qq, and q′q' is the pixel where the target sees the same scene point XX. By (B1), Ij[q′]−bj=eajL(X)I_j[q'] - b_j = e^{a_j} L(X) and Ii[q]−bi=eaiL(X)I_i[q] - b_i = e^{a_i} L(X), so rq=eajL(X)−eaj−aieaiL(X)=0r_q = e^{a_j} L(X) - e^{a_j - a_i} e^{a_i} L(X) = 0.

Lemma 2 (global minimizer without a prior). Every term wqρk(rq)w_q \rho_k(r_q) is ≥0\ge 0, and by Lemma 1 every term is 0 at the true state. So the true state attains the smallest possible value 0 of the tracking energy and of the window energy. This is a statement about the energy, not about uniqueness: a state with the same images (for example the same scene under another similarity, if the gauge were not fixed) has the same value.

Lemma 3 (exact Schur step). Let HH be symmetric with an invertible block HββH_{\beta\beta}, and split Hx=bH x = b into (xα,xβ)(x_\alpha, x_\beta). If xαx_\alpha solves (Hαα−HαβHββ−1Hβα)xα=bα−HαβHββ−1bβ(H_{\alpha\alpha} - H_{\alpha\beta} H_{\beta\beta}^{-1} H_{\beta\alpha}) x_\alpha = b_\alpha - H_{\alpha\beta} H_{\beta\beta}^{-1} b_\beta and xβ=Hββ−1(bβ−Hβαxα)x_\beta = H_{\beta\beta}^{-1}(b_\beta - H_{\beta\alpha} x_\alpha), then Hx=bH x = b. The second block row holds by the definition of xβx_\beta. The first block row is Hααxα+HαβHββ−1(bβ−Hβαxα)=bαH_{\alpha\alpha} x_\alpha + H_{\alpha\beta} H_{\beta\beta}^{-1}(b_\beta - H_{\beta\alpha} x_\alpha) = b_\alpha, which is the reduced equation after the terms are moved. So lines L9 and the back-substitution give the exact Gauss-Newton step. In the window every residual depends on one inverse depth, so HββH_{\beta\beta} is diagonal and its inverse is the list of reciprocals, which is what the code uses.

Lemma 4 (marginal of a quadratic). Let Q(xα,xβ)=−bTx+12xTHxQ(x_\alpha, x_\beta) = -b^{\mathsf T} x + \frac{1}{2} x^{\mathsf T} H x with HββH_{\beta\beta} positive definite. For fixed xαx_\alpha, QQ is a strictly convex quadratic in xβx_\beta, minimized at xβ=Hββ−1(bβ−Hβαxα)x_\beta = H_{\beta\beta}^{-1}(b_\beta - H_{\beta\alpha} x_\alpha). Putting this in gives min⁡xβQ=−b^Txα+12xαTH^xα+C\min_{x_\beta} Q = -\hat b^{\mathsf T} x_\alpha + \frac{1}{2} x_\alpha^{\mathsf T} \hat H x_\alpha + C with H^=Hαα−HαβHββ−1Hβα\hat H = H_{\alpha\alpha} - H_{\alpha\beta} H_{\beta\beta}^{-1} H_{\beta\alpha}, b^=bα−HαβHββ−1bβ\hat b = b_\alpha - H_{\alpha\beta} H_{\beta\beta}^{-1} b_\beta and a constant C=−12bβTHββ−1bβC = -\frac{1}{2} b_\beta^{\mathsf T} H_{\beta\beta}^{-1} b_\beta. So the prior of line L11 is, up to a constant, the Gauss-Newton model of the energy of the removed residuals minimized over the removed variables. If HH is positive semidefinite, so is H^\hat H, because xαTH^xα=min⁡xβxTHx≥0x_\alpha^{\mathsf T} \hat H x_\alpha = \min_{x_\beta} x^{\mathsf T} H x \ge 0 (the case b=0b = 0 of the same formula, times 2).

Lemma 5 (the truth stays a minimizer after marginalization). We use induction over the marginalizations. When line L11 builds its system, the state is the true state by (B4). The residual part of the right-hand side is −JTWr=0-J^{\mathsf T} W r = 0, because r=0r = 0 by Lemma 1. An older prior adds b^old−H^oldx\hat b_{old} - \hat H_{old} x, where x=0x = 0 because the older prior was also made at the true state, and b^old=0\hat b_{old} = 0 by the induction hypothesis. So b=0b = 0, and the new prior has b^=bα−HαβHββ−1bβ=0\hat b = b_\alpha - H_{\alpha\beta} H_{\beta\beta}^{-1} b_\beta = 0. With b^=0\hat b = 0 and H^⪰0\hat H \succeq 0 (Lemma 4, since a Gauss-Newton matrix JTWJJ^{\mathsf T} W J with W≥0W \ge 0 and an older prior matrix are both positive semidefinite), the prior is ≥0\ge 0 and equals 0 at x=0x = 0, the true state. The remaining residuals are zero at the true state by Lemma 1. So the true state is a global minimizer, with value 0, of the window energy plus the prior, after any number of marginalizations.

Lemma 6 (fixed point). At the true state, the right-hand side of every Gauss-Newton system is b=−JTWr+(b^−H^x)=0b = -J^{\mathsf T} W r + (\hat b - \hat H x) = 0, because r=0r = 0 by Lemma 1, b^=0\hat b = 0 by Lemma 5 and x=0x = 0. The step is therefore 0 (or the solve fails and the loop stops). A zero step gives the same energy, which is not smaller, so lines L3 and L9 stop and return the true state unchanged.

Lemma 7 (monotone energy). Lines L3 and L9 compute the energy after each candidate step and keep the step only if the energy is strictly smaller; otherwise they restore the previous state and stop. So the sequence of energies that the code keeps is strictly decreasing, and the returned energy is at most the starting energy. This holds for any data, not only under (B1) to (B4).

Conclusion. On exact data, the true state is a global minimizer of every energy the algorithm uses (Lemmas 2 and 5), it is a fixed point of every step (Lemma 6), each Gauss-Newton step is solved exactly by the Schur complement (Lemma 3), and the prior is the exact marginal of the Gauss-Newton model (Lemma 4). On any data, the kept energies never go up (Lemma 7). ■\blacksquare

What is not proved. Convergence to the true state from a start far from it. Gauss-Newton on the photometric error is a local method: the image is only close to linear within a pixel or two, and the energy has other minima. The pyramid, the constant motion guess and the frame rate are there to keep the start in the region where it works; none of them gives a guarantee. On real images (B1) and (B2) hold only approximately, the brightness model is an approximation, and the prior is a linearization made at a state that is not the truth, so the estimates are biased and drift. The keyframe and marginalization rules are heuristics and are not part of this proof.

Complexity

All counts are in the real RAM. The pattern has 8 pixels, a constant.

  • Tracking. One Gauss-Newton iteration at one level visits the 8m8m residuals of the newest keyframe, each with an 8×88 \times 8 outer product, and solves an 8×88 \times 8 system, so O(m)O(m). With LL levels and at most kk iterations, O(Lkm)O(Lkm) per frame.
  • Candidates. The depth search costs O(s)O(s) per candidate, so O(cs)O(cs) per frame.
  • Window step. A point has residuals into at most W−1W - 1 keyframes, and each residual touches 17 unknowns, so building the system costs O(nW)O(nW). The Schur complement adds, for each point, an outer product of its column over at most 8W8W keyframe entries, so O(nW2)O(nW^2). The reduced system is dense of size 8W8W and costs O(W3)O(W^3) to solve. One step costs O(nW2+W3)O(nW^2 + W^3); kk steps cost O(k(nW2+W3))O(k(nW^2 + W^3)). This is a cost per iteration, not a convergence bound.
  • Marginalization. The Schur complement over one keyframe and its points has the same form, O(nW2+W3)O(nW^2 + W^3) in a structured implementation. The code here stores the Gauss-Newton matrix densely and uses a dense solve for this step, which costs O((n+W)3)O((n + W)^3); that is a simplification for clarity.
  • Space. The structured form stores O(nW)O(nW) couplings between points and keyframes and the O(W2)O(W^2) reduced matrix and prior. The dense code uses O((n+W)2)O((n + W)^2).

A frame that is not a keyframe costs only O(Lkm+cs)O(Lkm + cs), and the window step runs once per keyframe.

Properties

  • Deterministic. There are no random samples. The result depends only on the input and the parameters.
  • Not exact. Gauss-Newton converges only locally, and the result depends on the start, on the pyramid and on the image content.
  • Online. Each frame costs a bounded amount of work for a fixed window and a fixed number of points.
  • Scale. With one camera the scale is fixed by the first depths and carried by the window and the prior. It drifts over long paths; see scale drift.
  • Photometric model. The affine brightness terms absorb changes of exposure and gain. Without them, a change of exposure moves the energy minimum away from the true pose.
  • Sparse and direct. It uses the intensities directly, with no descriptors, but only at sparse points, so the Gauss-Newton matrix has the same structure as in bundle adjustment.

Variants and improvements

  • Photometric calibration. The paper corrects the images with a known response function and vignetting map and uses the exposure times. Without them, more of the change has to go into (a,b)(a, b).
  • Stereo and inertial versions. Later work by the same group adds a stereo camera (which gives metric scale) or an inertial sensor. These are separate systems.
  • Loop closure. DSO is odometry and does not close loops. Systems built on it add a place recognition step and a pose graph; see loop closure detection.
  • Dense and semi-dense direct methods. DTAM (Newcombe, Lovegrove and Davison, ICCV 2011) estimates a dense depth map; LSD-SLAM (Engel, Schöps and Cremers, ECCV 2014) uses all pixels with enough gradient and a pose graph. DSO is sparse, which makes the joint optimization of depths and poses affordable.
  • Semi-direct methods. Semi-direct visual odometry uses direct alignment only for tracking and refines the structure with reprojection errors.

When to use it

Use DSO when the scene has little corner texture but many edges and smooth gradients, the camera has a global shutter, and you can calibrate the photometric response. Prefer a feature-based method such as Nister visual odometry or ORB-SLAM when the motion between frames is large, the exposure changes in ways the affine model does not fit, the camera has a rolling shutter, or you need relocalization and loop closure.

Pitfalls

  • Large motion. If the start of the tracking is more than a few pixels from the truth at the coarsest level, Gauss-Newton can converge to a wrong minimum. A higher frame rate or a better motion guess helps.
  • Gauge. Without a fixed keyframe and a fixed scale, the Gauss-Newton matrix is singular. The code fixes the first keyframe and one depth; the prior keeps the gauge after that keyframe leaves.
  • Prior consistency. If the Jacobians of the variables in the prior are later evaluated at a different point, the prior can gain information it does not have and the estimate becomes overconfident. The paper uses First Estimate Jacobians for this reason; the code does not.
  • Brightness gauge. (a,b)(a, b) of one frame must be fixed, and a strong gain change with little contrast makes aa and bb nearly interchangeable.
  • Pattern depth. All 8 pixels share one inverse depth. On a slanted surface close to the camera this is only an approximation.
  • Rolling shutter and motion blur. The model assumes one pose per image. Both break that assumption.

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()
direct_sparse_odometry.py 655 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-sparse-odometry/. The authors are listed in prov/YH2YPH.jsonl.
"""Direct sparse odometry (Engel, Koltun and Cremers, TPAMI 2018), small form.

The model follows the paper:
- A point is a pixel p of its host keyframe i with one inverse depth d. Its
  residual pattern has 8 pixels q = p + o, all with the same inverse depth.
- The residual of a pattern pixel in a target frame j is
      r = (I_j[q'] - b_j) - exp(a_j - a_i) (I_i[q] - b_i),
  q' = Pi(R Pi^-1(q, d) + t), with (R, t) = T_j T_i^-1. Each residual has the
  weight w = c^2 / (c^2 + |grad I_i(q)|^2) and the Huber norm.
- A new frame is tracked against the newest keyframe by Gauss-Newton on its
  pose and its affine brightness (a, b), coarse to fine, from a constant
  motion guess.
- A new keyframe is made when w_f f + w_ft f_t + w_a a > T_kf.
- Points are chosen with a gradient threshold per block (the median of the
  block plus g_th). Their inverse depth is found by a search along the
  epipolar line and a few Gauss-Newton steps on the inverse depth.
- The window of keyframes is optimized by Gauss-Newton on all poses, affine
  terms and inverse depths, with the Schur complement on the inverse depths.
  A keyframe that leaves the window is marginalized by the Schur complement
  into a quadratic prior on the remaining keyframes.

What is left out: photometric calibration (the images are taken as already
corrected), the first estimate Jacobians, the recovery after a tracking
failure, the outlier rules for points, and the initialization of the first
depths (the caller gives them). An image is any object with a method
sample(u, v) that returns (value, d/du, d/dv), or None outside the image.
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 dot, eye, matvec, mul, norm, skew, solve, transpose

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

# The 8-pixel residual pattern (offsets du, dv) used by this code.
PATTERN = [(0, -2), (-1, -1), (1, -1), (-2, 0), (0, 0), (2, 0), (-1, 1), (0, 2)]


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

class GridImage:
    """A gray image img[v][u]. Values and central-difference gradients are
    read with bilinear interpolation. Samples closer than one pixel to the
    border return None."""

    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":
        """The next pyramid level: the mean of each 2 x 2 block."""
        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. Pixel centers are integers, so a
    2 x 2 mean maps u to (u - 0.5) / 2."""
    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 so3_log(R: Matrix) -> Vector:
    tr = R[0][0] + R[1][1] + R[2][2]
    c = max(-1.0, min(1.0, (tr - 1.0) / 2.0))
    th = math.acos(c)
    v = [R[2][1] - R[1][2], R[0][2] - R[2][0], R[1][0] - R[0][1]]
    if th < 1e-7:
        return [0.5 * x for x in v]
    if math.pi - th < 1e-6:
        raise ValueError("so3_log: angle too close to pi")
    return [th / (2.0 * math.sin(th)) * x for x in v]


def apply_update(pose: Pose, delta: Sequence[float]) -> Pose:
    """(exp(w) R, exp(w) t + v) for delta = (w, v): the left update."""
    E = so3_exp(delta[:3])
    R, t = pose
    return mul(E, R), [a + b for a, b in zip(matvec(E, t), delta[3:6])]


def pose_delta(pose: Pose, ref: Pose) -> Vector:
    """The delta with apply_update(ref, delta) = pose."""
    Rd = mul(pose[0], transpose(ref[0]))
    w = so3_log(Rd)
    rt = matvec(Rd, ref[1])
    return w + [a - b for a, b in zip(pose[1], rt)]


def relative(tj: Pose, ti: Pose) -> Pose:
    """T_j T_i^-1, which maps host camera coordinates to target ones."""
    Rji = mul(tj[0], transpose(ti[0]))
    return Rji, [a - b for a, b in zip(tj[1], matvec(Rji, ti[1]))]


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


# ----------------------------------------------------- residual and weights

def huber_weight(r: float, k: float) -> float:
    a = abs(r)
    return 1.0 if a <= k else k / a


def huber(r: float, k: float) -> float:
    a = abs(r)
    return 0.5 * r * r if a <= k else k * (a - 0.5 * k)


def gradient_weight(g2: float, c: float) -> float:
    """c^2 / (c^2 + |grad I_i(q)|^2), from the squared gradient norm g2."""
    return c * c / (c * c + g2)


def warp(K, q: Sequence[float], d: float, rel: Pose):
    """Pi(R Pi^-1(q, d) + t): the target pixel and the target camera point."""
    fx, fy, cx, cy = K
    X = ((q[0] - cx) / fx / d, (q[1] - cy) / fy / d, 1.0 / d)
    R, t = rel
    Xt = [R[r][0] * X[0] + R[r][1] * X[1] + R[r][2] * X[2] + t[r] for r in range(3)]
    if Xt[2] <= 1e-9:
        return None, Xt
    return (fx * Xt[0] / Xt[2] + cx, fy * Xt[1] / Xt[2] + cy), Xt


def residual(host_img, tgt_img, K, q, d, host: Tuple[Pose, float, float], tgt: Tuple[Pose, float, float],
             with_jacobian: bool = False, rel: Optional[Pose] = None):
    """The photometric residual of one pattern pixel q of a point with inverse
    depth d, and its gradient weight. With with_jacobian, also the
    derivatives with respect to the target (6 pose, a_j, b_j), the host
    (6 pose, a_i, b_i) and d. rel may give T_j T_i^-1 when the caller has it.
    Returns None if a sample is outside an image."""
    (ti, ai, bi), (tj, aj, bj) = host, tgt
    hs = host_img.sample(q[0], q[1])
    if hs is None:
        return None
    if rel is None:
        rel = relative(tj, ti)
    qp, Xt = warp(K, q, d, rel)
    if qp is None:
        return None
    ts = tgt_img.sample(qp[0], qp[1])
    if ts is None:
        return None
    s = math.exp(aj - ai)
    r = (ts[0] - bj) - s * (hs[0] - bi)
    wp = hs[1] * hs[1] + hs[2] * hs[2]
    if not with_jacobian:
        return r, wp, qp
    fx, fy, cx, cy = K
    z = Xt[2]
    gu = [fx / z, 0.0, -fx * Xt[0] / (z * z)]
    gv = [0.0, fy / z, -fy * Xt[1] / (z * z)]
    dX = [ts[1] * gu[k] + ts[2] * gv[k] for k in range(3)]  # dr / dXt
    # target pose: dXt/dw = -[Xt]x, dXt/dv = I
    sx = skew(Xt)
    jt = [-sum(dX[r_] * sx[r_][c] for r_ in range(3)) for c in range(3)] + dX
    jt += [-s * (hs[0] - bi), -1.0]
    # host pose: dXt/dw_i = R_ji [Xh]x, dXt/dv_i = -R_ji
    Xh = [(q[0] - cx) / fx / d, (q[1] - cy) / fy / d, 1.0 / d]
    dXR = [sum(dX[r_] * rel[0][r_][c] for r_ in range(3)) for c in range(3)]  # dX^T R
    sh = skew(Xh)
    jh = [sum(dXR[r_] * sh[r_][c] for r_ in range(3)) for c in range(3)] + [-x for x in dXR]
    jh += [s * (hs[0] - bi), s]
    # inverse depth: dXh/dd = -Xh / d
    jd = -dot(dXR, Xh) / d
    return r, wp, qp, jt, jh, jd


# --------------------------------------------------------- point selection

def select_points(img: GridImage, block: int, g_th: float, passes: int = 3, factor: float = 0.75,
                  margin: int = 3) -> List[Tuple[int, int]]:
    """Region-adaptive gradient threshold. In each block of size block, the
    threshold is the median gradient norm of the block plus g_th, and the
    pixel with the largest gradient above it is chosen. Later passes use
    blocks of 2 and 4 times the size and a threshold multiplied by factor,
    and skip blocks that already hold a point."""
    g = [[math.hypot(img.gx[v][u], img.gy[v][u]) for u in range(img.w)] for v in range(img.h)]
    chosen: List[Tuple[int, int]] = []
    taken = set()
    size, scale_th = block, 1.0
    for _ in range(passes):
        for v0 in range(margin, img.h - margin, size):
            for u0 in range(margin, img.w - margin, size):
                cells = [(g[v][u], u, v) for v in range(v0, min(v0 + size, img.h - margin))
                         for u in range(u0, min(u0 + size, img.w - margin))]
                if not cells or any((u, v) in taken for _, u, v in cells):
                    continue
                vals = sorted(c[0] for c in cells)
                th = scale_th * (vals[len(vals) // 2] + g_th)
                best = max(cells)
                if best[0] > th:
                    chosen.append((best[1], best[2]))
                    taken.add((best[1], best[2]))
        size, scale_th = 2 * size, scale_th * factor
    return chosen


# -------------------------------------------------------------- tracking

def track_frame(points, host_pyr, tgt_pyr, K, host: Tuple[Pose, float, float], init: Tuple[Pose, float, float],
                huber_k: float = 9.0, grad_c: float = 50.0, iters: int = 20):
    """Two-frame direct alignment of a new frame against one keyframe:
    Gauss-Newton on the target pose and (a_j, b_j), coarse to fine, with the
    host and the inverse depths held fixed. points is a list of (u, v, d) in
    host pixels of level 0. Returns ((pose, a, b), RMSE)."""
    pose, aj, bj = init
    rmse = math.inf
    for lev in range(len(tgt_pyr) - 1, -1, -1):  # @line L3
        Kl = level_K(K, lev)
        f = 0.5 ** lev
        qs = []
        for (u, v, d) in points:
            pl = ((u + 0.5) * f - 0.5, (v + 0.5) * f - 0.5)
            for o in PATTERN:
                qs.append(((pl[0] + o[0], pl[1] + o[1]), d))

        def energy(state):
            e, n, sq = 0.0, 0, 0.0
            rel = relative(state[0], host[0])
            for q, d in qs:
                res = residual(host_pyr[lev], tgt_pyr[lev], Kl, q, d, host, state, rel=rel)
                if res is None:
                    continue
                e += gradient_weight(res[1], grad_c) * huber(res[0], huber_k)
                sq += res[0] ** 2
                n += 1
            return e, (math.sqrt(sq / n) if n else math.inf)

        state = (pose, aj, bj)
        e0, rmse = energy(state)
        for _ in range(iters):
            H = [[0.0] * 8 for _ in range(8)]
            b = [0.0] * 8
            rel = relative(state[0], host[0])
            for q, d in qs:
                res = residual(host_pyr[lev], tgt_pyr[lev], Kl, q, d, host, state, True, rel)
                if res is None:
                    continue
                r, wp, _, jt, _, _ = res
                w = gradient_weight(wp, grad_c) * huber_weight(r, huber_k)
                for x in range(8):
                    b[x] -= w * jt[x] * r
                    for y in range(8):
                        H[x][y] += w * jt[x] * jt[y]
            try:
                step = solve(H, b)
            except ValueError:
                break
            cand = (apply_update(state[0], step[:6]), state[1] + step[6], state[2] + step[7])
            e1, r1 = energy(cand)
            if not e1 < e0:
                break
            state, e0, rmse = cand, e1, r1
            if norm(step) < 1e-12:
                break
        pose, aj, bj = state
    return (pose, aj, bj), rmse


def keyframe_score(points, K, host: Tuple[Pose, float, float], tgt: Tuple[Pose, float, float],
                   wf: float, wft: float, wa: float) -> float:
    """w_f f + w_ft f_t + w_a a: f is the root mean square pixel shift of the
    points, f_t the same shift with the rotation set to I, and
    a = |a_j - a_i| (the log of exp(a_j - a_i) t_j / t_i with t = 1)."""
    rel = relative(tgt[0], host[0])
    rel_t = (eye(3), rel[1])
    sf, sft, n = 0.0, 0.0, 0
    for (u, v, d) in points:
        p1, _ = warp(K, (u, v), d, rel)
        p2, _ = warp(K, (u, v), d, rel_t)
        if p1 is None or p2 is None:
            continue
        sf += (p1[0] - u) ** 2 + (p1[1] - v) ** 2
        sft += (p2[0] - u) ** 2 + (p2[1] - v) ** 2
        n += 1
    if n == 0:
        return math.inf
    return wf * math.sqrt(sf / n) + wft * math.sqrt(sft / n) + wa * abs(tgt[1] - host[1])


# ----------------------------------------------- inverse depth of new points

def search_depth(host_img, tgt_img, K, p, host, tgt, d_min: float, d_max: float, steps: int = 40,
                 grad_c: float = 50.0, gn_iters: int = 10) -> Optional[Tuple[float, float]]:
    """The inverse depth of the pixel p of the host: the best of steps
    values in [d_min, d_max] (a discrete search along the epipolar line),
    then Gauss-Newton on d alone. Returns (d, RMSE) or None."""
    rel = relative(tgt[0], host[0])

    def cost(d):
        s, n = 0.0, 0
        for o in PATTERN:
            res = residual(host_img, tgt_img, K, (p[0] + o[0], p[1] + o[1]), d, host, tgt, rel=rel)
            if res is None:
                return math.inf
            s += res[0] ** 2
            n += 1
        return s / n
    best_d, best_c = None, math.inf
    for k in range(steps):
        d = d_min + (d_max - d_min) * k / (steps - 1)
        c = cost(d)
        if c < best_c:
            best_d, best_c = d, c
    if best_d is None:
        return None
    d = best_d
    for _ in range(gn_iters):
        h, g = 0.0, 0.0
        for o in PATTERN:
            res = residual(host_img, tgt_img, K, (p[0] + o[0], p[1] + o[1]), d, host, tgt, True, rel)
            if res is None:
                return None
            h += res[5] ** 2
            g -= res[5] * res[0]
        if h <= 0:
            break
        nd = d + g / h
        nc = cost(nd) if nd > 0 else math.inf
        if not nc < best_c:
            break
        d, best_c = nd, nc
    return d, math.sqrt(best_c)


# ------------------------------------------------------ window optimization

class Keyframe:
    def __init__(self, fid: int, img, pose: Pose, a: float = 0.0, b: float = 0.0, fixed: bool = False):
        self.fid, self.img, self.pose, self.a, self.b, self.fixed = fid, img, pose, a, b, fixed


class Point:
    def __init__(self, host: int, u: float, v: float, d: float, fixed: bool = False):
        self.host, self.u, self.v, self.d, self.fixed = host, u, v, d, fixed


class Prior:
    """A quadratic prior -b^T x + x^T H x / 2 on the deltas x of some
    keyframes from their linearization point (pose_delta, a - a0, b - b0)."""

    def __init__(self, fids: List[int], H: Matrix, b: Vector, ref: Dict[int, Tuple[Pose, float, float]]):
        self.fids, self.H, self.b, self.ref = fids, H, b, ref

    def delta(self, kfs: Dict[int, Keyframe]) -> Vector:
        x = []
        for f in self.fids:
            pose, a0, b0 = self.ref[f]
            kf = kfs[f]
            x += pose_delta(kf.pose, pose) + [kf.a - a0, kf.b - b0]
        return x

    def energy(self, kfs: Dict[int, Keyframe]) -> float:
        x = self.delta(kfs)
        return -dot(self.b, x) + 0.5 * dot(x, matvec(self.H, x))


def schur_marginalize(H: Matrix, b: Vector, keep: List[int], drop: List[int]) -> Tuple[Matrix, Vector]:
    """H_kk - H_kd H_dd^-1 H_dk and b_k - H_kd H_dd^-1 b_d."""
    if not drop:
        return [[H[i][j] for j in keep] for i in keep], [b[i] for i in keep]
    Hdd = [[H[i][j] for j in drop] for i in drop]
    Hdk = [[H[i][j] for j in keep] for i in drop]
    X = solve(Hdd, [row + [b[i]] for row, i in zip(Hdk, drop)])  # H_dd^-1 [H_dk | b_d]
    Hn = [[H[i][j] - sum(H[i][drop[m]] * X[m][c] for m in range(len(drop))) for c, j in enumerate(keep)]
          for i in keep]
    bn = [b[i] - sum(H[i][drop[m]] * X[m][len(keep)] for m in range(len(drop))) for i in keep]
    return Hn, bn


def _system(kfs: Dict[int, Keyframe], points: List[Point], K, prior: Optional[Prior], huber_k: float,
            grad_c: float, skip_target: Optional[int] = None):
    """The Gauss-Newton system H x = b over the free keyframe blocks (8 each)
    and the free inverse depths (1 each), and the energy."""
    fidx: Dict[int, int] = {}
    for f in sorted(kfs):
        if not kfs[f].fixed:
            fidx[f] = 8 * len(fidx)
    nf = 8 * len(fidx)
    pidx = {}
    for k, p in enumerate(points):
        if not p.fixed:
            pidx[k] = nf + len(pidx)
    n = nf + len(pidx)
    H = [[0.0] * n for _ in range(n)]
    b = [0.0] * n
    energy = 0.0
    rels = {(i, j): relative(kfs[j].pose, kfs[i].pose) for i in kfs for j in kfs if i != j}
    for k, p in enumerate(points):
        h = kfs[p.host]
        for f, t in kfs.items():
            if f == p.host or f == skip_target:
                continue
            for o in PATTERN:
                res = residual(h.img, t.img, K, (p.u + o[0], p.v + o[1]), p.d, (h.pose, h.a, h.b),
                               (t.pose, t.a, t.b), True, rels[(p.host, f)])
                if res is None:
                    continue
                r, wp, _, jt, jh, jd = res
                wg = gradient_weight(wp, grad_c)
                energy += wg * huber(r, huber_k)
                w = wg * huber_weight(r, huber_k)
                cols = []
                if f in fidx:
                    cols += [(fidx[f] + x, jt[x]) for x in range(8)]
                if p.host in fidx:
                    cols += [(fidx[p.host] + x, jh[x]) for x in range(8)]
                if k in pidx:
                    cols.append((pidx[k], jd))
                for i, ji in cols:
                    b[i] -= w * ji * r
                    for j, jj in cols:
                        H[i][j] += w * ji * jj
    if prior is not None:
        x = prior.delta(kfs)
        energy += -dot(prior.b, x) + 0.5 * dot(x, matvec(prior.H, x))
        hx = matvec(prior.H, x)
        for a, fa in enumerate(prior.fids):
            if fa not in fidx:
                continue
            for i in range(8):
                b[fidx[fa] + i] += prior.b[8 * a + i] - hx[8 * a + i]
                for c, fc in enumerate(prior.fids):
                    if fc in fidx:
                        for j in range(8):
                            H[fidx[fa] + i][fidx[fc] + j] += prior.H[8 * a + i][8 * c + j]
    return H, b, energy, fidx, pidx


def window_energy(kfs, points, K, prior, huber_k=9.0, grad_c=50.0) -> float:
    e = 0.0
    rels = {(i, j): relative(kfs[j].pose, kfs[i].pose) for i in kfs for j in kfs if i != j}
    for p in points:
        h = kfs[p.host]
        for f, t in kfs.items():
            if f == p.host:
                continue
            for o in PATTERN:
                res = residual(h.img, t.img, K, (p.u + o[0], p.v + o[1]), p.d, (h.pose, h.a, h.b), (t.pose, t.a, t.b),
                               rel=rels[(p.host, f)])
                if res is not None:
                    e += gradient_weight(res[1], grad_c) * huber(res[0], huber_k)
    if prior is not None:
        e += prior.energy(kfs)
    return e


def optimize_window(kfs: Dict[int, Keyframe], points: List[Point], K, prior: Optional[Prior] = None,
                    iters: int = 6, huber_k: float = 9.0, grad_c: float = 50.0) -> List[float]:
    """Gauss-Newton on the window; the inverse depths are removed by the
    Schur complement (their block of H is diagonal). A step is kept only if
    the energy goes down. Returns the energy after each kept step."""
    history = [window_energy(kfs, points, K, prior, huber_k, grad_c)]
    for _ in range(iters):
        H, b, _, fidx, pidx = _system(kfs, points, K, prior, huber_k, grad_c)  # @line L8
        nf = 8 * len(fidx)
        dep = sorted(pidx.values())
        for i in dep:
            if H[i][i] <= 0.0:
                H[i][i] = 1e-12
        # Each residual has one inverse depth, so the depth block is diagonal and
        # the Schur complement costs O(n (8 N_f)^2) for n points.
        Hr = [H[i][:nf] for i in range(nf)]  # @line L9
        br = b[:nf]
        for i in dep:
            col = [H[x][i] for x in range(nf)]
            if not any(col):
                continue
            for x in range(nf):
                if col[x] == 0.0:
                    continue
                f = col[x] / H[i][i]
                br[x] -= f * b[i]
                row = Hr[x]
                for y in range(nf):
                    row[y] -= f * col[y]
        try:
            dx = solve(Hr, br) if nf else []  # @line L9
        except ValueError:
            break
        dd = {i: (b[i] - sum(H[i][j] * dx[j] for j in range(nf))) / H[i][i] for i in dep}  # @line L9
        saved = ({f: (kf.pose, kf.a, kf.b) for f, kf in kfs.items()}, [p.d for p in points])
        for f, s in fidx.items():
            kf = kfs[f]
            kf.pose = apply_update(kf.pose, dx[s:s + 6])
            kf.a, kf.b = kf.a + dx[s + 6], kf.b + dx[s + 7]
        for k, i in pidx.items():
            points[k].d = max(1e-6, points[k].d + dd[i])
        e = window_energy(kfs, points, K, prior, huber_k, grad_c)
        if not e < history[-1]:
            for f, (pose, a, bb) in saved[0].items():
                kfs[f].pose, kfs[f].a, kfs[f].b = pose, a, bb
            for p, d in zip(points, saved[1]):
                p.d = d
            break
        history.append(e)
    return history


def marginalize_keyframe(kfs: Dict[int, Keyframe], points: List[Point], K, prior: Optional[Prior], m: int,
                         huber_k: float = 9.0, grad_c: float = 50.0) -> Tuple[List[Point], Optional[Prior]]:
    """Remove keyframe m. Residuals of points of other hosts into m are
    dropped; the points hosted in m and the block of m are marginalized by
    the Schur complement into a new prior on the other free keyframes."""
    H, b, _, fidx, pidx = _system(kfs, points, K, prior, huber_k, grad_c, skip_target=m)  # @line L11
    drop = [pidx[k] for k, p in enumerate(points) if p.host == m and k in pidx]
    if m in fidx:
        drop += list(range(fidx[m], fidx[m] + 8))
    keep_f = [f for f in sorted(fidx) if f != m]
    keep = [fidx[f] + x for f in keep_f for x in range(8)]
    for i in drop:
        if H[i][i] <= 0.0:
            H[i][i] = 1e-12
    Hn, bn = schur_marginalize(H, b, keep, drop)  # @line L11
    ref = {f: (kfs[f].pose, kfs[f].a, kfs[f].b) for f in keep_f}
    new_prior = Prior(keep_f, Hn, bn, ref) if keep_f else None
    del kfs[m]
    return [p for p in points if p.host != m], new_prior


def choose_marginalized(kfs: Dict[int, Keyframe], points: List[Point], K, n_max: int, eps: float = 1e-3) -> Optional[int]:
    """The rule of the paper: the two newest keyframes stay; a keyframe with
    less than 5 percent of its points visible in the newest one goes; if
    still more than n_max remain, the one that maximizes
    sqrt(d(i, 1)) sum_j (d(i, j) + eps)^-1 goes, d being the distance of the
    camera centers and keyframe 1 the newest."""
    order = sorted(kfs)
    if len(order) <= 2:
        return None
    newest = kfs[order[-1]]
    for f in order[:-2]:
        own = [p for p in points if p.host == f]
        if own:
            seen = 0
            for p in own:
                q, _ = warp(K, (p.u, p.v), p.d, relative(newest.pose, kfs[f].pose))
                if q is not None and newest.img.sample(q[0], q[1]) is not None:
                    seen += 1
            if seen < 0.05 * len(own):
                return f
    if len(order) <= n_max:
        return None
    c1 = center(newest.pose)
    best, best_s = None, -1.0
    for f in order[:-2]:
        ci = center(kfs[f].pose)
        s = math.sqrt(norm([a - b for a, b in zip(ci, c1)])) * sum(
            1.0 / (norm([a - b for a, b in zip(ci, center(kfs[j].pose))]) + eps) for j in order[:-1] if j != f)
        if s > best_s:
            best, best_s = f, s
    return best


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

def run_dso(frames: Sequence[GridImage], K, first_depth, levels: int = 2, n_max: int = 3, block: int = 4,
            g_th: float = 3.0, wf: float = 1.0, wft: float = 1.0, wa: float = 1.0, t_kf: float = 2.0,
            d_range: Tuple[float, float] = (0.05, 1.0), win_iters: int = 6) -> Dict:
    """Run the pipeline on a list of images. first_depth(u, v) gives the
    inverse depth of a pixel of frame 0, which fixes the scale. Returns the
    poses and affine terms of all frames and the keyframe ids."""
    kfs: Dict[int, Keyframe] = {0: Keyframe(0, frames[0], (eye(3), [0.0, 0.0, 0.0]), fixed=True)}  # @line L1
    pts0 = select_points(frames[0], block, g_th)
    points = [Point(0, u, v, first_depth(u, v), fixed=(k == 0)) for k, (u, v) in enumerate(pts0)]  # @line L1
    prior: Optional[Prior] = None
    pyrs = {0: pyramid(frames[0], levels)}
    states = [((eye(3), [0.0, 0.0, 0.0]), 0.0, 0.0)]
    immature = [(u, v) for (u, v) in select_points(frames[0], block, g_th) if (u, v) not in set(pts0)]
    depth_guess: Dict[Tuple[int, int], float] = {}
    for j in range(1, len(frames)):  # @line L2
        last = max(kfs)
        kf = kfs[last]
        pyr = pyramid(frames[j], levels)
        prev = states[-1]
        if len(states) >= 2:
            motion = relative(states[-1][0], states[-2][0])
            guess_pose = (mul(motion[0], prev[0][0]), [a + b for a, b in zip(matvec(motion[0], prev[0][1]), motion[1])])
        else:
            guess_pose = prev[0]
        own = [(p.u, p.v, p.d) for p in points if p.host == last]
        state, _ = track_frame(own, pyrs[last], pyr, K, (kf.pose, kf.a, kf.b), (guess_pose, prev[1], prev[2]))  # @line L3
        states.append(state)
        for (u, v) in immature:  # @line L4
            got = search_depth(kf.img, frames[j], K, (u, v), (kf.pose, kf.a, kf.b), state, d_range[0], d_range[1])
            if got is not None:
                depth_guess[(u, v)] = got[0]  # @line L4
        if keyframe_score(own, K, (kf.pose, kf.a, kf.b), state, wf, wft, wa) <= t_kf:  # @line L5
            continue
        for (u, v), d in depth_guess.items():  # @line L6
            points.append(Point(last, u, v, d))  # @line L6
        kfs[j] = Keyframe(j, frames[j], state[0], state[1], state[2])  # @line L7
        pyrs[j] = pyr
        optimize_window(kfs, points, K, prior, iters=win_iters)  # @line L8
        m = choose_marginalized(kfs, points, K, n_max)  # @line L10
        if m is not None:
            points, prior = marginalize_keyframe(kfs, points, K, prior, m)  # @line L11
        for f, k in kfs.items():
            states[f] = (k.pose, k.a, k.b)
        used = {(p.u, p.v) for p in points if p.host == j}
        immature = [q for q in select_points(frames[j], block, g_th) if q not in used]  # @line L12
        depth_guess = {}
    return {"states": states, "keyframes": sorted(kfs), "points": points, "prior": prior}  # @line L13
test_direct_sparse_odometry.py 317 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-sparse-odometry/. The authors are listed in prov/YH2YPH.jsonl.
"""Tests for direct_sparse_odometry.

Most tests use an analytic image: the exact image of a textured plane, so a
correct estimate makes every residual zero and the estimates can be checked
to high accuracy. 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 direct_sparse_odometry as dso  # noqa: E402
from cvla import matvec, mul, norm, solve, transpose  # noqa: E402

K = (40.0, 40.0, 23.5, 17.5)
W, H = 48, 36


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 hit(self, pose, Kl, u, v):
        R, t = pose
        fx, fy, cx, cy = Kl
        c = dso.center(pose)
        ray = matvec(transpose(R), [(u - cx) / fx, (v - cy) / fy, 1.0])
        s = (self.z0 + self.sx * c[0] - c[2]) / (ray[2] - self.sx * ray[0])
        return [c[i] + s * ray[i] for i in range(3)], s

    def inv_depth(self, pose, u, v):
        return 1.0 / self.hit(pose, K, u, v)[1]


class AnalyticImage:
    """The exact image exp(a) L + b of a plane seen by a camera, with
    central-difference gradients. It has the same border rule as GridImage."""

    def __init__(self, plane, pose, a, b, Kl=K, w=W, h=H):
        self.plane, self.pose, self.a, self.b, self.Kl, self.w, self.h = plane, pose, a, b, Kl, w, h
        self.rt, self.c, self.gain = transpose(pose[0]), dso.center(pose), math.exp(a)

    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 self.gain * 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, state, levels):
    pose, a, b = state
    return [AnalyticImage(plane, pose, a, b, dso.level_K(K, l), W >> l, H >> l) for l in range(levels)]


def make_pose(w, c):
    R = dso.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_points(step, margin=6):
    return [(float(u), float(v)) for v in range(margin, H - margin, step) for u in range(margin, W - margin, step)]


IDENT = (dso.eye(3), [0.0, 0.0, 0.0])


def test_jacobians_match_finite_differences():
    plane = Plane(5.0, 0.2)
    host = (make_pose([0.02, -0.03, 0.01], [0.1, -0.2, 0.3]), 0.15, 4.0)
    tgt = (make_pose([-0.01, 0.04, 0.02], [0.4, 0.1, 0.2]), -0.1, -3.0)
    himg = AnalyticImage(plane, *host)
    timg = AnalyticImage(plane, *tgt)
    q, d = (21.3, 16.7), 0.21
    r, _, _, jt, jh, jd = dso.residual(himg, timg, K, q, d, host, tgt, True)
    e = 1e-6

    def r_of(h, t, dd):
        return dso.residual(himg, timg, K, q, dd, h, t)[0]

    def bump(state, k, s):
        pose, a, b = state
        if k < 6:
            delta = [0.0] * 6
            delta[k] = s
            return dso.apply_update(pose, delta), a, b
        return (pose, a + s, b) if k == 6 else (pose, a, b + s)

    for k in range(8):
        num = (r_of(host, bump(tgt, k, e), d) - r_of(host, bump(tgt, k, -e), d)) / (2 * e)
        assert abs(num - jt[k]) <= 1e-4 * (1.0 + abs(num))
        num = (r_of(bump(host, k, e), tgt, d) - r_of(bump(host, k, -e), tgt, d)) / (2 * e)
        assert abs(num - jh[k]) <= 1e-4 * (1.0 + abs(num))
    num = (r_of(host, tgt, d + e) - r_of(host, tgt, d - e)) / (2 * e)
    assert abs(num - jd) <= 1e-4 * (1.0 + abs(num))
    assert abs(r - r_of(host, tgt, d)) == 0.0


def test_tracking_recovers_pose_and_brightness():
    plane = Plane(5.0)
    host = (IDENT, 0.1, 3.0)
    truth = (make_pose([0.004, -0.008, 0.003], [0.08, -0.05, 0.1]), -0.15, 7.0)
    hp = analytic_pyramid(plane, host, 2)
    tp = analytic_pyramid(plane, truth, 2)
    pts = [(u, v, plane.inv_depth(IDENT, u, v)) for u, v in grid_points(6)]
    (pose, a, b), rmse = dso.track_frame(pts, hp, tp, K, host, (IDENT, 0.0, 0.0))
    ang, dt = pose_err(pose, truth[0])
    assert ang < 1e-7 and dt < 1e-6
    assert abs(a - truth[1]) < 1e-6 and abs(b - truth[2]) < 1e-4
    assert rmse < 1e-5


def test_search_depth_finds_inverse_depth():
    plane = Plane(4.0)
    host = (IDENT, 0.0, 0.0)
    tgt = (make_pose([0.0, 0.01, 0.0], [0.3, 0.05, 0.0]), 0.05, 2.0)
    himg, timg = AnalyticImage(plane, *host), AnalyticImage(plane, *tgt)
    for p in [(14.0, 12.0), (30.0, 20.0), (22.0, 9.0)]:
        d, rmse = dso.search_depth(himg, timg, K, p, host, tgt, 0.05, 0.6)
        assert abs(d - 0.25) < 1e-6
        assert rmse < 1e-5


def test_schur_complement_equals_joint_minimum():
    rng = random.Random(3)
    n = 7
    A = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
    Hm = [[sum(A[k][i] * A[k][j] for k in range(n)) + (1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
    b = [rng.uniform(-1, 1) for _ in range(n)]
    keep, drop = [0, 2, 5], [1, 3, 4, 6]
    Hn, bn = dso.schur_marginalize(Hm, b, keep, drop)
    full = solve(Hm, b)
    red = solve(Hn, bn)
    for i, k in enumerate(keep):
        assert abs(red[i] - full[k]) < 1e-10

    def energy(x):
        return -sum(p * q for p, q in zip(b, x)) + 0.5 * sum(x[i] * Hm[i][j] * x[j] for i in range(n) for j in range(n))

    def reduced_gap(xk):
        # min over the dropped part, compared with the reduced quadratic
        rhs = [b[d] - sum(Hm[d][k] * xk[i] for i, k in enumerate(keep)) for d in drop]
        xd = solve([[Hm[d][e] for e in drop] for d in drop], rhs)
        x = [0.0] * n
        for i, k in enumerate(keep):
            x[k] = xk[i]
        for i, d in enumerate(drop):
            x[d] = xd[i]
        er = -sum(p * q for p, q in zip(bn, xk)) + 0.5 * sum(xk[i] * Hn[i][j] * xk[j] for i in range(3) for j in range(3))
        return energy(x) - er

    g1 = reduced_gap([0.3, -0.2, 0.7])
    g2 = reduced_gap([-1.1, 0.4, 0.0])
    assert abs(g1 - g2) < 1e-10


def window_scene():
    plane = Plane(5.0)
    truth = {0: (IDENT, 0.0, 0.0),
             1: (make_pose([0.0, 0.0, 0.0], [0.2, 0.05, 0.1]), 0.1, 4.0),
             2: (make_pose([0.006, -0.01, 0.004], [0.4, -0.05, 0.15]), -0.12, -5.0),
             3: (make_pose([0.0, 0.0, 0.0], [0.55, 0.02, 0.2]), 0.05, 2.0)}
    kfs = {f: dso.Keyframe(f, AnalyticImage(plane, *s), s[0], s[1], s[2], fixed=(f == 0)) for f, s in truth.items()}
    pts = [dso.Point(0, u, v, plane.inv_depth(IDENT, u, v), fixed=(k == 0)) for k, (u, v) in enumerate(grid_points(7))]
    c1 = truth[1][0]
    pts += [dso.Point(1, u, v, plane.inv_depth(c1, u, v)) for u, v in grid_points(9, 8)]
    return plane, truth, kfs, pts


def perturb(kfs, pts, rng, fids):
    for f in fids:
        kf = kfs[f]
        kf.pose = dso.apply_update(kf.pose, [rng.uniform(-0.004, 0.004) for _ in range(3)]
                                   + [rng.uniform(-0.02, 0.02) for _ in range(3)])
        kf.a += rng.uniform(-0.03, 0.03)
        kf.b += rng.uniform(-1.0, 1.0)
    for p in pts:
        if not p.fixed:
            p.d *= 1.0 + rng.uniform(-0.03, 0.03)


def check_truth(kfs, pts, truth, plane, tol):
    for f, kf in kfs.items():
        ang, dt = pose_err(kf.pose, truth[f][0])
        assert ang < tol and dt < tol
        assert abs(kf.a - truth[f][1]) < tol and abs(kf.b - truth[f][2]) < 100 * tol
    for p in pts:
        assert abs(p.d - plane.inv_depth(truth[p.host][0], p.u, p.v)) < tol


def test_window_optimization_recovers_truth():
    plane, truth, kfs, pts = window_scene()
    del kfs[3]
    rng = random.Random(5)
    perturb(kfs, pts, rng, [1, 2])
    hist = dso.optimize_window(kfs, pts, K, None, iters=10)
    assert all(x > y for x, y in zip(hist, hist[1:]))
    assert hist[-1] < 1e-12 * hist[0]
    check_truth(kfs, pts, truth, plane, 1e-6)


def test_marginalization_keeps_the_truth():
    plane, truth, kfs, pts = window_scene()
    pts, prior = dso.marginalize_keyframe(kfs, pts, K, None, 1)
    assert sorted(kfs) == [0, 2, 3]
    assert all(p.host == 0 for p in pts)
    assert prior.fids == [2, 3] and len(prior.H) == 16
    assert max(abs(x) for x in prior.b) < 1e-6
    for i in range(16):
        for j in range(16):
            assert abs(prior.H[i][j] - prior.H[j][i]) < 1e-6 * (1.0 + abs(prior.H[i][j]))
    # the prior plus the remaining residuals still have their minimum at the truth
    rng = random.Random(9)
    perturb(kfs, pts, rng, [2, 3])
    hist = dso.optimize_window(kfs, pts, K, prior, iters=10)
    assert all(x > y for x, y in zip(hist, hist[1:]))
    check_truth(kfs, pts, truth, plane, 1e-6)


def test_keyframe_score_by_hand():
    host = (IDENT, 0.1, 0.0)
    pts = [(K[2], K[3], 0.2)]
    tgt = (make_pose([0.0, 0.0, 0.0], [-0.5, 0.0, 0.0]), 0.4, 0.0)  # moves 0.5 to the left
    s = dso.keyframe_score(pts, K, host, tgt, 1.0, 2.0, 10.0)
    assert abs(s - (4.0 + 2.0 * 4.0 + 10.0 * 0.3)) < 1e-12
    rot = (dso.relative(make_pose([0.0, 0.01, 0.0], [0.0, 0.0, 0.0]), IDENT), 0.1, 0.0)
    s = dso.keyframe_score(pts, K, host, rot, 0.0, 1.0, 0.0)
    assert abs(s) < 1e-12
    s = dso.keyframe_score(pts, K, host, rot, 1.0, 0.0, 0.0)
    assert abs(s - 40.0 * math.tan(0.01)) < 1e-9


def test_select_points():
    flat = dso.GridImage([[50.0] * 20 for _ in range(16)])
    assert dso.select_points(flat, 4, 3.0) == []
    edge = dso.GridImage([[0.0 if u < 10 else 100.0 for u in range(20)] for _ in range(16)])
    got = dso.select_points(edge, 4, 3.0)
    assert got and all(u in (9, 10) for u, _ in got)
    assert len(set(got)) == len(got)


def test_choose_marginalized_by_hand():
    plane = Plane(5.0)
    kfs = {}
    xs = [0.0, 0.1, 0.5, 0.6, 0.7]
    for f, x in enumerate(xs):
        pose = make_pose([0.0, 0.0, 0.0], [x, 0.0, 0.0])
        kfs[f] = dso.Keyframe(f, AnalyticImage(plane, pose, 0.0, 0.0), pose)
    pts = [dso.Point(f, 24.0, 18.0, 0.2) for f in kfs]
    eps = 1e-3

    def score(f):
        return math.sqrt(abs(xs[f] - xs[4])) * sum(1.0 / (abs(xs[f] - xs[j]) + eps) for j in range(4) if j != f)

    want = max(range(3), key=score)
    assert dso.choose_marginalized(kfs, pts, K, 4, eps) == want
    assert dso.choose_marginalized(kfs, pts, K, 5, eps) is None
    # a keyframe whose points all leave the newest image goes first
    pts.append(dso.Point(2, 24.0, 18.0, 0.2))
    pts[2] = dso.Point(1, 2.0, 18.0, 0.2)
    pts[1] = dso.Point(1, 2.0, 18.0, 0.2)
    assert dso.choose_marginalized(kfs, pts, K, 5, eps) == 1


def test_run_dso_on_pixel_grids():
    # Bilinear sampling of a pixel grid is not the true image, so the
    # estimates are not exact here. Even a single tracking step from frame 0
    # to frame 1 with the true depths is off by about 0.05 degree, and a
    # rotation about the vertical axis looks much like a sideways move, so
    # the errors add up along the path. The bounds below are loose on purpose.
    plane = Plane(5.0, 0.1)
    n = 7
    truth = [(make_pose([0.0, 0.003 * k, 0.001 * k], [0.12 * k, 0.02 * k, 0.03 * k]), 0.02 * k, 1.5 * k)
             for k in range(n)]
    frames = []
    for pose, a, b in truth:
        img = AnalyticImage(plane, pose, a, b)
        frames.append(dso.GridImage([[img.value(u, v) for u in range(W)] for v in range(H)]))
    out = dso.run_dso(frames, K, lambda u, v: plane.inv_depth(IDENT, u, v), levels=2, n_max=3, block=6,
                      g_th=3.0, t_kf=4.0)
    assert len(out["keyframes"]) == 3
    assert out["prior"] is not None  # at least one keyframe was marginalized
    path = 0.0
    for k in range(1, n):
        path += norm([a - b for a, b in zip(dso.center(truth[k][0]), dso.center(truth[k - 1][0]))])
    for k in range(n):
        ang, _ = pose_err(out["states"][k][0], truth[k][0])
        dc = norm([a - b for a, b in zip(dso.center(out["states"][k][0]), dso.center(truth[k][0]))])
        assert ang < math.radians(1.0)
        assert dc < 0.1 * path
        assert abs(out["states"][k][1] - truth[k][1]) < 0.03

History

Direct methods track the camera by aligning image intensities, an idea that goes back to the work of Lucas and Kanade (1981) and was made into a theory for camera motion by Irani and Anandan (1999). DTAM (2011) and LSD-SLAM (2014) used dense and semi-dense depth maps. Engel, Koltun and Cremers published DSO as an arXiv preprint in July 2016 and in IEEE TPAMI in 2018. Its authors describe it as a fully direct model with a joint optimization of all parameters of a window of keyframes, including the affine brightness terms. Old keyframes leave by marginalization, in the manner of the sliding window filters of Sibley, Matthies and Sukhatme and the keyframe window of OKVIS (Leutenegger and others, 2015).

References

  1. Jakob Engel, Vladlen Koltun and Daniel Cremers, Direct sparse odometry, IEEE Transactions on Pattern Analysis and Machine Intelligence 40(3), 2018, 611-625, Section 2 (the photometric model, the residual pattern, the weights and the windowed Gauss-Newton optimization with marginalization) and Section 3 (frame tracking, keyframe creation and marginalization, point selection and activation)
  2. Gabe Sibley, Larry Matthies and Gaurav Sukhatme, Sliding window filters and their application to planetary landing, Journal of Field Robotics 27(5), 2010, 587-608, the sliding window filter, which removes old states from a window of states by marginalization with the Schur complement
  3. Simon Baker and Iain Matthews, Lucas-Kanade 20 years on: a unifying framework, International Journal of Computer Vision 56(3), 2004, 221-255, the Gauss-Newton image alignment that frame tracking uses

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