Algorithm Search⌘K

Algorithmadvanced

Calibration from vanishing points

Also called orthogonal vanishing points calibration.

Get the focal length, the principal point and the rotation from the vanishing points of three orthogonal directions: the principal point is the orthocenter of their triangle.

Time
Θ(1) worst · average · best
Space
Θ(1) extra
Where
k = the number of polar iterations at line L9 (at most 60)
Properties
deterministicexactofflineiterative
Origin
Bruno Caprile, Vincent Torre, 1990

Calibration from vanishing points finds the focal length ff, the principal point cc and the rotation RR of a camera from a single image that shows three mutually orthogonal sets of parallel lines, such as the edges of a building or a box. Each set of lines meets at a vanishing point vi∼Kriv_i \sim K r_i, where rir_i is the direction of the lines in the camera frame. If the camera has zero skew and square pixels, the principal point is the orthocenter of the triangle v1v2v3v_1 v_2 v_3, and f2=−(v1−c)⋅(v2−c)f^2 = -(v_1 - c) \cdot (v_2 - c) (Caprile and Torre 1990, HZ Section 8.8). The method needs no calibration target and has a closed form. It is less accurate than Zhang's method, which uses many points on several views of a plane, and unlike Tsai's method it needs no known 3D coordinates at all. The camera calibration page states the problem; the vanishing point detection page covers how to find the three points.

In plain words

Stand in front of a building and take a photo. The horizontal edges along the front wall seem to meet at one point far to the side. The edges along the side wall meet at another point, and the vertical edges meet at a third point far above or below. These three meeting points form a triangle.

The camera's center of view sits where the three heights of this triangle cross. The focal length follows from how far the points are from that center. Each meeting point also tells the direction of one set of edges, so you also get how the camera is turned. All this comes from one photo and a few lines, with no special pattern in the scene. The method assumes that the pixels are square and that the camera has no skew, which holds for nearly all modern cameras.

The problem

Input. Three finite pixels v1,v2,v3v_1, v_2, v_3, the vanishing points of three mutually orthogonal scene directions. Coordinates follow the area: uu to the right, vv down, and the center of a pixel at integer coordinates.

Model. K=(f0cx0fcy001)K = \begin{pmatrix} f & 0 & c_x \\ 0 & f & c_y \\ 0 & 0 & 1 \end{pmatrix} with zero skew and square pixels. The world axes are the three directions, and R=[r1  r2  r3]R = [r_1 \; r_2 \; r_3] holds them in the camera frame, so vi∼KRei=Kriv_i \sim K R e_i = K r_i. Lens distortion must be removed first, because lens distortion acts on normalized coordinates (project, distort, then apply KK) and bends the lines that define the viv_i.

Output. ff, cc and a rotation RR whose columns are ±ri\pm r_i. The sign of each column is not fixed by the image, because the directions rir_i and −ri-r_i have the same vanishing point. The translation is not part of the output: vanishing points are images of points at infinity, so they do not depend on where the camera is.

The key fact. K−1(vi,1)TK^{-1} (v_i, 1)^{\mathsf T} is parallel to rir_i, and with the form of KK above it equals ((vi−c)/f,1)((v_i - c) / f, 1). So ri⋅rj=0r_i \cdot r_j = 0 becomes

(vi−c)⋅(vj−c)=−f2(i≠j).(v_i - c) \cdot (v_j - c) = -f^2 \qquad (i \ne j).

In the language of the image of the absolute conic ω=(KKT)−1\omega = (K K^{\mathsf T})^{-1}, this is viTωvj=0v_i^{\mathsf T} \omega v_j = 0. Subtract the equation for the pair (1,3)(1, 3) from the one for (2,3)(2, 3): (v1−v2)⋅(v3−c)=0(v_1 - v_2) \cdot (v_3 - c) = 0, so cc lies on the altitude of the triangle from v3v_3. In the same way, cc lies on the other two altitudes, so cc is the orthocenter.

The algorithm

  1. VP-CALIBRATE(v_1, v_2, v_3)
  2. 1a_1 <- v_1 - v_2; b_1 <- a_1 . v_3
  3. 2a_2 <- v_2 - v_3; b_2 <- a_2 . v_1
  4. 3D <- det(a_1, a_2); if D = 0 then fail: the points are collinear
  5. 4c <- the solution p of a_1 . p = b_1 and a_2 . p = b_2, by Cramer's rule
  6. 5q <- -(v_1 - c) . (v_2 - c); if q <= 0 then fail: the triangle is not acute
  7. 6f <- sqrt(q); K <- [[f, 0, c_x], [0, f, c_y], [0, 0, 1]]
  8. 7for i <- 1 to 3: r_i <- K^-1 (v_i, 1) / ||K^-1 (v_i, 1)||
  9. 8R <- [r_1 r_2 r_3]; if det R < 0 then r_3 <- -r_3
  10. 9R <- nearest rotation to R, by the iteration X <- (X + X^-T) / 2
  11. 10return K, R

Lines L1 to L4 intersect two altitudes. The equation a1⋅p=b1a_1 \cdot p = b_1 says (v1−v2)⋅(p−v3)=0(v_1 - v_2) \cdot (p - v_3) = 0, the altitude from v3v_3, and a2⋅p=b2a_2 \cdot p = b_2 is the altitude from v1v_1. With a1=(a1x,a1y)a_1 = (a_{1x}, a_{1y}) and a2=(a2x,a2y)a_2 = (a_{2x}, a_{2y}),

D=a1xa2y−a1ya2x,cx=b1a2y−a1yb2D,cy=a1xb2−a2xb1D.D = a_{1x} a_{2y} - a_{1y} a_{2x}, \qquad c_x = \frac{b_1 a_{2y} - a_{1y} b_2}{D}, \qquad c_y = \frac{a_{1x} b_2 - a_{2x} b_1}{D}.

In floating point, line L3 rejects ∣D∣|D| below a small multiple of ∥a1∥∥a2∥\lVert a_1 \rVert \lVert a_2 \rVert. Line L5 uses the pair (1,2)(1, 2); at the orthocenter all three pairs give the same value, as the proof shows. Line L7 picks for each column the sign with a positive ZZ component, because K−1(vi,1)K^{-1} (v_i, 1) has last entry 1. Line L8 makes the frame right handed. Line L9 is the Newton iteration for the orthogonal polar factor (Higham 1986); it does not change an exact rotation, and with noisy input it returns the nearest rotation in the Frobenius norm.

The two point variant. If the principal point is known, for example as the image center, two vanishing points of orthogonal directions suffice: f=−(v1−c)⋅(v2−c)f = \sqrt{-(v_1 - c) \cdot (v_2 - c)}.

Example

Let the true camera have f=800f = 800 and c=(320,240)c = (320, 240). The three scene directions have, in the camera frame, the directions (2,0,1)(2, 0, 1), (−0.5,1,1)(-0.5, 1, 1) and (−0.5,−1.25,1)(-0.5, -1.25, 1), which are pairwise orthogonal. Their vanishing points are vi=(800xi/zi+320,800yi/zi+240)v_i = (800 x_i / z_i + 320, 800 y_i / z_i + 240):

v1=(1920,240),v2=(−80,1040),v3=(−80,−760).v_1 = (1920, 240), \qquad v_2 = (-80, 1040), \qquad v_3 = (-80, -760).
line values
L1 a1=(2000,−800)a_1 = (2000, -800), b1=2000⋅(−80)+(−800)⋅(−760)=448000b_1 = 2000 \cdot (-80) + (-800) \cdot (-760) = 448000
L2 a2=(0,1800)a_2 = (0, 1800), b2=0⋅1920+1800⋅240=432000b_2 = 0 \cdot 1920 + 1800 \cdot 240 = 432000
L3 D=2000⋅1800−(−800)⋅0=3600000D = 2000 \cdot 1800 - (-800) \cdot 0 = 3600000
L4 cx=(448000⋅1800+800⋅432000)/3600000=320c_x = (448000 \cdot 1800 + 800 \cdot 432000) / 3600000 = 320, cy=2000⋅432000/3600000=240c_y = 2000 \cdot 432000 / 3600000 = 240
L5 q=−(1600,0)⋅(−400,800)=640000q = -(1600, 0) \cdot (-400, 800) = 640000
L6 f=800f = 800
L7 r1=(2,0,1)/5≈(0.8944,0,0.4472)r_1 = (2, 0, 1) / \sqrt 5 \approx (0.8944, 0, 0.4472), r2=(−1/3,2/3,2/3)r_2 = (-1/3, 2/3, 2/3), r3≈(−0.2981,−0.7454,0.5963)r_3 \approx (-0.2981, -0.7454, 0.5963)
L8 r1×r2=r3r_1 \times r_2 = r_3, so det⁡R=1\det R = 1 and no column changes sign
L9 RR is already a rotation and does not change

The side v2v3v_2 v_3 is vertical, so the altitude from v1v_1 is the row v=240v = 240, and indeed cy=240c_y = 240. The other two pairs give the same value: (v1−c)⋅(v3−c)=(1600,0)⋅(−400,−1000)=−640000(v_1 - c) \cdot (v_3 - c) = (1600, 0) \cdot (-400, -1000) = -640000 and (v2−c)⋅(v3−c)=(−400,800)⋅(−400,−1000)=160000−800000=−640000(v_2 - c) \cdot (v_3 - c) = (-400, 800) \cdot (-400, -1000) = 160000 - 800000 = -640000. The triangle is acute; for example, the angle at v1v_1 has (v2−v1)⋅(v3−v1)=3200000=f2+∥v1−c∥2(v_2 - v_1) \cdot (v_3 - v_1) = 3200000 = f^2 + \lVert v_1 - c \rVert^2.

As a check through the IAC, write ω∝(w10w20w1w3w2w3w4)\omega \propto \begin{pmatrix} w_1 & 0 & w_2 \\ 0 & w_1 & w_3 \\ w_2 & w_3 & w_4 \end{pmatrix}. Each pair gives w1(xixj+yiyj)+w2(xi+xj)+w3(yi+yj)+w4=0w_1 (x_i x_j + y_i y_j) + w_2 (x_i + x_j) + w_3 (y_i + y_j) + w_4 = 0, here the rows (96000,1840,1280,1)(96000, 1840, 1280, 1), (−336000,1840,−520,1)(-336000, 1840, -520, 1) and (−784000,−160,280,1)(-784000, -160, 280, 1). The null vector is (1,−320,−240,800000)(1, -320, -240, 800000), which gives c=(320,240)c = (320, 240) and f2=800000−3202−2402=640000f^2 = 800000 - 320^2 - 240^2 = 640000 again. A script with exact fractions confirmed every number in this section.

Correctness

The full proof is in proofs/correctness.md. In outline: orthogonality gives (vi−c)⋅(vj−c)=−f2(v_i - c) \cdot (v_j - c) = -f^2 for each pair, and the difference of two of these equations is an altitude equation, so the true cc solves the system of line L4. The three vectors (vi,1)∼Kri(v_i, 1) \sim K r_i are independent, so the viv_i are not collinear, D≠0D \ne 0 and the solution is unique. Then line L5 gives q=f2>0q = f^2 > 0, and line L7 gives ±ri\pm r_i. Two more facts come from the same identity. The triangle of a real camera is always acute, because the angle at viv_i has (vj−vi)⋅(vk−vi)=f2+∥vi−c∥2>0(v_j - v_i) \cdot (v_k - v_i) = f^2 + \lVert v_i - c \rVert^2 > 0. And every input that the algorithm accepts is the exact set of vanishing points of the camera it returns; so a rejection at line L3 or L5 proves that no camera with zero skew and square pixels fits the input.

Proof: Three exact vanishing points of orthogonal directions give K and R, and a returned answer always fits the inputfull

We use the notation of the page. The camera has zero skew and square pixels, so K=(f0cx0fcy001)K = \begin{pmatrix} f & 0 & c_x \\ 0 & f & c_y \\ 0 & 0 & 1 \end{pmatrix} with f>0f > 0 and c=(cx,cy)c = (c_x, c_y). The rotation R=[r1  r2  r3]R = [r_1 \; r_2 \; r_3] holds the three orthogonal scene directions in the camera frame, and rizr_{iz} is the ZZ component of rir_i. The vanishing point of direction ii is vi∼Kriv_i \sim K r_i. It is a finite pixel exactly when riz≠0r_{iz} \ne 0, and then

vi−c=friz(rix,riy),K−1(vi1)=ririz.v_i - c = \frac{f}{r_{iz}} (r_{ix}, r_{iy}), \qquad K^{-1} \begin{pmatrix} v_i \\ 1 \end{pmatrix} = \frac{r_i}{r_{iz}}.

For a point pp of the image we write ai(p)=vi−pa_i(p) = v_i - p, and ai=ai(c)a_i = a_i(c).

Claim. (a) Let v1,v2,v3v_1, v_2, v_3 be the exact vanishing points of a camera as above, all finite. Then the points are not on one line, the triangle v1v2v3v_1 v_2 v_3 has three acute angles, and lines L1 to L10 return the true KK and a rotation whose columns are ±ri\pm r_i. (b) In exact arithmetic, for any three input points that lines L3 and L5 accept, the returned RR is a rotation and KRei∼(vi,1)K R e_i \sim (v_i, 1) for i=1,2,3i = 1, 2, 3. So every accepted input is the exact set of vanishing points of some camera with zero skew and square pixels. (c) If line L3 or line L5 rejects the input, then no camera with zero skew and square pixels has these three points as finite vanishing points of three orthogonal directions.

Step 1: the key identity

Let i≠ji \ne j. The directions are orthogonal, so ri⋅rj=0r_i \cdot r_j = 0. Divide by rizrjzr_{iz} r_{jz} and use the formula for K−1(vi,1)K^{-1} (v_i, 1):

0=ririz⋅rjrjz=aif⋅ajf+1,soai⋅aj=(vi−c)⋅(vj−c)=−f2.(1)0 = \frac{r_i}{r_{iz}} \cdot \frac{r_j}{r_{jz}} = \frac{a_i}{f} \cdot \frac{a_j}{f} + 1, \qquad\text{so}\qquad a_i \cdot a_j = (v_i - c) \cdot (v_j - c) = -f^2. \tag{1}

Step 2: the points are not collinear and the triangle is acute

The vectors (vi,1)∼Kri(v_i, 1) \sim K r_i are images of three independent vectors under the invertible KK, so they are independent. If v1,v2,v3v_1, v_2, v_3 were on one line ll, then lT(vi,1)=0l^{\mathsf T} (v_i, 1) = 0 for all three, and three independent vectors cannot all be orthogonal to one nonzero vector ll in R3\mathbb R^3. So the points are not collinear, and the vectors v1−v2v_1 - v_2 and v2−v3v_2 - v_3 are independent. The determinant DD of line L3 is not zero.

For the angle at viv_i, with {i,j,k}={1,2,3}\{i, j, k\} = \{1, 2, 3\}, (1) gives

(vj−vi)⋅(vk−vi)=(aj−ai)⋅(ak−ai)=aj⋅ak−aj⋅ai−ai⋅ak+ai⋅ai=f2+∥ai∥2>0.(v_j - v_i) \cdot (v_k - v_i) = (a_j - a_i) \cdot (a_k - a_i) = a_j \cdot a_k - a_j \cdot a_i - a_i \cdot a_k + a_i \cdot a_i = f^2 + \lVert a_i \rVert^2 > 0.

So every angle of the triangle is acute.

Step 3: lines L1 to L6 return c and f

Lines L1 and L2 set a(1)=v1−v2a^{(1)} = v_1 - v_2, b1=a(1)⋅v3b_1 = a^{(1)} \cdot v_3, a(2)=v2−v3a^{(2)} = v_2 - v_3 and b2=a(2)⋅v1b_2 = a^{(2)} \cdot v_1. Line L4 solves the 2×22 \times 2 system

a(1)⋅p=b1,a(2)⋅p=b2(2)a^{(1)} \cdot p = b_1, \qquad a^{(2)} \cdot p = b_2 \tag{2}

by Cramer's rule. The first equation says (v1−v2)⋅(p−v3)=0(v_1 - v_2) \cdot (p - v_3) = 0, so pp is on the altitude from v3v_3; the second says pp is on the altitude from v1v_1. By Step 2, D≠0D \ne 0, so (2) has exactly one solution, the orthocenter. The true cc solves (2), because by (1)

(v1−v2)⋅(v3−c)=a1⋅a3−a2⋅a3=−f2+f2=0,(v_1 - v_2) \cdot (v_3 - c) = a_1 \cdot a_3 - a_2 \cdot a_3 = -f^2 + f^2 = 0,

and in the same way (v2−v3)⋅(v1−c)=a2⋅a1−a3⋅a1=0(v_2 - v_3) \cdot (v_1 - c) = a_2 \cdot a_1 - a_3 \cdot a_1 = 0. So line L4 returns cc. Line L5 computes q=−a1⋅a2=f2>0q = -a_1 \cdot a_2 = f^2 > 0 by (1), so it does not reject, and line L6 sets the true ff and KK.

Step 4: lines L7 to L10 return a rotation with columns plus or minus r_i

Line L7 computes di=((vi−c)/f,1)=K−1(vi,1)=ri/rizd_i = ((v_i - c) / f, 1) = K^{-1} (v_i, 1) = r_i / r_{iz} and divides it by its length. As ∥ri∥=1\lVert r_i \rVert = 1, the result is σiri\sigma_i r_i with σi=sign⁡(riz)∈{1,−1}\sigma_i = \operatorname{sign}(r_{iz}) \in \{1, -1\}. Line L8 forms S=Rdiag⁡(σ1,σ2,σ3)S = R \operatorname{diag}(\sigma_1, \sigma_2, \sigma_3), with det⁡S=σ1σ2σ3\det S = \sigma_1 \sigma_2 \sigma_3. If this is −1-1, line L8 negates the third column, so the matrix becomes Rdiag⁡(σ1,σ2,σ1σ2)R \operatorname{diag}(\sigma_1, \sigma_2, \sigma_1 \sigma_2), whose determinant is +1+1. In both cases the matrix is a rotation with columns ±ri\pm r_i. Line L9 runs the iteration X←(X+X−T)/2X \leftarrow (X + X^{-\mathsf T}) / 2. For a rotation X−T=XX^{-\mathsf T} = X, so the iteration does not change it. This proves (a).

Step 5: a returned answer fits the input (part b)

Take any three input points for which lines L3 and L5 do not reject. Let p=(px,py)p = (p_x, p_y) be the solution of (2) and write ai=vi−pa_i = v_i - p. The first equation of (2) says (a1−a2)⋅a3=0(a_1 - a_2) \cdot a_3 = 0, so a1⋅a3=a2⋅a3a_1 \cdot a_3 = a_2 \cdot a_3. The second says (a2−a3)⋅a1=0(a_2 - a_3) \cdot a_1 = 0, so a1⋅a2=a1⋅a3a_1 \cdot a_2 = a_1 \cdot a_3. So all three products ai⋅aja_i \cdot a_j with i≠ji \ne j have the same value, and line L5 sets qq to minus this value, with q>0q > 0. With f=qf = \sqrt q and di=(ai/f,1)d_i = (a_i / f, 1),

di⋅dj=ai⋅ajq+1=−1+1=0(i≠j).d_i \cdot d_j = \frac{a_i \cdot a_j}{q} + 1 = -1 + 1 = 0 \qquad (i \ne j).

So the unit vectors of line L7 are orthonormal, the matrix of line L8 is a rotation after the sign fix, and line L9 keeps it (Step 4). Each column is ±di/∥di∥\pm d_i / \lVert d_i \rVert, and Kdi=(vi,1)K d_i = (v_i, 1) by the definition of did_i, so KRei∼(vi,1)K R e_i \sim (v_i, 1). With rounding, the columns are only nearly orthonormal, and line L9 replaces the matrix with its orthogonal polar factor, the nearest rotation in the Frobenius norm (the determinant is positive after line L8).

Step 6: rejections are correct (part c)

Suppose some camera with zero skew and square pixels had v1,v2,v3v_1, v_2, v_3 as finite vanishing points of three orthogonal directions. Then Step 2 shows that the points are not collinear, so line L3 does not reject. Step 3 shows that the unique solution of (2) is its principal point and that q=f2>0q = f^2 > 0 there, so line L5 does not reject either. Hence a rejection at line L3 or line L5 proves that no such camera exists. In particular, three collinear points, or a triangle with a right or an obtuse angle, are rejected. For a right or obtuse angle at viv_i, the identity of Step 2 holds at the orthocenter pp for any triangle (its proof used only that the three products ai⋅aja_i \cdot a_j are equal, which Step 5 shows), so (vj−vi)⋅(vk−vi)=q+∥vi−p∥2≤0(v_j - v_i) \cdot (v_k - v_i) = q + \lVert v_i - p \rVert^2 \le 0 forces q≤0q \le 0.

Cost

Each line does a fixed number of arithmetic operations on numbers of the real-RAM, except line L9, which runs at most a fixed number (60) of iterations of fixed cost on a 3×33 \times 3 matrix. So the method takes Θ(1)\Theta(1) time and Θ(1)\Theta(1) extra space.

Complexity

In the real-RAM model, lines L1 to L8 do a fixed number of arithmetic operations and three square roots: Θ(1)\Theta(1) time and Θ(1)\Theta(1) extra space. Line L9 runs at most a fixed number of iterations on a 3×33 \times 3 matrix, so the total stays Θ(1)\Theta(1). For an exact rotation it stops after one iteration. The real cost of calibration from vanishing points is in vanishing point detection, which is linear or worse in the number of line segments.

Properties

  • Closed form. No start value and no iteration, apart from the final projection onto rotations.
  • Order free. Any order of the three points gives the same KK; only the order and the signs of the columns of RR change. The tests check all six orders.
  • Uses one image. The method needs no motion and no known lengths. In return it needs strong assumptions: zero skew, square pixels and no distortion.
  • Invariant to scale of the scene and to translation. Vanishing points do not depend on tt or on the size of the scene, so neither does the result.
  • Exact on exact data. With exact vanishing points, the output is the true KK and RR up to the signs of the columns.

Variants and improvements

  • Known principal point. With cc assumed at the image center, two orthogonal vanishing points give ff, as above. This is the common case when one direction (often the vertical) is nearly parallel to the image plane and its vanishing point is far away.
  • More than three points or images. Each orthogonal pair gives one linear equation viTωvj=0v_i^{\mathsf T} \omega v_j = 0 on the IAC. With more pairs, from several images or several boxes, stack the equations and solve them by least squares, then get KK from ω\omega by the Cholesky decomposition. Other linear constraints fit in the same system: zero skew, square pixels, and the images of circular points from Zhang's method (HZ Section 8.8).
  • Weaker camera models. Without the square pixel assumption, ω\omega has 4 unknowns up to scale. Three orthogonal vanishing points give only 3 equations, so one more constraint is needed, for example a vanishing line together with the vanishing point of its normal direction (HZ Section 8.8).
  • Refinement. After the closed form, the line segments that support each vanishing point can be refitted jointly with KK and RR, so that the three points are exactly orthogonal. This is a small nonlinear least squares problem.
  • Manhattan world detection. Detectors that assume three orthogonal directions estimate KK (or only ff) and the three vanishing points together, so the orthogonality constraint helps the detection itself.

When to use it

Use it when you have only one image, or images from a camera you cannot calibrate in advance, of a scene with clear orthogonal structure: buildings, rooms, roads with poles, boxes. It is also a good way to get a start value for bundle adjustment or to check a calibration. Do not use it when you can print a pattern and take several photos; Zhang's method is much more accurate and also estimates distortion. Do not use it with a strong wide-angle lens unless the distortion is removed first.

Pitfalls

  • A vanishing point far away. If one direction is nearly parallel to the image plane, its vanishing point is far outside the image and its position is poorly determined. The orthocenter then moves a lot for small errors. In the limit, with one vanishing point at infinity, the principal point is only known to lie on the line through the other two, and cc must be assumed. Fall back to the two point variant.
  • Directions that are not orthogonal. The method trusts that the three directions are at right angles. Real buildings have walls that are a few degrees off, and a wrong pairing of a line to a direction moves a vanishing point.
  • Distortion. Radial distortion bends straight lines, so the line intersections do not meet at one point. Undistort the segments first, for example with the Brown-Conrady model.
  • Noise. In the tests, Gaussian noise with sigma = 1 pixel on each vanishing point of a camera with f=800f = 800 gave focal length errors up to about 3 pixels and principal point errors up to about 5 pixels over 40 random views. This is a measurement on synthetic data with nearby vanishing points, not a bound. Errors on real images are much larger, because a vanishing point from a few short segments can be off by many pixels.
  • Signs of the columns. Each column of RR is known only up to sign. Fix the signs with extra knowledge, such as the vertical pointing up, before you use RR.
  • A rejection is information. A right or obtuse triangle, or a nonpositive qq, means that the points cannot come from a camera with zero skew and square pixels. Usually one vanishing point is wrong. Do not take the absolute value of qq.

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.

vanishing_point_calibration.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vanishing-point-calibration/. The authors are listed in prov/QBYP5B.jsonl.
"""Camera calibration from three vanishing points of orthogonal directions.

The method of Caprile and Torre (1990), in the notation of the area: pixel
(u, v) with u to the right and v down, K = [[f, 0, c_x], [0, f, c_y], [0, 0, 1]]
(zero skew and square pixels), and a vanishing point v_i ~ K r_i, where r_i
is the direction of the i-th scene axis in the camera frame. Then the
principal point c is the orthocenter of the triangle v_1 v_2 v_3 and
f^2 = -(v_1 - c) . (v_2 - c).

The vanishing points are finite pixels (x, y). The functions orthocenter and
focal_squared use only +, -, * and /, so they also accept Fraction inputs
and then give exact results.
"""

from __future__ import annotations

import math
from typing import List, Sequence, Tuple

Point = Sequence[float]
Matrix = List[List[float]]


def _dot2(a: Point, b: Point):
    return a[0] * b[0] + a[1] * b[1]


def _sub2(a: Point, b: Point):
    return (a[0] - b[0], a[1] - b[1])


def orthocenter(v1: Point, v2: Point, v3: Point, rel_tol: float = 1e-12):
    """Intersection of the altitudes of the triangle v1 v2 v3.

    The altitude from v3 is the set of c with (c - v3) . (v1 - v2) = 0, and
    the altitude from v1 is the set of c with (c - v1) . (v2 - v3) = 0.
    Raises ValueError if the three points are (nearly) on one line.
    """
    a1 = _sub2(v1, v2)  # @line L1
    b1 = _dot2(a1, v3)  # @line L1
    a2 = _sub2(v2, v3)  # @line L2
    b2 = _dot2(a2, v1)  # @line L2
    D = a1[0] * a2[1] - a1[1] * a2[0]  # @line L3
    if D == 0 or abs(D) <= rel_tol * math.sqrt(float(_dot2(a1, a1) * _dot2(a2, a2))):  # @line L3
        raise ValueError("the vanishing points are collinear")  # @line L3
    cx = (b1 * a2[1] - a1[1] * b2) / D  # @line L4
    cy = (a1[0] * b2 - a2[0] * b1) / D  # @line L4
    return (cx, cy)


def focal_squared(v1: Point, v2: Point, c: Point):
    """f^2 = -(v1 - c) . (v2 - c) for two orthogonal vanishing points."""
    return -_dot2(_sub2(v1, c), _sub2(v2, c))  # @line L5


def focal_from_two(v1: Point, v2: Point, c: Point) -> float:
    """Focal length from two orthogonal vanishing points and a known
    principal point c (the two point variant)."""
    q = focal_squared(v1, v2, c)
    if q <= 0:
        raise ValueError("the points do not come from orthogonal directions")
    return math.sqrt(q)


def make_K(f: float, cx: float, cy: float) -> Matrix:
    return [[f, 0.0, cx], [0.0, f, cy], [0.0, 0.0, 1.0]]


def _det3(A: Matrix) -> float:
    return (A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1])
            - A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0])
            + A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]))


def _inv3(A: Matrix) -> Matrix:
    d = _det3(A)
    C = [[A[1][1] * A[2][2] - A[1][2] * A[2][1], A[0][2] * A[2][1] - A[0][1] * A[2][2],
          A[0][1] * A[1][2] - A[0][2] * A[1][1]],
         [A[1][2] * A[2][0] - A[1][0] * A[2][2], A[0][0] * A[2][2] - A[0][2] * A[2][0],
          A[0][2] * A[1][0] - A[0][0] * A[1][2]],
         [A[1][0] * A[2][1] - A[1][1] * A[2][0], A[0][1] * A[2][0] - A[0][0] * A[2][1],
          A[0][0] * A[1][1] - A[0][1] * A[1][0]]]
    return [[C[i][j] / d for j in range(3)] for i in range(3)]


def nearest_rotation(M: Matrix, tol: float = 1e-15, max_iter: int = 60) -> Matrix:
    """Orthogonal polar factor of M by the Newton iteration
    M <- (M + M^-T) / 2. For det M > 0 the result is the rotation nearest
    to M in the Frobenius norm. A rotation is a fixed point."""
    X = [list(map(float, row)) for row in M]
    for _ in range(max_iter):
        Xi = _inv3(X)
        Y = [[(X[i][j] + Xi[j][i]) / 2.0 for j in range(3)] for i in range(3)]
        change = max(abs(Y[i][j] - X[i][j]) for i in range(3) for j in range(3))
        X = Y
        if change <= tol:
            break
    return X


def calibrate(v1: Point, v2: Point, v3: Point) -> Tuple[Matrix, Matrix]:
    """Return (K, R) from three finite vanishing points of orthogonal
    directions. The columns of R are the scene axes in the camera frame,
    each known only up to sign; this function picks the sign with a
    positive Z component for r_1 and r_2 and fixes det R = +1 with r_3.
    Raises ValueError for collinear points or an obtuse or right triangle.
    """
    vs = [(float(v[0]), float(v[1])) for v in (v1, v2, v3)]
    c = orthocenter(*vs)  # @line L1
    q = focal_squared(vs[0], vs[1], c)  # @line L5
    if not q > 0:  # @line L5
        raise ValueError("no real focal length: the triangle is not acute")  # @line L5
    f = math.sqrt(q)  # @line L6
    K = make_K(f, c[0], c[1])  # @line L6
    cols = []
    for v in vs:
        d = ((v[0] - c[0]) / f, (v[1] - c[1]) / f, 1.0)  # @line L7
        n = math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2])  # @line L7
        cols.append([x / n for x in d])  # @line L7
    R = [[cols[j][i] for j in range(3)] for i in range(3)]  # @line L8
    if _det3(R) < 0:  # @line L8
        for i in range(3):  # @line L8
            R[i][2] = -R[i][2]  # @line L8
    R = nearest_rotation(R)  # @line L9
    return K, R  # @line L10
test_vanishing_point_calibration.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vanishing-point-calibration/. The authors are listed in prov/QBYP5B.jsonl.
"""Tests of calibration from three orthogonal vanishing points."""

import itertools
import math
import random
from fractions import Fraction

import pytest

from vanishing_point_calibration import (calibrate, focal_from_two, focal_squared,
                                         nearest_rotation, orthocenter)

# The worked example of the page: f = 800, c = (320, 240), and the scene axes
# have the camera frame directions (2, 0, 1), (-0.5, 1, 1), (-0.5, -1.25, 1).
V1, V2, V3 = (1920, 240), (-80, 1040), (-80, -760)


def quat_to_R(q):
    w, x, y, z = 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_facing(rng, min_z=0.25):
    """A random rotation whose three columns all have Z >= min_z, so that
    the three vanishing points are finite and not too far away."""
    while True:
        q = [rng.gauss(0.0, 1.0) for _ in range(4)]
        n = math.sqrt(sum(a * a for a in q))
        R = quat_to_R([a / n for a in q])
        if min(R[2][i] for i in range(3)) >= min_z:
            return R


def vanishing_points(f, cx, cy, R):
    return [(f * R[0][i] / R[2][i] + cx, f * R[1][i] / R[2][i] + cy) for i in range(3)]


def det3(A):
    return (A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1])
            - A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0])
            + A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]))


def rotation_angle_deg(A, B):
    M = [[sum(A[k][i] * B[k][j] for k in range(3)) for j in range(3)] for i in range(3)]
    tr = M[0][0] + M[1][1] + M[2][2]
    return math.degrees(math.acos(max(-1.0, min(1.0, (tr - 1.0) / 2.0))))


def is_rotation(R, tol):
    for i in range(3):
        for j in range(3):
            g = sum(R[k][i] * R[k][j] for k in range(3))
            if abs(g - (1.0 if i == j else 0.0)) > tol:
                return False
    return abs(det3(R) - 1.0) <= tol


def iac_reference(v1, v2, v3):
    """Reference method: solve the IAC omega = [[w1, 0, w2], [0, w1, w3],
    [w2, w3, w4]] (zero skew, square pixels) from v_i^T omega v_j = 0 as the
    null vector of a 3 x 4 matrix, by cofactors, then read off c and f."""
    A = []
    for a, b in ((v1, v2), (v1, v3), (v2, v3)):
        A.append([a[0] * b[0] + a[1] * b[1], a[0] + b[0], a[1] + b[1], 1.0])

    def minor(k):
        cols = [j for j in range(4) if j != k]
        return det3([[row[j] for j in cols] for row in A])

    w = [(-1) ** k * minor(k) for k in range(4)]
    cx, cy = -w[1] / w[0], -w[2] / w[0]
    f2 = w[3] / w[0] - cx * cx - cy * cy
    return cx, cy, f2


def test_worked_example_exact():
    vs = [tuple(Fraction(x) for x in v) for v in (V1, V2, V3)]
    c = orthocenter(*vs)
    assert c == (Fraction(320), Fraction(240))
    for a, b in itertools.combinations(vs, 2):
        assert focal_squared(a, b, c) == Fraction(640000)


def test_worked_example_rotation():
    K, R = calibrate(V1, V2, V3)
    assert abs(K[0][0] - 800.0) < 1e-9 and abs(K[1][1] - 800.0) < 1e-9
    assert abs(K[0][2] - 320.0) < 1e-9 and abs(K[1][2] - 240.0) < 1e-9
    dirs = [(2.0, 0.0, 1.0), (-0.5, 1.0, 1.0), (-0.5, -1.25, 1.0)]
    for j, d in enumerate(dirs):
        n = math.sqrt(sum(x * x for x in d))
        col = [R[i][j] for i in range(3)]
        s = 1.0 if j < 2 else math.copysign(1.0, sum(c * x for c, x in zip(col, d)))
        assert all(abs(col[i] - s * d[i] / n) < 1e-12 for i in range(3))
    assert is_rotation(R, 1e-12)


def test_random_exact_recovery_and_reference():
    rng = random.Random(20250101)
    for _ in range(60):
        f = rng.uniform(300.0, 1500.0)
        cx, cy = rng.uniform(200.0, 450.0), rng.uniform(150.0, 330.0)
        Rt = random_rotation_facing(rng)
        vs = vanishing_points(f, cx, cy, Rt)
        K, R = calibrate(*vs)
        assert abs(K[0][0] - f) <= 1e-8 * f
        assert math.hypot(K[0][2] - cx, K[1][2] - cy) <= 1e-8 * f
        assert K[0][1] == 0.0 and K[0][0] == K[1][1]
        assert is_rotation(R, 1e-10)
        for j in range(3):
            dot = sum(R[i][j] * Rt[i][j] for i in range(3))
            assert abs(abs(dot) - 1.0) <= 1e-9
        rx, ry, rf2 = iac_reference(*vs)
        assert math.hypot(rx - K[0][2], ry - K[1][2]) <= 1e-6 * f
        assert abs(math.sqrt(rf2) - K[0][0]) <= 1e-6 * f


def test_order_does_not_matter():
    rng = random.Random(5)
    Rt = random_rotation_facing(rng)
    vs = vanishing_points(900.0, 330.0, 250.0, Rt)
    K0, _ = calibrate(*vs)
    for perm in itertools.permutations(vs):
        K, R = calibrate(*perm)
        assert all(abs(K[i][j] - K0[i][j]) <= 1e-8 * 900.0 for i in range(3) for j in range(3))
        assert is_rotation(R, 1e-10)


def test_orthocenter_property_and_acute_triangle():
    rng = random.Random(11)
    for _ in range(30):
        Rt = random_rotation_facing(rng)
        vs = vanishing_points(700.0, 300.0, 200.0, Rt)
        c = orthocenter(*vs)
        for i in range(3):
            a, b, o = vs[i], vs[(i + 1) % 3], vs[(i + 2) % 3]
            side = (a[0] - b[0], a[1] - b[1])
            alt = (c[0] - o[0], c[1] - o[1])
            scale = math.hypot(*side) * max(1.0, math.hypot(*alt))
            assert abs(side[0] * alt[0] + side[1] * alt[1]) <= 1e-9 * scale
            u = (a[0] - o[0], a[1] - o[1])
            w = (b[0] - o[0], b[1] - o[1])
            assert u[0] * w[0] + u[1] * w[1] > 0.0


def test_two_point_variant_with_known_principal_point():
    rng = random.Random(3)
    for _ in range(20):
        f = rng.uniform(400.0, 1200.0)
        Rt = random_rotation_facing(rng)
        vs = vanishing_points(f, 320.0, 240.0, Rt)
        for a, b in itertools.combinations(vs, 2):
            assert abs(focal_from_two(a, b, (320.0, 240.0)) - f) <= 1e-8 * f


def test_noise():
    # sigma = 1 pixel of Gaussian noise on each vanishing point, 40 cameras
    # with f = 800 and c = (320, 240); tolerances 10 px, 15 px and 1 degree.
    rng = random.Random(7)
    for _ in range(40):
        Rt = random_rotation_facing(rng, min_z=0.3)
        vs = [(x + rng.gauss(0.0, 1.0), y + rng.gauss(0.0, 1.0))
              for x, y in vanishing_points(800.0, 320.0, 240.0, Rt)]
        K, R = calibrate(*vs)
        assert abs(K[0][0] - 800.0) < 10.0
        assert math.hypot(K[0][2] - 320.0, K[1][2] - 240.0) < 15.0
        assert is_rotation(R, 1e-10)
        assert rotation_angle_deg(R, Rt) < 1.0


def test_collinear_points_raise():
    with pytest.raises(ValueError):
        calibrate((0.0, 0.0), (100.0, 50.0), (300.0, 150.0))
    with pytest.raises(ValueError):
        orthocenter((Fraction(1), Fraction(2)), (Fraction(3), Fraction(4)), (Fraction(5), Fraction(6)))


def test_obtuse_or_right_triangle_raises():
    # The angle at (1, 1) is obtuse, so no real focal length exists.
    with pytest.raises(ValueError):
        calibrate((0.0, 0.0), (10.0, 0.0), (1.0, 1.0))
    c = orthocenter((Fraction(0), Fraction(0)), (Fraction(10), Fraction(0)), (Fraction(1), Fraction(1)))
    assert focal_squared((0, 0), (10, 0), c) < 0
    # A right angle at (0, 0): the orthocenter is that vertex and f^2 = 0.
    with pytest.raises(ValueError):
        calibrate((0.0, 0.0), (10.0, 0.0), (0.0, 7.0))
    with pytest.raises(ValueError):
        focal_from_two((0.0, 0.0), (10.0, 0.0), (5.0, 5.0))


def test_nearest_rotation_fixes_rotations_and_projects():
    rng = random.Random(2)
    R = random_rotation_facing(rng, min_z=0.0)
    assert all(abs(a - b) <= 1e-14 for ra, rb in zip(nearest_rotation(R), R) for a, b in zip(ra, rb))
    M = [[R[i][j] + rng.uniform(-0.01, 0.01) for j in range(3)] for i in range(3)]
    Q = nearest_rotation(M)
    assert is_rotation(Q, 1e-12)
    assert rotation_angle_deg(Q, R) < 2.0

History

The orthocenter property of three orthogonal vanishing points was shown by Bruno Caprile and Vincent Torre in 1990, in a paper that also recovered the rotation of the camera from the same vanishing points. Hartley and Zisserman later described the same method with the image of the absolute conic: each orthogonal pair is a linear constraint on ω\omega, and other known properties of the camera add more linear constraints. Since then, the method has been a standard tool for single image metrology and for calibration in man-made scenes.

References

  1. Bruno Caprile and Vincent Torre, Using vanishing points for camera calibration, International Journal of Computer Vision 4(2), 1990, 127-139, the orthocenter property of the principal point, the focal length from two orthogonal vanishing points, and the rotation from the vanishing points
  2. Richard Hartley and Andrew Zisserman, Multiple View Geometry in Computer Vision, second edition, Cambridge University Press, 2004, Section 8.6, Vanishing points and vanishing lines; Section 8.8, Determining calibration K from a single view (the linear constraints on omega and the orthocenter result)
  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 from vanishing points)

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