Algorithm Search⌘K

Algorithmcore

Zhang's calibration method

Also called planar camera calibration, Zhang's method.

Calibrate a camera from several views of a planar pattern, getting K in closed form from the homographies and refining all parameters with Levenberg-Marquardt.

Time
O(n N + T n N^3) worst · average · best
Space
O(n N^2) extra
Where
N = the number of views; T = the number of Levenberg-Marquardt iterations; n = the number of points on the pattern
Properties
deterministicnot exactofflineiterative
Origin
Zhengyou Zhang, 2000

Zhang's method calibrates a camera from N≥3N \ge 3 photos of a flat pattern, such as a printed checkerboard, taken from different angles. Each photo gives a homography Hj∼K[r1  r2  t]H_j \sim K [r_1 \; r_2 \; t] from the plane to the image. Because r1r_1 and r2r_2 are orthonormal, each HjH_j gives two linear equations on the symmetric matrix B=K−TK−1B = K^{-\mathsf T} K^{-1}. An SVD solves for BB, a closed form gives KK, and K−1HjK^{-1} H_j gives each pose. A Levenberg-Marquardt fit of the reprojection error over all parameters, with radial distortion, then gives the final answer. Among the close pages, camera calibration states the problem; DLT resectioning needs a 3D target, not a plane, and estimates a general PP; camera matrix decomposition splits such a PP; and Tsai's method uses the radial alignment constraint, which needs a known principal point.

In plain words

Print a checkerboard and glue it to a flat board. Take ten or so photos of it, tilted in different ways. In each photo the board looks like a squashed square. How it is squashed depends both on how the board is tilted and on the camera's focal length and center. One tilt alone cannot separate the two. But the true corners of the board are at right angles and the squares are equal, and every tilted view must agree with that. Each photo gives two such conditions on the camera. Three photos are enough to solve for the camera in one step. Then a search adjusts all the numbers together, with the lens bending, until the predicted corners land on the found corners.

The problem

Input. Model points mi=(Xi,Yi)m_i = (X_i, Y_i), i=1,…,ni = 1, \dots, n, on the plane Z=0Z = 0 of the pattern frame, with n≥4n \ge 4 and no three on one line; and their pixels uiju_{ij} in views j=1,…,Nj = 1, \dots, N. Either N≥3N \ge 3, or N≥2N \ge 2 with zero skew.

Output. KK, the radial distortion (k1,k2)(k_1, k_2), and the pose (Rj,tj)(R_j, t_j) of each view. The model is: Xc=Rj(Xi,Yi,0)T+tjX_c = R_j (X_i, Y_i, 0)^{\mathsf T} + t_j, (x,y)=(Xc/Zc,Yc/Zc)(x, y) = (X_c / Z_c, Y_c / Z_c), xd=x(1+k1r2+k2r4)x_d = x (1 + k_1 r^2 + k_2 r^4) and yd=y(1+k1r2+k2r4)y_d = y (1 + k_1 r^2 + k_2 r^4) with r2=x2+y2r^2 = x^2 + y^2, and u=K(xd,yd,1)Tu = K (x_d, y_d, 1)^{\mathsf T}.

Goal. Minimize the reprojection error ∑j∑i∥uij−π(K,k1,k2,Rj,tj;mi)∥2\sum_{j} \sum_{i} \| u_{ij} - \pi(K, k_1, k_2, R_j, t_j; m_i) \|^2, which is the maximum likelihood estimate under Gaussian pixel noise.

The algorithm

For a point on Z=0Z = 0, K[r1  r2  r3  t](X,Y,0,1)T=K[r1  r2  t](X,Y,1)TK [r_1 \; r_2 \; r_3 \; t] (X, Y, 0, 1)^{\mathsf T} = K [r_1 \; r_2 \; t] (X, Y, 1)^{\mathsf T}, so the view is the homography H=[h1  h2  h3]=λK[r1  r2  t]H = [h_1 \; h_2 \; h_3] = \lambda K [r_1 \; r_2 \; t]. Then K−1h1K^{-1} h_1 and K−1h2K^{-1} h_2 are orthogonal and of equal length, which gives

h1TBh2=0,h1TBh1−h2TBh2=0,B=K−TK−1.h_1^{\mathsf T} B h_2 = 0, \qquad h_1^{\mathsf T} B h_1 - h_2^{\mathsf T} B h_2 = 0, \qquad B = K^{-\mathsf T} K^{-1}.

With b=(B11,B12,B22,B13,B23,B33)b = (B_{11}, B_{12}, B_{22}, B_{13}, B_{23}, B_{33}) and the columns hi=(hi1,hi2,hi3)h_i = (h_{i1}, h_{i2}, h_{i3}), one has hiTBhj=vijTbh_i^{\mathsf T} B h_j = v_{ij}^{\mathsf T} b with

vij=(hi1hj1,  hi1hj2+hi2hj1,  hi2hj2,  hi3hj1+hi1hj3,  hi3hj2+hi2hj3,  hi3hj3).v_{ij} = (h_{i1} h_{j1},\; h_{i1} h_{j2} + h_{i2} h_{j1},\; h_{i2} h_{j2},\; h_{i3} h_{j1} + h_{i1} h_{j3},\; h_{i3} h_{j2} + h_{i2} h_{j3},\; h_{i3} h_{j3}).

So each view adds the rows v12Tv_{12}^{\mathsf T} and (v11−v22)T(v_{11} - v_{22})^{\mathsf T} to a matrix VV with Vb=0V b = 0. The matrix BB is the image of the absolute conic ω\omega, and the two equations say that the images of the two circular points of the plane lie on it.

  1. ZHANG-CALIBRATE(m_1..m_n, u_ij for views j = 1..N)
  2. 1for j <- 1 to N: H_j <- normalized DLT homography from the m_i to the u_ij
  3. 2for j <- 1 to N: add the rows v_12(H_j)^T and (v_11(H_j) - v_22(H_j))^T to V
  4. 3if the skew is known to be 0 then add the row (0, 1, 0, 0, 0, 0) to V
  5. 4b <- unit right singular vector of V for the smallest singular value
  6. 5K_0 <- closed form intrinsics from b
  7. 6for j <- 1 to N: (R_j, t_j) <- pose from K_0^-1 H_j, then the nearest rotation
  8. 7(k_1, k_2) <- linear least squares with K_0 and the poses fixed
  9. 8minimize the reprojection error over K, k_1, k_2, R_j, t_j by Levenberg-Marquardt
  10. 9return K, k_1, k_2, (R_j, t_j) for j = 1..N

Line L1 is the DLT for homographies with the normalization of Hartley. Line L4 needs at least 5 rows; with fewer, the code raises an error. Line L5 is the closed form of Zhang (2000). With λ\lambda the unknown scale of bb,

v0=B12B13−B11B23B11B22−B122,λ=B33−B132+v0(B12B13−B11B23)B11,α=λ/B11,v_0 = \frac{B_{12} B_{13} - B_{11} B_{23}}{B_{11} B_{22} - B_{12}^2}, \quad \lambda = B_{33} - \frac{B_{13}^2 + v_0 (B_{12} B_{13} - B_{11} B_{23})}{B_{11}}, \quad \alpha = \sqrt{\lambda / B_{11}},
β=λB11B11B22−B122,γ=−B12α2βλ,u0=γv0β−B13α2λ,\beta = \sqrt{\frac{\lambda B_{11}}{B_{11} B_{22} - B_{12}^2}}, \quad \gamma = -\frac{B_{12} \alpha^2 \beta}{\lambda}, \quad u_0 = \frac{\gamma v_0}{\beta} - \frac{B_{13} \alpha^2}{\lambda},

and K0=(αγu00βv0001)K_0 = \begin{pmatrix} \alpha & \gamma & u_0 \\ 0 & \beta & v_0 \\ 0 & 0 & 1 \end{pmatrix}. The sign of bb does not matter. Line L6 sets r1=μK0−1h1r_1 = \mu K_0^{-1} h_1, r2=μK0−1h2r_2 = \mu K_0^{-1} h_2, r3=r1×r2r_3 = r_1 \times r_2 and t=μK0−1h3t = \mu K_0^{-1} h_3, with μ=±1/∥K0−1h1∥\mu = \pm 1 / \|K_0^{-1} h_1\| and the sign that puts the plane in front of the camera (tz>0t_z > 0). With noise, [r1  r2  r3][r_1 \; r_2 \; r_3] is not exactly a rotation, so it is replaced by the nearest rotation UVTU V^{\mathsf T} from its SVD. Line L7 uses the fact that, with (u,v)(u, v) the ideal pixel and (u˘,v˘)(\breve u, \breve v) the distorted one, u˘−u=(u−cx)(k1r2+k2r4)\breve u - u = (u - c_x)(k_1 r^2 + k_2 r^4), and the same for vv; these are two linear equations in (k1,k2)(k_1, k_2) per point. Line L8 fits all 7+6N7 + 6N parameters, with each rotation as a rotation vector.

Example

The closed form on exact numbers. Take K=(213042001)K = \begin{pmatrix} 2 & 1 & 3 \\ 0 & 4 & 2 \\ 0 & 0 & 1 \end{pmatrix}. Then K−1=(1/2−1/8−5/401/4−1/2001)K^{-1} = \begin{pmatrix} 1/2 & -1/8 & -5/4 \\ 0 & 1/4 & -1/2 \\ 0 & 0 & 1 \end{pmatrix}, and B=K−TK−1B = K^{-\mathsf T} K^{-1} gives

b=(14,−116,564,−58,132,4516).b = \left(\tfrac{1}{4}, -\tfrac{1}{16}, \tfrac{5}{64}, -\tfrac{5}{8}, \tfrac{1}{32}, \tfrac{45}{16}\right).

Line L5: B11B22−B122=1/64B_{11} B_{22} - B_{12}^2 = 1/64 and B12B13−B11B23=1/32B_{12} B_{13} - B_{11} B_{23} = 1/32, so v0=2v_0 = 2; λ=45/16−(25/64+2/32)⋅4=1\lambda = 45/16 - (25/64 + 2/32) \cdot 4 = 1; α=4=2\alpha = \sqrt{4} = 2; β=16=4\beta = \sqrt{16} = 4; γ=(1/16)⋅4⋅4=1\gamma = (1/16) \cdot 4 \cdot 4 = 1; u0=1⋅2/4+(5/8)⋅4=3u_0 = 1 \cdot 2 / 4 + (5/8) \cdot 4 = 3. This is KK. With −3b-3 b in place of bb, λ\lambda becomes −3-3 and the same KK comes out.

A full run. The reference tests use KK with fx=800f_x = 800, fy=780f_y = 780, skew 1.51.5 and principal point (320,240)(320, 240), radial distortion k1=−0.25k_1 = -0.25, k2=0.08k_2 = 0.08, a 6×56 \times 5 grid of unit spacing, and 4 views tilted by up to about 0.5 radians at a depth of 12.

step result
L1 to L5, exact pixels K0=(810.421.46320.510790.95240.97)K_0 = \begin{pmatrix} 810.42 & 1.46 & 320.51 \\ 0 & 790.95 & 240.97 \end{pmatrix}, off by about 1.3% because the closed form ignores distortion
L7 a first (k1,k2)(k_1, k_2) with K0K_0 fixed
L8 the cost falls from 17.02 to 3.3⋅10−253.3 \cdot 10^{-25} in 7 accepted steps
L9 KK, k1k_1, k2k_2 and all poses equal to the true values with a relative error below 10−610^{-6}

Without distortion, 3 views give KK to 12 digits from line L5 alone. With pixel noise of σ=0.2\sigma = 0.2 on 5 views, zero skew and the same distortion, one run (seed 7) gave fx=798.24f_x = 798.24, fy=778.00f_y = 778.00, principal point (317.96,238.69)(317.96, 238.69), k1=−0.2472k_1 = -0.2472, k2=0.0167k_2 = 0.0167 and an RMS reprojection error of 0.19 pixel. The focal lengths are good to 0.3%, but k2k_2 is far from 0.08: with 30 points per view, the r4r^4 term is weakly determined.

Correctness

With exact data and no distortion, each HjH_j is λjK[r1  r2  t]\lambda_j K [r_1 \; r_2 \; t], so the true bb satisfies Vb=0V b = 0. If VV has rank 5, which holds for 3 views in general position, line L4 returns a multiple of the true bb. The closed form of line L5 recovers KK from any nonzero multiple μK−TK−1\mu K^{-\mathsf T} K^{-1}: one checks that the expression for λ\lambda equals μ\mu, and then each formula gives the matching entry of KK. Line L6 then gives the exact poses. Line L8 accepts only steps that lower the cost, so the cost never increases; it converges to a local minimum, which is the global one when the start is close, as the closed form makes it in practice. The full proof is in the proof file below.

Proof: The closed form of Zhang's method recovers K and the poses from exact views of a plane, and the refinement never increases the costfull

We use the notation of the page. K=(αγu00βv0001)K = \begin{pmatrix} \alpha & \gamma & u_0 \\ 0 & \beta & v_0 \\ 0 & 0 & 1 \end{pmatrix} with α,β>0\alpha, \beta > 0. View jj has the pose (Rj,tj)(R_j, t_j) with columns Rj=[r1  r2  r3]R_j = [r_1 \; r_2 \; r_3] and tj,z>0t_{j,z} > 0 for the points of the pattern. We write B∗=K−TK−1B^\ast = K^{-\mathsf T} K^{-1} and b∗b^\ast for its six entries in the order (B11,B12,B22,B13,B23,B33)(B_{11}, B_{12}, B_{22}, B_{13}, B_{23}, B_{33}).

Claim. (a) If the pixels are exact, there is no distortion, the model points include 4 points with no three on one line, and the matrix VV of lines L2 and L3 has rank 5, then line L5 returns the true KK and line L6 returns the true poses. (b) Line L8 never increases the reprojection error.

We assume, as the method does, that the camera center is not on the plane of the pattern in any view.

Lemma 1 (homography of a view). For a model point (X,Y)(X, Y), the pixel is u∼H(X,Y,1)Tu \sim H (X, Y, 1)^{\mathsf T} with H=K[r1  r2  t]H = K [r_1 \; r_2 \; t], and HH is invertible.

Proof. The point is (X,Y,0)(X, Y, 0) in the pattern frame, so K(R(X,Y,0)T+t)=K(Xr1+Yr2+t)=K[r1  r2  t](X,Y,1)TK (R (X, Y, 0)^{\mathsf T} + t) = K (X r_1 + Y r_2 + t) = K [r_1 \; r_2 \; t] (X, Y, 1)^{\mathsf T}. Suppose [r1  r2  t]c=0[r_1 \; r_2 \; t] c = 0 for some c≠0c \ne 0. Then c3≠0c_3 \ne 0, because r1r_1 and r2r_2 are independent, and the point (c1/c3,c2/c3,0)(c_1 / c_3, c_2 / c_3, 0) of the plane has camera coordinates c1/c3 r1+c2/c3 r2+t=0c_1 / c_3\, r_1 + c_2 / c_3\, r_2 + t = 0. So the camera center lies on the plane, which we excluded. Hence [r1  r2  t][r_1 \; r_2 \; t] and HH are invertible. □\square

By the DLT for homographies, 4 exact correspondences with no three on one line determine HH up to a nonzero scale, so line L1 returns Hj=λjK[r1  r2  tj]H_j = \lambda_j K [r_1 \; r_2 \; t_j] with λj≠0\lambda_j \ne 0.

Lemma 2 (the two equations). For every view, h1TB∗h2=0h_1^{\mathsf T} B^\ast h_2 = 0 and h1TB∗h1=h2TB∗h2h_1^{\mathsf T} B^\ast h_1 = h_2^{\mathsf T} B^\ast h_2. For every symmetric BB with entry vector bb and every pair of vectors hi,hjh_i, h_j, hiTBhj=vijTbh_i^{\mathsf T} B h_j = v_{ij}^{\mathsf T} b.

Proof. K−1h1=λjr1K^{-1} h_1 = \lambda_j r_1 and K−1h2=λjr2K^{-1} h_2 = \lambda_j r_2, so h1TB∗h2=λj2r1Tr2=0h_1^{\mathsf T} B^\ast h_2 = \lambda_j^2 r_1^{\mathsf T} r_2 = 0 and hkTB∗hk=λj2∥rk∥2=λj2h_k^{\mathsf T} B^\ast h_k = \lambda_j^2 \|r_k\|^2 = \lambda_j^2 for k=1,2k = 1, 2. For the second part, expand hiTBhj=∑k,lBklhikhjlh_i^{\mathsf T} B h_j = \sum_{k, l} B_{kl} h_{ik} h_{jl}; the diagonal terms give B11hi1hj1B_{11} h_{i1} h_{j1}, B22hi2hj2B_{22} h_{i2} h_{j2}, B33hi3hj3B_{33} h_{i3} h_{j3}, and each off-diagonal pair Bkl=BlkB_{kl} = B_{lk} gives Bkl(hikhjl+hilhjk)B_{kl} (h_{ik} h_{jl} + h_{il} h_{jk}). These are the six entries of vijv_{ij}. □\square

So the true b∗b^\ast satisfies Vb∗=0V b^\ast = 0. The row (0,1,0,0,0,0)(0, 1, 0, 0, 0, 0) of line L3 says B12=0B_{12} = 0, and B12∗=−γ/(α2β)=0B^\ast_{12} = -\gamma / (\alpha^2 \beta) = 0 when the skew γ\gamma is 0, so it holds too. If VV has rank 5, its null space is spanned by b∗b^\ast, and line L4 returns b=μ b∗b = \mu\, b^\ast for some μ≠0\mu \ne 0, by the minimum property of the smallest right singular vector.

Lemma 3 (the closed form). If B=μK−TK−1B = \mu K^{-\mathsf T} K^{-1} with μ≠0\mu \ne 0, the formulas of line L5 return KK.

Proof. K−1=(1/α−γ/(αβ)(γv0−u0β)/(αβ)01/β−v0/β001)K^{-1} = \begin{pmatrix} 1/\alpha & -\gamma/(\alpha\beta) & (\gamma v_0 - u_0 \beta)/(\alpha\beta) \\ 0 & 1/\beta & -v_0/\beta \\ 0 & 0 & 1 \end{pmatrix}. Write e=γv0−u0βe = \gamma v_0 - u_0 \beta. Multiplying out μK−TK−1\mu K^{-\mathsf T} K^{-1} gives

B11=μα2,B12=−μγα2β,B22=μ(γ2α2β2+1β2),B13=μeα2β,B_{11} = \frac{\mu}{\alpha^2}, \quad B_{12} = -\frac{\mu \gamma}{\alpha^2 \beta}, \quad B_{22} = \mu \Big(\frac{\gamma^2}{\alpha^2 \beta^2} + \frac{1}{\beta^2}\Big), \quad B_{13} = \frac{\mu e}{\alpha^2 \beta},
B23=−μ(γeα2β2+v0β2),B33=μ(e2α2β2+v02β2+1).B_{23} = -\mu \Big(\frac{\gamma e}{\alpha^2 \beta^2} + \frac{v_0}{\beta^2}\Big), \quad B_{33} = \mu \Big(\frac{e^2}{\alpha^2 \beta^2} + \frac{v_0^2}{\beta^2} + 1\Big).

Then B11B22−B122=μ2/(α2β2)B_{11} B_{22} - B_{12}^2 = \mu^2 / (\alpha^2 \beta^2), which is positive, and

B12B13−B11B23=μ2(−γeα4β2+γeα4β2+v0α2β2)=μ2v0α2β2.B_{12} B_{13} - B_{11} B_{23} = \mu^2 \Big(-\frac{\gamma e}{\alpha^4 \beta^2} + \frac{\gamma e}{\alpha^4 \beta^2} + \frac{v_0}{\alpha^2 \beta^2}\Big) = \frac{\mu^2 v_0}{\alpha^2 \beta^2}.

So the first formula gives v0v_0. Next, B132/B11=μe2/(α2β2)B_{13}^2 / B_{11} = \mu e^2 / (\alpha^2 \beta^2) and v0(B12B13−B11B23)/B11=μv02/β2v_0 (B_{12} B_{13} - B_{11} B_{23}) / B_{11} = \mu v_0^2 / \beta^2, so the formula for λ\lambda gives B33−μe2/(α2β2)−μv02/β2=μB_{33} - \mu e^2/(\alpha^2\beta^2) - \mu v_0^2/\beta^2 = \mu. Then λ/B11=α2>0\lambda / B_{11} = \alpha^2 > 0, so the formula gives α\alpha; λB11/(B11B22−B122)=μ⋅(μ/α2)⋅(α2β2/μ2)=β2\lambda B_{11} / (B_{11} B_{22} - B_{12}^2) = \mu \cdot (\mu / \alpha^2) \cdot (\alpha^2 \beta^2 / \mu^2) = \beta^2, so it gives β\beta; −B12α2β/λ=(μγ/(α2β))⋅α2β/μ=γ-B_{12} \alpha^2 \beta / \lambda = (\mu \gamma / (\alpha^2 \beta)) \cdot \alpha^2 \beta / \mu = \gamma; and γv0/β−B13α2/λ=γv0/β−e/β=u0\gamma v_0 / \beta - B_{13} \alpha^2 / \lambda = \gamma v_0 / \beta - e / \beta = u_0. The sign of μ\mu cancels in every step. □\square

Lemma 4 (the poses). With the true KK and Hj=λjK[r1  r2  tj]H_j = \lambda_j K [r_1 \; r_2 \; t_j], line L6 returns RjR_j and tjt_j.

Proof. K−1h1=λjr1K^{-1} h_1 = \lambda_j r_1 has norm ∣λj∣|\lambda_j|, so μ=±1/∣λj∣\mu = \pm 1 / |\lambda_j| gives μK−1h1=±r1\mu K^{-1} h_1 = \pm r_1, with the same sign ϵ=±1\epsilon = \pm 1 for r2r_2 and tjt_j. The code picks the sign with a positive third entry of μK−1h3=ϵtj\mu K^{-1} h_3 = \epsilon t_j; since tj,z>0t_{j,z} > 0, this is ϵ=+1\epsilon = +1. Then r3=r1×r2r_3 = r_1 \times r_2 is the third column of the rotation RjR_j, because the columns of a rotation form a right handed orthonormal basis. The matrix is already a rotation, and the nearest rotation to a rotation QQ is QQ itself (Q=USVTQ = U S V^{\mathsf T} with S=IS = I gives UVT=QU V^{\mathsf T} = Q). □\square

Proof of (a). Lemmas 1 and 2 show Vb∗=0V b^\ast = 0. With rank 5, line L4 returns a nonzero multiple of b∗b^\ast. Lemma 3 shows that line L5 returns KK, and Lemma 4 that line L6 returns the poses. □\square

Proof of (b). In line L8, a step is accepted only if the new cost is strictly lower than the current one; otherwise the damping grows and the step is tried again, and the loop ends if no step is accepted. So the sequence of accepted costs is strictly decreasing, and the returned parameters have a cost no higher than the start. □\square

Remark (rank of V). Lemma 2 depends on the plane only through r1r_1 and r2r_2, that is, through the orientation of the plane. Two views with the same RjR_j give the same two rows up to scale, so pure translations of the pattern do not raise the rank of VV. In general position, each view with a new orientation adds up to 2 to the rank, so 3 views reach rank 5 (and 2 views with the row of line L3). Finally, (b) does not say that line L8 finds the global minimum; with exact data, the start of (a) already has cost 0 when there is no distortion, and in the presence of distortion the start is close enough in practice, which is a heuristic, not a theorem.

Complexity

The time is O(nN)O(n N) for lines L1 to L7: each homography is an SVD of a 2n×92n \times 9 matrix, and VV has 2N2N (or 2N+12N + 1) rows and 6 columns. Each Levenberg-Marquardt iteration in the reference code forms the Jacobian by forward differences, which costs O(nN)O(n N) model evaluations because a pose parameter affects only its own view, then forms the dense normal matrix of size 7+6N7 + 6N in O(nN⋅N2)O(n N \cdot N^2) and solves it in O(N3)O(N^3). So TT iterations cost O(TnN3)O(T n N^3), and the extra space is the dense Jacobian, O(nN2)O(n N^2). The Jacobian is block sparse: with a Schur complement on the pose blocks, as in bundle adjustment, each iteration costs O(nN)O(n N). With N=10N = 10 to 30 views, the dense form is fast enough. The method is not exact: with noise, it returns a local minimum of a nonlinear cost.

Properties

  • Needs only a plane. A printed pattern is cheap and easy to make accurate, unlike a 3D target.
  • No starting guess. Lines L1 to L7 give a start from the data alone.
  • Maximum likelihood at the end. The final fit minimizes the reprojection error, so under Gaussian noise it is the maximum likelihood estimate, if Levenberg-Marquardt finds the global minimum.
  • Degenerate motions. Views of parallel planes give the same two equations, because the equations depend only on the orientation of the plane through its circular points. So pure translations of the pattern add nothing; the tests check that three translated views leave VV with rank 2.
  • Deterministic. The same input gives the same output; there is no random sampling.

Variants and improvements

  • Zero skew. Add the row (0,1,0,0,0,0)(0, 1, 0, 0, 0, 0) (line L3), which needs only 2 views, and keep the skew fixed at 0 in line L8. Most modern cameras have zero skew.
  • More distortion terms. Add a third radial term and the two tangential terms of the Brown-Conrady model, as OpenCV does, only in line L8. For wide lenses, use a fisheye model.
  • Sparse refinement. Exploit the block structure of the Jacobian, as in bundle adjustment, for many views.
  • Better corners. Subpixel corner detection, and patterns with coded marks, such as ChArUco or AprilTag grids, which allow partial views of the board.
  • Several cameras. Calibrate each camera, then fit the fixed relative pose, as in stereo camera calibration.
  • Known principal point. Fix cxc_x and cyc_y in the closed form, so that one view is enough for the focal lengths; this is weaker in accuracy.

When to use it

Use Zhang's method to calibrate a camera in the lab or in the field, when you can move a flat pattern in front of it. It is the default for most cameras with a normal field of view. Use DLT resectioning if you have a precise 3D target. Use self-calibration if no target is available. For lenses wider than about 120 degrees, use a fisheye model in the refinement, because the pinhole start can be far off.

Pitfalls

  • Too little tilt. Views that face the camera, or views that only translate, make VV nearly rank deficient, and the principal point and focal length become unstable. Tilt the board clearly about both axes.
  • Corners only near the center. The distortion is fitted from the corners near the edges of the image. Cover the whole image across all views.
  • Assuming the closed form is the answer. With distortion, K0K_0 is biased, about 1% in the example. Always run line L8.
  • A pattern that is not flat or not to scale. Measure the printed square size; a warped board biases the result, and a wrong square size scales all the translations.
  • Ambiguous board orientation. A symmetric board can be detected rotated by 180 degrees in some views, so the point order changes. Use a board with an odd and an even number of corners, or coded marks.
  • Reporting only the RMS error. A low RMS on the data used for the fit can hide a poorly determined k2k_2 or principal point. Check the parameter spread over subsets of the views.

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.

cvgeom.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Camera geometry and synthetic scenes for the computer vision pages.

Conventions (prompts of the area, also stated on the pages):
- The camera frame has X to the right, Y down and Z forward. A point is in
  front of the camera if Z > 0.
- K = [[fx, s, cx], [0, fy, cy], [0, 0, 1]] in pixels.
- A world point Xw maps to the camera frame by Xc = R Xw + t. The camera
  matrix is P = K [R | t], and the center is C = -R^T t.
- Rotations are active and right-handed. Quaternions are (w, x, y, z) in the
  Hamilton convention.

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

from __future__ import annotations

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

from cvla import det, matvec, mul, solve, transpose

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


def to_h(x: Sequence[float]) -> Vector:
    """Append a 1: the homogeneous vector of a point."""
    return [float(v) for v in x] + [1.0]


def from_h(x: Sequence[float]) -> Vector:
    """Divide by the last entry and drop it. Raises ValueError if the last
    entry is zero (a point at infinity)."""
    w = x[-1]
    if w == 0:
        raise ValueError("from_h: point at infinity")
    return [v / w for v in x[:-1]]


def make_K(fx: float, fy: float, cx: float, cy: float, s: float = 0.0) -> Matrix:
    """The intrinsic matrix [[fx, s, cx], [0, fy, cy], [0, 0, 1]]."""
    return [[float(fx), float(s), float(cx)],
            [0.0, float(fy), float(cy)],
            [0.0, 0.0, 1.0]]


def camera_matrix(K: Sequence[Sequence[float]], R: Sequence[Sequence[float]],
                  t: Sequence[float]) -> Matrix:
    """The 3 x 4 camera matrix P = K [R | t]."""
    rt = [list(R[i]) + [t[i]] for i in range(3)]
    return mul(K, rt)


def project(P: Sequence[Sequence[float]], X):
    """Pixel coordinates (u, v) of a point X under the camera P.

    X is a 3D point (3 entries) or a homogeneous point (4 entries). If X is
    a list of points, the result is the list of their projections."""
    if len(X) > 0 and isinstance(X[0], (list, tuple)):
        return [project(P, x) for x in X]
    xh = to_h(X) if len(X) == 3 else list(X)
    return from_h(matvec(P, xh))


def camera_center(P: Sequence[Sequence[float]]) -> Vector:
    """The center C of a finite camera P = [M | p4]: C = -M^-1 p4, so that
    P (C, 1) = 0."""
    m = [list(row[:3]) for row in P]
    p4 = [row[3] for row in P]
    return [-v for v in solve(m, p4)]


def rot_x(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the X axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a: float) -> Matrix:
    """Rotation by the angle a (radians) about the Z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def axis_angle_to_R(axis: Sequence[float], theta: Optional[float] = None) -> Matrix:
    """Rotation by theta (radians) about the axis, by the right-hand rule
    (Rodrigues formula). The axis need not be a unit vector. If theta is
    None, axis is the rotation vector w = theta a, with theta = ||w||."""
    n = math.sqrt(sum(float(v) * float(v) for v in axis))
    if theta is None:
        theta = n
    if n == 0.0 or theta == 0.0:
        return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    x, y, z = (float(v) / n for v in axis)
    c, s = math.cos(theta), math.sin(theta)
    d = 1.0 - c
    return [[c + x * x * d, x * y * d - z * s, x * z * d + y * s],
            [y * x * d + z * s, c + y * y * d, y * z * d - x * s],
            [z * x * d - y * s, z * y * d + x * s, c + z * z * d]]


def quat_to_R(q: Sequence[float]) -> Matrix:
    """Rotation matrix of the quaternion q = (w, x, y, z), Hamilton
    convention. q is normalized first; q and -q give the same matrix."""
    n = math.sqrt(sum(float(v) * float(v) for v in q))
    if n == 0.0:
        raise ValueError("quat_to_R: zero quaternion")
    w, x, y, z = (float(v) / n for v in q)
    return [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
            [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
            [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]


def random_rotation(rng: random.Random) -> Matrix:
    """A rotation drawn from the uniform (Haar) distribution: a uniform
    random unit quaternion by the method of Shoemake (1992)."""
    u1, u2, u3 = rng.random(), rng.random(), rng.random()
    a, b = math.sqrt(1.0 - u1), math.sqrt(u1)
    q = (b * math.cos(2 * math.pi * u3), a * math.sin(2 * math.pi * u2),
         a * math.cos(2 * math.pi * u2), b * math.sin(2 * math.pi * u3))
    return quat_to_R(q)


def _small_rotation(rng: random.Random, max_angle: float) -> Matrix:
    axis = [rng.gauss(0.0, 1.0) for _ in range(3)]
    return axis_angle_to_R(axis, rng.uniform(0.0, max_angle))


def random_scene(rng: random.Random, n: int = 20, n_cams: int = 2,
                 K: Optional[Sequence[Sequence[float]]] = None,
                 cams: Optional[Sequence[Tuple]] = None,
                 radius: float = 1.0, distance: float = 5.0,
                 max_angle: float = 0.3, planar: bool = False,
                 first_identity: bool = False,
                 size: Optional[Tuple[float, float]] = None,
                 min_depth: float = 0.1) -> Dict[str, list]:
    """A synthetic scene with known cameras and points.

    Cameras: if cams is given, it is a list of (K, R, t) and is used as it
    is. Otherwise n_cams cameras look at the world origin from the distance
    `distance`. Each one is the camera at center (0, 0, -distance) with
    R = I, turned about the origin by a random rotation of angle at most
    max_angle (radians). K defaults to make_K(800, 800, 320, 240). With
    first_identity, the world frame is moved to the frame of camera 0, so
    that camera 0 has R = I and t = 0 (the points move with it).

    Points: n points drawn uniformly in the cube [-radius, radius]^3 (with
    Z = 0 if planar, before any move of the world frame). A point is kept
    only if its depth is at least min_depth in every camera, and, if size =
    (W, H) is given, if its projection lies in [0, W] x [0, H] in every
    camera. Raises ValueError if 1000 n draws are not enough.

    Returns a dict with lists "K", "R", "t", "P" (one entry per camera),
    "X" (the 3D points) and "x" (x[i][j] is the pixel of point j in
    camera i, without noise)."""
    if cams is not None:
        Ks = [[list(r) for r in c[0]] for c in cams]
        Rs = [[list(r) for r in c[1]] for c in cams]
        ts = [list(c[2]) for c in cams]
    else:
        k0 = [list(r) for r in K] if K is not None else make_K(800, 800, 320, 240)
        Ks, Rs, ts = [], [], []
        c0 = [0.0, 0.0, -float(distance)]
        for _ in range(n_cams):
            q = _small_rotation(rng, max_angle)
            r = transpose(q)
            center = matvec(q, c0)
            Ks.append([list(row) for row in k0])
            Rs.append(r)
            ts.append([-v for v in matvec(r, center)])
    pts: List[Vector] = []
    tries = 0
    while len(pts) < n:
        tries += 1
        if tries > 1000 * max(n, 1):
            raise ValueError("random_scene: cannot place the points")
        x = [rng.uniform(-radius, radius) for _ in range(3)]
        if planar:
            x[2] = 0.0
        ok = True
        for k, r, t in zip(Ks, Rs, ts):
            xc = [a + b for a, b in zip(matvec(r, x), t)]
            if xc[2] < min_depth:
                ok = False
                break
            if size is not None:
                u = (k[0][0] * xc[0] + k[0][1] * xc[1]) / xc[2] + k[0][2]
                v = k[1][1] * xc[1] / xc[2] + k[1][2]
                if not (0.0 <= u <= size[0] and 0.0 <= v <= size[1]):
                    ok = False
                    break
        if ok:
            pts.append(x)
    if first_identity and Rs:
        r0, t0 = Rs[0], ts[0]
        pts = [[a + b for a, b in zip(matvec(r0, x), t0)] for x in pts]
        r0t = transpose(r0)
        newR, newt = [], []
        for r, t in zip(Rs, ts):
            rr = mul(r, r0t)
            newR.append(rr)
            newt.append([a - b for a, b in zip(t, matvec(rr, t0))])
        Rs, ts = newR, newt
        Rs[0] = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
        ts[0] = [0.0, 0.0, 0.0]
    Ps = [camera_matrix(k, r, t) for k, r, t in zip(Ks, Rs, ts)]
    xs = [[project(p, x) for x in pts] for p in Ps]
    return {"K": Ks, "R": Rs, "t": ts, "P": Ps, "X": pts, "x": xs}


def add_noise(rng: random.Random, pts: Sequence[Sequence[float]], sigma: float) -> List[Vector]:
    """A copy of the points with independent Gaussian noise of standard
    deviation sigma added to every coordinate."""
    return [[float(v) + rng.gauss(0.0, sigma) for v in p] for p in pts]


def self_test() -> None:
    """Check random_scene and quat_to_R. Raises AssertionError."""
    rng = random.Random(11)
    scene = random_scene(rng, n=30, n_cams=4)
    for r, t in zip(scene["R"], scene["t"]):
        for x in scene["X"]:
            assert matvec(r, x)[2] + t[2] > 0.0
    for _ in range(5):
        q = [rng.gauss(0.0, 1.0) for _ in range(4)]
        r = quat_to_R(q)
        rtr = mul(transpose(r), r)
        assert all(abs(rtr[i][j] - (1.0 if i == j else 0.0)) <= 1e-12
                   for i in range(3) for j in range(3))
        assert abs(det(r) - 1.0) <= 1e-12


if __name__ == "__main__":
    self_test()
cvla.py 494 lines
# 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()
zhang_calibration_method.py 321 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zhang-calibration-method/. The authors are listed in prov/WSAQZX.jsonl.
"""Zhang's calibration method from views of a plane (Zhang 2000).

The model points lie on the plane Z = 0 of the world frame and are given
as (X, Y). For each view the pixels of the same points are given. The
camera follows the conventions of the area: X_c = R X_w + t, K =
[[f_x, s, c_x], [0, f_y, c_y], [0, 0, 1]], and the radial distortion acts
on the normalized coordinates (x, y) = (X_c / Z_c, Y_c / Z_c):
x_d = x (1 + k1 r^2 + k2 r^4) with r^2 = x^2 + y^2, then (u, v) = K (x_d, y_d, 1).
"""

from __future__ import annotations

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

from cvla import cross, inv, matvec, mul, norm, nullvec, solve, svd, transpose
from cvgeom import axis_angle_to_R, make_K

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


# ------------------------------------------------- homography of one view

def _normalizer(pts: Sequence[Sequence[float]]) -> Matrix:
    """Similarity that moves the centroid to 0 and the mean distance to
    sqrt(2) (the conditioning step of the DLT)."""
    n = len(pts)
    cx = sum(p[0] for p in pts) / n
    cy = sum(p[1] for p in pts) / n
    d = sum(math.hypot(p[0] - cx, p[1] - cy) for p in pts) / n
    if d == 0.0:
        raise ValueError("all points coincide")
    s = math.sqrt(2.0) / d
    return [[s, 0.0, -s * cx], [0.0, s, -s * cy], [0.0, 0.0, 1.0]]


def homography_dlt(src: Sequence[Sequence[float]], dst: Sequence[Sequence[float]]) -> Matrix:
    """The homography H with dst ~ H src, from n >= 4 point pairs, by the
    normalized DLT. H is scaled to Frobenius norm 1."""
    if len(src) < 4 or len(src) != len(dst):
        raise ValueError("need at least 4 point pairs")
    T1, T2 = _normalizer(src), _normalizer(dst)
    a = []
    for p, q in zip(src, dst):
        x = matvec(T1, [p[0], p[1], 1.0])
        u, v, w = matvec(T2, [q[0], q[1], 1.0])
        a.append([0.0, 0.0, 0.0] + [-w * c for c in x] + [v * c for c in x])
        a.append([w * c for c in x] + [0.0, 0.0, 0.0] + [-u * c for c in x])
    h = nullvec(a)
    H = mul(mul(inv(T2), [h[0:3], h[3:6], h[6:9]]), T1)
    s = norm(H)
    return [[v / s for v in row] for row in H]


# ------------------------------------------------- closed-form intrinsics

def v_ij(H: Sequence[Sequence[float]], i: int, j: int) -> Vector:
    """The vector v_ij of Zhang (2000) with h_i^T B h_j = v_ij^T b, for the
    columns i and j of H (0-based) and b = (B11, B12, B22, B13, B23, B33)."""
    hi = [H[0][i], H[1][i], H[2][i]]
    hj = [H[0][j], H[1][j], H[2][j]]
    return [hi[0] * hj[0],
            hi[0] * hj[1] + hi[1] * hj[0],
            hi[1] * hj[1],
            hi[2] * hj[0] + hi[0] * hj[2],
            hi[2] * hj[1] + hi[1] * hj[2],
            hi[2] * hj[2]]


def constraint_matrix(Hs: Sequence[Sequence[Sequence[float]]], zero_skew: bool = False) -> Matrix:
    """The matrix V with two rows per view, and the row (0, 1, 0, 0, 0, 0)
    (that is B12 = 0) when the skew is known to be zero."""
    V = []
    for H in Hs:
        V.append(v_ij(H, 0, 1))  # @line L2
        V.append([a - b for a, b in zip(v_ij(H, 0, 0), v_ij(H, 1, 1))])  # @line L2
    if zero_skew:
        V.append([0.0, 1.0, 0.0, 0.0, 0.0, 0.0])  # @line L3
    return V


def intrinsics_from_b(b: Sequence[float]) -> Matrix:
    """K from b = (B11, B12, B22, B13, B23, B33), B = lambda K^-T K^-1, by
    the closed form of Zhang (2000), Appendix B. The sign of b does not
    matter. Raises ValueError if B is not definite."""
    B11, B12, B22, B13, B23, B33 = b
    den = B11 * B22 - B12 * B12
    if B11 == 0.0 or den <= 0.0:
        raise ValueError("B is not definite")
    v0 = (B12 * B13 - B11 * B23) / den
    lam = B33 - (B13 * B13 + v0 * (B12 * B13 - B11 * B23)) / B11
    if lam / B11 <= 0.0:
        raise ValueError("B is not definite")
    alpha = math.sqrt(lam / B11)
    beta = math.sqrt(lam * B11 / den)
    gamma = -B12 * alpha * alpha * beta / lam
    u0 = gamma * v0 / beta - B13 * alpha * alpha / lam
    return make_K(alpha, beta, u0, v0, gamma)


def intrinsics_from_homographies(Hs: Sequence[Sequence[Sequence[float]]],
                                 zero_skew: bool = False) -> Matrix:
    """K from the homographies of N views: 3 views in general, 2 if the
    skew is zero."""
    V = constraint_matrix(Hs, zero_skew)
    if len(V) < 5:
        raise ValueError("need 3 views, or 2 views with zero skew")
    return intrinsics_from_b(nullvec(V))  # @line L4


# ------------------------------------------------------------ extrinsics

def nearest_rotation(Q: Sequence[Sequence[float]]) -> Matrix:
    """The rotation closest to Q in the Frobenius norm: U V^T from the SVD
    Q = U S V^T, with the sign fix that keeps det = +1."""
    U, _, V = svd(Q)
    R = mul(U, transpose(V))
    if (R[0][0] * (R[1][1] * R[2][2] - R[1][2] * R[2][1])
            - R[0][1] * (R[1][0] * R[2][2] - R[1][2] * R[2][0])
            + R[0][2] * (R[1][0] * R[2][1] - R[1][1] * R[2][0])) < 0.0:
        U = [row[:2] + [-row[2]] for row in U]
        R = mul(U, transpose(V))
    return R


def extrinsics_from_homography(K: Sequence[Sequence[float]],
                               H: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector]:
    """(R, t) of one view from H ~ K [r1 r2 t]. The sign of the scale is
    chosen so that t_z > 0 (the plane is in front of the camera)."""
    Ki = inv(K)
    a1 = matvec(Ki, [H[0][0], H[1][0], H[2][0]])
    a2 = matvec(Ki, [H[0][1], H[1][1], H[2][1]])
    a3 = matvec(Ki, [H[0][2], H[1][2], H[2][2]])
    lam = 1.0 / norm(a1)
    if a3[2] < 0.0:
        lam = -lam
    r1 = [lam * v for v in a1]
    r2 = [lam * v for v in a2]
    r3 = cross(r1, r2)
    t = [lam * v for v in a3]
    Q = [[r1[k], r2[k], r3[k]] for k in range(3)]
    return nearest_rotation(Q), t


# ------------------------------------------- projection with distortion

def rotation_to_vector(R: Sequence[Sequence[float]]) -> Vector:
    """The rotation vector w = theta a of R (the inverse of axis_angle_to_R
    with theta = None), for angles in [0, pi]."""
    c = (R[0][0] + R[1][1] + R[2][2] - 1.0) / 2.0
    w = [R[2][1] - R[1][2], R[0][2] - R[2][0], R[1][0] - R[0][1]]
    s = norm(w) / 2.0
    theta = math.atan2(s, c)
    if theta < 1e-7:
        return [v / 2.0 for v in w]
    if c < 0.0 and s < 1e-4:
        k = max(range(3), key=lambda i: R[i][i])
        a = [(R[k][j] + R[j][k]) / 2.0 for j in range(3)]
        a[k] = R[k][k] - c
        na = norm(a)
        a = [v / na for v in a]
        if sum(x * y for x, y in zip(a, w)) < 0.0:
            a = [-v for v in a]
        return [theta * v for v in a]
    f = theta / (2.0 * s)
    return [f * v for v in w]


def project_plane_points(K: Sequence[Sequence[float]], k1: float, k2: float,
                         R: Sequence[Sequence[float]], t: Sequence[float],
                         pts: Sequence[Sequence[float]]) -> List[Vector]:
    """Pixels of the model points (X, Y, 0): project, distort, apply K."""
    out = []
    for X, Y in ((p[0], p[1]) for p in pts):
        xc = [R[i][0] * X + R[i][1] * Y + t[i] for i in range(3)]
        x, y = xc[0] / xc[2], xc[1] / xc[2]
        r2 = x * x + y * y
        f = 1.0 + k1 * r2 + k2 * r2 * r2
        xd, yd = x * f, y * f
        out.append([K[0][0] * xd + K[0][1] * yd + K[0][2], K[1][1] * yd + K[1][2]])
    return out


def estimate_distortion(K, poses, pts, obs) -> Tuple[float, float]:
    """Linear least squares for (k1, k2) with K and the poses fixed (Zhang
    2000, section 3.3). For an ideal pixel (u, v) and its normalized point
    (x, y), the model gives u_d - u = (u - c_x)(k1 r^2 + k2 r^4), and the same
    for v. This holds with a nonzero skew too, because u - c_x = f_x x + s y."""
    ata = [[0.0, 0.0], [0.0, 0.0]]
    atb = [0.0, 0.0]
    for (R, t), view in zip(poses, obs):
        ideal = project_plane_points(K, 0.0, 0.0, R, t, pts)
        for p, (u, v), (ud, vd) in zip(pts, ideal, view):
            xc = [R[i][0] * p[0] + R[i][1] * p[1] + t[i] for i in range(3)]
            r2 = (xc[0] * xc[0] + xc[1] * xc[1]) / (xc[2] * xc[2])
            for row, rhs in (([(u - K[0][2]) * r2, (u - K[0][2]) * r2 * r2], ud - u),
                             ([(v - K[1][2]) * r2, (v - K[1][2]) * r2 * r2], vd - v)):
                for a in range(2):
                    atb[a] += row[a] * rhs
                    for b in range(2):
                        ata[a][b] += row[a] * row[b]
    k = solve(ata, atb)
    return k[0], k[1]


# ------------------------------------------------ Levenberg-Marquardt

def _unpack(p: Sequence[float], n_views: int):
    K = make_K(p[0], p[1], p[3], p[4], p[2])
    poses = []
    for i in range(n_views):
        q = p[7 + 6 * i: 13 + 6 * i]
        poses.append((axis_angle_to_R(q[0:3]), list(q[3:6])))
    return K, p[5], p[6], poses


def _view_residuals(p: Sequence[float], i: int, pts, view) -> Vector:
    K = make_K(p[0], p[1], p[3], p[4], p[2])
    q = p[7 + 6 * i: 13 + 6 * i]
    proj = project_plane_points(K, p[5], p[6], axis_angle_to_R(q[0:3]), q[3:6], pts)
    out = []
    for (u, v), (uo, vo) in zip(proj, view):
        out.append(u - uo)
        out.append(v - vo)
    return out


def refine(p0: Sequence[float], pts, obs, zero_skew: bool = False,
           distortion: bool = True, max_iter: int = 100) -> Tuple[Vector, List[float]]:
    """Levenberg-Marquardt on the sum of squared reprojection errors. The
    parameters are (f_x, f_y, s, c_x, c_y, k1, k2) and, per view, a rotation
    vector and t. The Jacobian is by forward differences, view by view.
    Returns the parameters and the cost after each accepted step (the first
    entry is the start cost); the cost never increases."""
    p = [float(v) for v in p0]
    nv = len(obs)
    fixed = ({2} if zero_skew else set()) | (set() if distortion else {5, 6})
    free = [j for j in range(len(p)) if j not in fixed]
    m = sum(2 * len(view) for view in obs)
    offs = [0]
    for view in obs:
        offs.append(offs[-1] + 2 * len(view))

    def residuals(q):
        r = []
        for i in range(nv):
            r.extend(_view_residuals(q, i, pts, obs[i]))
        return r

    r = residuals(p)
    cost = sum(v * v for v in r)
    history = [cost]
    mu = 1e-3
    for _ in range(max_iter):
        cols = []
        for j in free:
            h = 1e-7 * max(1.0, abs(p[j]))
            q = list(p)
            q[j] += h
            col = [0.0] * m
            views = range(nv) if j < 7 else [(j - 7) // 6]
            for i in views:
                ri = _view_residuals(q, i, pts, obs[i])
                for k, val in enumerate(ri):
                    col[offs[i] + k] = (val - r[offs[i] + k]) / h
            cols.append(col)
        nf = len(free)
        A = [[sum(a * b for a, b in zip(cols[x], cols[y])) for y in range(nf)] for x in range(nf)]
        g = [sum(a * b for a, b in zip(cols[x], r)) for x in range(nf)]
        accepted = False
        while mu < 1e12:
            Ad = [[A[x][y] + (mu * A[x][x] if x == y else 0.0) for y in range(nf)] for x in range(nf)]
            try:
                delta = solve(Ad, [-v for v in g])
            except ValueError:
                mu *= 10.0
                continue
            q = list(p)
            for x, j in enumerate(free):
                q[j] += delta[x]
            rnew = residuals(q)
            cq = sum(v * v for v in rnew)
            if cq < cost:
                accepted = True
                drop = cost - cq
                p, r, cost = q, rnew, cq
                history.append(cost)
                mu = max(mu / 10.0, 1e-15)
                break
            mu *= 10.0
        if not accepted or drop <= 1e-12 * cost or cost <= 1e-24:
            break
    return p, history


# ------------------------------------------------------------- driver

def calibrate(pts: Sequence[Sequence[float]], obs: Sequence[Sequence[Sequence[float]]],
              zero_skew: bool = False, distortion: bool = True,
              refine_all: bool = True) -> Dict[str, object]:
    """Zhang's method. pts are the model points (X, Y) on the plane Z = 0;
    obs[i][j] is the pixel of pts[j] in view i. Returns a dict with K, k1,
    k2, R (list), t (list), the closed-form K0, and the LM cost history."""
    Hs = [homography_dlt(pts, view) for view in obs]  # @line L1
    K0 = intrinsics_from_homographies(Hs, zero_skew)  # @line L5
    poses = [extrinsics_from_homography(K0, H) for H in Hs]  # @line L6
    k1 = k2 = 0.0
    if distortion:
        k1, k2 = estimate_distortion(K0, poses, pts, obs)  # @line L7
    p = [K0[0][0], K0[1][1], 0.0 if zero_skew else K0[0][1], K0[0][2], K0[1][2], k1, k2]
    for R, t in poses:
        p.extend(rotation_to_vector(R) + list(t))
    history: List[float] = []
    if refine_all:
        p, history = refine(p, pts, obs, zero_skew, distortion)  # @line L8
    K, k1, k2, poses = _unpack(p, len(obs))
    return {"K": K, "k1": k1, "k2": k2, "R": [P[0] for P in poses],  # @line L9
            "t": [P[1] for P in poses], "K0": K0, "history": history}
test_zhang_calibration_method.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zhang-calibration-method/. The authors are listed in prov/WSAQZX.jsonl.
"""Tests of Zhang's calibration method on synthetic views of a planar grid."""

import math
import random

from cvgeom import add_noise, axis_angle_to_R, make_K, rot_x, rot_y, rot_z
from cvla import cholesky, det, eye, inv, matvec, mul, norm, nullvec, sub, svd, transpose
from zhang_calibration_method import (calibrate, constraint_matrix, estimate_distortion,
                                      extrinsics_from_homography, homography_dlt,
                                      intrinsics_from_b, intrinsics_from_homographies,
                                      project_plane_points, rotation_to_vector)

GRID = [[float(X), float(Y)] for Y in range(5) for X in range(6)]
CENTER = [2.5, 2.0, 0.0]
K_SKEW = make_K(800, 780, 320, 240, 1.5)
K_ZERO = make_K(800, 780, 320, 240)
TILTS = [(0.35, 0.1, 0.0), (-0.1, 0.4, 0.3), (0.2, -0.35, -0.2), (-0.3, -0.2, 0.5),
         (0.15, 0.3, -0.4)]


def pose(a, b, c, depth=12.0):
    R = mul(mul(rot_x(a), rot_y(b)), rot_z(c))
    Rc = matvec(R, CENTER)
    return R, [0.0 - Rc[0], 0.0 - Rc[1], depth - Rc[2]]


def views(K, n, k1=0.0, k2=0.0):
    poses = [pose(*TILTS[i]) for i in range(n)]
    obs = [project_plane_points(K, k1, k2, R, t, GRID) for R, t in poses]
    return poses, obs


def rel(a, b):
    return norm(sub(a, b)) / norm(b)


def is_rotation(R, tol):
    return norm(sub(mul(transpose(R), R), eye(3))) <= tol and abs(det(R) - 1.0) <= tol


def test_homography_maps_the_grid():
    poses, obs = views(K_SKEW, 1)
    H = homography_dlt(GRID, obs[0])
    for p, q in zip(GRID, obs[0]):
        w = matvec(H, [p[0], p[1], 1.0])
        assert math.hypot(w[0] / w[2] - q[0], w[1] / w[2] - q[1]) <= 1e-8


def test_closed_form_exact_with_skew():
    for n in (3, 4, 5):
        poses, obs = views(K_SKEW, n)
        Hs = [homography_dlt(GRID, view) for view in obs]
        K = intrinsics_from_homographies(Hs)
        assert rel(K, K_SKEW) <= 1e-8
        for (R0, t0), H in zip(poses, Hs):
            R, t = extrinsics_from_homography(K, H)
            assert is_rotation(R, 1e-12)
            assert norm(sub(R, R0)) <= 1e-8
            assert rel(t, t0) <= 1e-8


def test_zero_skew_needs_two_views_only():
    poses, obs = views(K_ZERO, 2)
    Hs = [homography_dlt(GRID, view) for view in obs]
    assert rel(intrinsics_from_homographies(Hs, zero_skew=True), K_ZERO) <= 1e-8


def test_too_few_views_raise():
    _, obs = views(K_SKEW, 2)
    Hs = [homography_dlt(GRID, view) for view in obs]
    try:
        intrinsics_from_homographies(Hs)
    except ValueError:
        return
    raise AssertionError("expected ValueError")


def test_b_against_cholesky():
    # B = lambda K^-T K^-1 and K^-T is lower triangular, so the Cholesky
    # factor L of B (after its sign is made positive) is a multiple of K^-T.
    _, obs = views(K_SKEW, 4)
    b = nullvec(constraint_matrix([homography_dlt(GRID, view) for view in obs]))
    if b[0] < 0.0:
        b = [-v for v in b]
    B = [[b[0], b[1], b[3]], [b[1], b[2], b[4]], [b[3], b[4], b[5]]]
    K = inv(transpose(cholesky(B)))
    K = [[v / K[2][2] for v in row] for row in K]
    assert rel(K, intrinsics_from_b(b)) <= 1e-8
    assert rel(intrinsics_from_b([-v for v in b]), K) <= 1e-8


def test_parallel_planes_are_degenerate():
    # Views that differ only by a translation have the same h1 and h2 up to
    # scale, so they add no new constraint: V keeps rank 2.
    obs = []
    for t in ([-2.5, -2.0, 10.0], [-1.0, -3.0, 14.0], [-3.5, 0.5, 12.0]):
        obs.append(project_plane_points(K_SKEW, 0.0, 0.0, eye(3), t, GRID))
    V = constraint_matrix([homography_dlt(GRID, view) for view in obs])
    _, s, _ = svd(V)
    assert s[1] / s[0] > 1e-6
    assert s[2] / s[0] <= 1e-10


def test_distortion_estimate_is_exact_with_true_poses():
    poses, obs = views(K_SKEW, 3, -0.25, 0.08)
    k1, k2 = estimate_distortion(K_SKEW, poses, GRID, obs)
    assert abs(k1 + 0.25) <= 1e-10 and abs(k2 - 0.08) <= 1e-10


def test_full_pipeline_exact_with_distortion():
    poses, obs = views(K_SKEW, 4, -0.25, 0.08)
    res = calibrate(GRID, obs)
    assert rel(res["K"], K_SKEW) <= 1e-6
    assert abs(res["k1"] + 0.25) <= 1e-6 and abs(res["k2"] - 0.08) <= 1e-6
    for (R0, t0), R, t in zip(poses, res["R"], res["t"]):
        assert is_rotation(R, 1e-12)
        assert norm(sub(R, R0)) <= 1e-6
        assert rel(t, t0) <= 1e-6
    # The closed form alone is biased by the distortion.
    assert rel(res["K0"], K_SKEW) > 1e-4


def test_lm_cost_never_increases():
    rng = random.Random(3)
    _, obs = views(K_SKEW, 4, -0.25, 0.08)
    obs = [add_noise(rng, view, 0.3) for view in obs]
    hist = calibrate(GRID, obs)["history"]
    assert len(hist) >= 3
    assert all(b <= a for a, b in zip(hist, hist[1:]))
    assert hist[-1] < hist[0]


def test_noise_sigma_02_five_views():
    # sigma = 0.2 pixel on 5 views of 30 points, zero skew, with distortion.
    rng = random.Random(7)
    _, obs = views(K_ZERO, 5, -0.25, 0.08)
    obs = [add_noise(rng, view, 0.2) for view in obs]
    res = calibrate(GRID, obs, zero_skew=True)
    K = res["K"]
    assert K[0][1] == 0.0
    assert abs(K[0][0] - 800.0) / 800.0 <= 0.01
    assert abs(K[1][1] - 780.0) / 780.0 <= 0.01
    assert abs(K[0][2] - 320.0) <= 5.0 and abs(K[1][2] - 240.0) <= 5.0
    rms = math.sqrt(res["history"][-1] / (2 * 5 * len(GRID)))
    assert 0.1 <= rms <= 0.2


def test_rotation_vector_round_trip():
    rng = random.Random(5)
    angles = [0.0, 1e-9, 0.5, 2.0, math.pi - 2e-4, math.pi - 1e-4, math.pi - 1e-6, math.pi]
    for theta in angles:
        axis = [rng.gauss(0.0, 1.0) for _ in range(3)]
        R = axis_angle_to_R(axis, theta)
        w = rotation_to_vector(R)
        assert norm(sub(axis_angle_to_R(w), R)) <= 1e-9

History

Zhengyou Zhang described the method in a Microsoft Research technical report in 1998 and published it in IEEE Transactions on Pattern Analysis and Machine Intelligence in 2000. The method replaced the 3D targets of earlier photogrammetric methods with a pattern that anyone can print, and the closed form start removed the need for a guess. The calibration functions of OpenCV and the MATLAB camera calibration toolbox of Jean-Yves Bouguet follow its scheme of a closed form start and a full nonlinear fit with distortion.

References

  1. Zhengyou Zhang, A flexible new technique for camera calibration, IEEE Transactions on Pattern Analysis and Machine Intelligence 22(11), 2000, 1330-1334, the basic constraints on the homography, the closed form solution for B and K, the maximum likelihood refinement, and the treatment of radial distortion
  2. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 8.5, Camera calibration and the image of the absolute conic (calibration from the images of the circular points of planes); Section 4.4 on data normalization for the homography DLT
  3. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 11, Structure from motion and SLAM (the part on geometric intrinsic calibration with planar patterns)

Where this leads

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