Algorithmcore
P3P
Also called perspective-three-point, Grunert's method.
Solve the pose from three point pairs by finding the distances to the three points from a quartic equation, giving up to four solutions.
- Solves
- Perspective-n-point
- Time
- Θ(n) worst · average · best
- Space
- Θ(1) extra
- Where
- n = the number of point pairs, three to solve and the rest to choose among the solutions
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Johann August Grunert, Robert M. Haralick, Martin A. Fischler, Robert C. Bolles, 1841
P3P finds the pose of a calibrated camera from three known world points and their images. It is the smallest case of the perspective-n-point problem with a finite number of answers: three pairs give six equations for the six unknowns of the pose. The classical method of Grunert (1841) does not solve for the pose directly. It first finds the distances from the camera center to the three points. The angles between the three viewing rays and the sides of the world triangle give three equations from the law of cosines. With the ratios and , they reduce to one quartic in . Each positive real root gives the three points in the camera frame, and the pose is the rigid motion that maps the world triangle onto them. There are at most four solutions, and usually two. A fourth point picks the right one. The method is the standard minimal solver for pose inside RANSAC.
In plain words
You know where three marks are in the world, and you see them in one photo of a camera whose lens you know. Each mark in the photo tells you a direction from the camera. So you know the angle between each pair of directions, and you know how far apart the marks are. The camera must sit at a place from which the three marks are seen under exactly these angles. The method finds how far each mark is from the camera, then turns and moves the triangle of marks to match. Usually two places fit, and up to four can fit. A fourth mark tells you which one is right.
The problem
Input. Three world points that are not collinear, and their images in normalized coordinates, for pixels and the intrinsic matrix . For the selection step, one or more further pairs .
Output. Every pose with a rotation such that with for , where is the unit vector along . The selection step returns the one with the smallest reprojection error on the further pairs.
The algorithm
Write , and for the cosines of the angles at the center between the rays , and , and , , for the sides opposite to them. The three triangles formed by the center and two of the points give
Put , , and . The second equation gives , and the other two become
Their difference is linear in : with and . Put into (A) and multiply by :
Written out, this is the quartic of Grunert in the form given by Haralick and coauthors (1994), with and .
P3P(X1, X2, X3, y1, y2, y3)- 1
f_i <- (y_i1, y_i2, 1) / || (y_i1, y_i2, 1) ||, for i = 1, 2, 3 - 2
cos α <- f2 · f3 ; cos β <- f1 · f3 ; cos γ <- f1 · f2 - 3
a <- || X2 - X3 || ; b <- || X1 - X3 || ; c <- || X1 - X2 || - 4
form the polynomials N(v), D(v) and the quartic G(v) - 5
for each real root v > 0 of G - 6
if D(v) is not close to 0 then U <- { N(v) / D(v) } - 7
else U <- the real roots u of (A) - 8
for each u in U with u > 0 - 9
s1 <- b / sqrt(Q(v)) ; s2 <- u s1 ; s3 <- v s1 ; skip u if the three cosine equations fail - 10
Y_i <- s_i f_i, for i = 1, 2, 3 - 11
(R, t) <- the rigid motion with R X_i + t = Y_i, from a frame built on each triangle - 12
add (R, t) to the output unless it is already there - 13
return the output P3P-SELECT(X1 .. Xn, y1 .. yn), n >= 4- 14
S <- P3P(X1, X2, X3, y1, y2, y3) - 15
return the pose in S with the smallest sum of squared reprojection errors on pairs 4 .. n
Line L7 handles the case , where is not defined. Then as well, the equations (A) and (B) are the same, and both roots of (A) are candidates. The check in line L9 has two jobs. In exact arithmetic it always passes. In floating point it rejects a root near a common root of and , where is only a ratio of rounding errors. Line L11 builds on each triangle the orthonormal frame with along the first side and along the normal, and sets and . Any solver of the Wahba problem, such as the Kabsch algorithm, gives the same motion here.
Example
Take the world points , , , the fourth point , and the true pose , , with angles in radians. The images are , , and . All values are rounded to four places.
| line | value |
|---|---|
| L2 | , , |
| L3 | , , , so |
| L4 | |
| L5 | two real roots, and |
| L6 | and |
| L9 | and |
| L11 | the first pose has ; the second is the true pose |
| L15 | the reprojection errors of are and , so the second pose is chosen |
The second set of distances matches the true camera frame points , and , whose lengths are , and . The first pose also puts the three points exactly on their rays in front of the camera, so three points alone cannot tell the two apart.
Correctness
Each valid pose gives distances that satisfy the three cosine equations. Each solution of those equations with positive distances gives exactly one rotation and translation, because two triangles with the same sides are related by one rigid motion, and a right-handed frame on each makes it a rotation. The substitution , is reversible, and the difference of (A) and (B) is , so a pair solves both if and only if and either , or and solves (A). So the output is exactly the set of valid poses. At a root with , the quartic has a double root, so the total count is still at most 4 unless is the zero polynomial. The full proof is in the proof file of this page.
Proof: The roots of Grunert's quartic give exactly the poses that put three points on their rays in front of the camerafull
We use the notation of the page. The world points are not collinear, and the side lengths are , and . The image points are distinct, is the unit vector along , and , , . A pose with is valid if with for . The arithmetic is exact (real RAM), and the root finder of line L5 returns every real root of .
Put , ,
Claim. Assume is not the zero polynomial. (a) Every pose returned by P3P is valid. (b) Every valid pose is returned. (c) There are at most four valid poses.
Lemma 1 (the three equations). A pose is valid with distances only if
Conversely, if positive satisfy (1), then there is exactly one and one with , and line L11 returns them.
Proof. A rigid motion keeps distances, so , and expanding the square gives the first equation; the others are the same. For the converse, put . By (1) the triangles and have the same side lengths. For a triangle , line L11 builds the frame , the unit normal along , . This is a right-handed orthonormal frame. In it, has coordinates , and has coordinates with by the law of cosines and , because the cross product points along . These coordinates depend only on , , , so they are the same for and . Let and be the frame matrices, with the frame vectors as columns. Both are rotations, so , and for each . With we get . The motion is unique, because a rigid motion is fixed by its action on three points that are not collinear: the difference of two such motions fixes , and their cross product, which span .
Lemma 2 (reduction to one unknown). Let , and put and . Then (1) holds if and only if
Moreover, for all real and , , where (A) and (B) stand for their left sides.
Proof. The rays and are distinct unit vectors with positive third entries, so , and . Substitute and in (1). The second equation becomes . The third becomes , and after division by it is (A). The first becomes , which is (B) in the same way. The steps can be reversed. For the last statement,
since .
Lemma 3 (the quartic). If and satisfy (A) and (B), then . If and , then is the only with (A) and (B). If and , then , and the with (A) and (B) are exactly the real roots of (A).
Proof. By Lemma 2, (A) and (B) give . Multiply (A) by and replace by : the result is . If , (B) forces , and then , so (A) holds, and (B) holds because . If , then , so , and for every : the two equations are the same, and their solutions are the roots of (A).
Proof of part (a). Take an output pose. It comes from a root of (line L5) and a (line L8). If , line L6 sets , and Lemma 3 gives (A) and (B). If , line L7 takes the roots of (A), and Lemma 3 again gives (A) and (B). Line L9 sets , and , so (1) holds by Lemma 2, and the check of (1) in line L9 passes in exact arithmetic. By Lemma 1, line L11 returns a valid pose.
Proof of part (b). Take a valid pose with distances , and put and . By Lemma 1 and Lemma 2, (A) and (B) hold, so by Lemma 3, and line L5 meets this . If , line L6 finds this same by Lemma 3. If , this is a root of (A), so it is one of the values of line L7. Then lines L9 to L11 rebuild the same and, by the uniqueness in Lemma 1, the same pose. Line L12 drops a pose only if it equals one already stored, so the pose is in the output.
Proof of part (c). By Lemma 1 a valid pose is fixed by , and by Lemma 2 these are fixed by . So we count the pairs with (A) and (B). has degree at most 4 and is not zero, so it has at most four roots, counted with multiplicity. A root with carries one pair. A root with carries at most two pairs, the two roots of (A). But then too, and each of the three terms of has a factor of the form , or , all of which vanish to order at least 2 at , so is a root of of multiplicity at least 2. In both cases the number of pairs at a root is at most its multiplicity, so there are at most four pairs.
Remark (floating point). In floating point, a root of near a common root of and can have small but not zero. Then is a quotient of two rounding errors and does not satisfy (A) and (B). The check of (1) in line L9, with a relative tolerance of , rejects such a value. This tolerance is a heuristic, not a theorem. A true root near a double root of loses about half of its digits, and on random scenes its relative residual is about ; the false values of this kind miss by more than .
Remark (the zero polynomial). is the zero polynomial when the problem has infinitely many solutions, for example when the camera center lies on the circle through the three points, in their own plane. Every point of the same arc of that circle sees the three points under the same angles, so each one gives a valid pose. The solver is not meant for this case.
Complexity
The solver does a fixed number of arithmetic steps and solves one quartic. In the real RAM model, with the roots of a quartic as one step, P3P takes time and space. In floating point the roots come from a closed form or from a few iterations of a root finder such as the companion matrix method. P3P-SELECT adds work for each further pair and each of at most four poses, so it takes time and extra space.
Properties
- At most four solutions. This is a theorem. On random scenes with the camera a few units away, two solutions are by far the most common case, and one or four occur in a few percent of the scenes.
- Minimal. Three pairs give six equations for six unknowns, so P3P has no redundancy and cannot detect an error in its own data.
- Rotation always proper. The output is a rotation with determinant , not a reflection, because both frames of line L11 are right-handed.
- Positive depths built in. Only and are kept, so every point is in front of the camera.
- Independent of the world frame. Only the side lengths of the world triangle enter the quartic.
Variants and improvements
- Other eliminations. Haralick and coauthors (1994) compared Grunert's method with the later direct solutions of Finsterwalder, Merritt, Fischler and Bolles, Linnainmaa and others. They differ in which ratio is the unknown and in their numerical stability.
- Direct pose. Kneip, Scaramuzza and Siegwart (2011) solve a quartic for parameters of the pose itself and skip the distances.
- Cubic first. Lambda Twist of Persson and Nordberg (2018) finds one real root of a cubic and then two quadratics, followed by a short Gauss-Newton polish. It is faster and more stable than the quartic solvers.
- Generalized cameras. With rays that do not meet in one center, the problem becomes the generalized P3P of the generalized camera model.
- More points. For points, linear and iterative methods such as EPnP solve the overdetermined problem. P3P stays the solver inside RANSAC and is followed by refinement of the reprojection error on all inliers.
When to use it
Use P3P inside RANSAC when you have many 2D-3D matches with outliers, for example to place a new image in incremental structure from motion or to relocalize a camera against a map. The small sample of three keeps the number of RANSAC iterations low. Test each of the up to four poses on the other matches, then refine the best one on its inliers. When the matches are already clean and many, use a method for points instead.
Pitfalls
- Pixels instead of normalized coordinates. The angles between rays need ; pixels give wrong cosines.
- Danger cylinder. When the camera center lies on the cylinder through the three points with its axis normal to their plane, two solutions merge into a double root. Near it the pose is unstable, as Thompson (1966) described for space resection.
- Division by zero. happens at true solutions, for example when the second ray is perpendicular to the side . An implementation that always divides then returns a wrong pose.
- False roots. A common root of and is a root of that is not a solution; without the check of line L9 it gives a pose that does not fit the rays.
- Collinear points. Three collinear world points do not fix the rotation about their line; the solver must reject them.
- Picking one solution blindly. The smallest distance or the first root is not the true pose in general. Use a fourth point or the RANSAC consensus.
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.
# 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()
p3p.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/p3p/. The authors are listed in prov/E145BQ.jsonl.
"""P3P by Grunert's elimination.
Given three world points X1, X2, X3 and their images y1, y2, y3 in
normalized image coordinates (y = K^-1 x, two entries each), find every
pose (R, t) with Xc = R Xw + t that maps each Xi onto its ray with a
positive depth. There are at most four such poses.
The unknowns are the distances s1, s2, s3 from the camera center to the
three points. With s2 = u s1 and s3 = v s1, the law of cosines in the
three triangles (center, Xi, Xj) gives a quartic in v and a rational
expression for u. Each positive root gives the three points in the
camera frame, and the pose is the rigid motion that maps the world
triangle onto the camera triangle.
Cost: O(1). The quartic is solved by cvla.polyroots_real; the rest is a
fixed number of arithmetic operations.
"""
from __future__ import annotations
import math
from typing import List, Sequence, Tuple
from cvla import cross, dot, matvec, mul, norm, polyroots_real, sub, transpose
Matrix = List[List[float]]
Vector = List[float]
# ------------------------------------------------- polynomials in v
# A polynomial is a list of coefficients, highest power first.
def _padd(p: Sequence[float], q: Sequence[float]) -> Vector:
n = max(len(p), len(q))
p = [0.0] * (n - len(p)) + list(p)
q = [0.0] * (n - len(q)) + list(q)
return [a + b for a, b in zip(p, q)]
def _pmul(p: Sequence[float], q: Sequence[float]) -> Vector:
r = [0.0] * (len(p) + len(q) - 1)
for i, a in enumerate(p):
for j, b in enumerate(q):
r[i + j] += a * b
return r
def _pscale(p: Sequence[float], c: float) -> Vector:
return [c * a for a in p]
def _peval(p: Sequence[float], x: float) -> float:
s = 0.0
for a in p:
s = s * x + a
return s
# ------------------------------------------------------------ the solver
def bearing(y: Sequence[float]) -> Vector:
"""The unit vector along the ray of the normalized image point y."""
f = [float(y[0]), float(y[1]), 1.0]
n = norm(f)
return [c / n for c in f]
def grunert_polynomials(ca: float, cb: float, cg: float, a: float, b: float,
c: float) -> Tuple[Vector, Vector, Vector]:
"""The quartic G(v) and the polynomials N(v), D(v) with u = N(v) / D(v).
ca, cb, cg are the cosines of the angles at the center between the rays
(2, 3), (1, 3) and (1, 2); a, b, c are the side lengths |X2 X3|,
|X1 X3| and |X1 X2|. G = N^2 - 2 cg N D + (1 - (c/b)^2 Q) D^2 with
Q(v) = v^2 - 2 cb v + 1."""
p = (a * a - c * c) / (b * b)
q = [1.0, -2.0 * cb, 1.0] # Q(v)
num = [p - 1.0, -2.0 * p * cb, 1.0 + p] # N(v)
den = [-2.0 * ca, 2.0 * cg] # D(v)
g = _padd(_pmul(num, num), _pscale(_pmul(num, den), -2.0 * cg))
g = _padd(g, _pmul(_padd([1.0], _pscale(q, -(c * c) / (b * b))), _pmul(den, den)))
return g, num, den
def _laws_of_cosines_hold(s: Sequence[float], ca: float, cb: float, cg: float,
a: float, b: float, c: float, rel: float = 1e-3) -> bool:
"""True if the distances s satisfy the three equations of the page
within rel times the squared side length. A root of G that is not a
true solution (a common root of N and D) misses by far more than
rel; a true root near a double root can miss by about 1e-5."""
s1, s2, s3 = s
return (abs(s2 * s2 + s3 * s3 - 2.0 * s2 * s3 * ca - a * a) <= rel * a * a and
abs(s1 * s1 + s3 * s3 - 2.0 * s1 * s3 * cb - b * b) <= rel * b * b and
abs(s1 * s1 + s2 * s2 - 2.0 * s1 * s2 * cg - c * c) <= rel * c * c)
def rigid_from_triangles(X: Sequence[Sequence[float]],
Y: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector]:
"""The rotation R and translation t with Y_i = R X_i + t for two
congruent triangles, from an orthonormal frame built on each one."""
def frame(P):
e1 = sub(P[1], P[0])
e1 = [c / norm(e1) for c in e1]
e3 = cross(sub(P[1], P[0]), sub(P[2], P[0]))
e3 = [c / norm(e3) for c in e3]
e2 = cross(e3, e1)
return transpose([e1, e2, e3]) # columns e1, e2, e3
R = mul(frame(Y), transpose(frame(X)))
RX = matvec(R, X[0])
t = [Y[0][i] - RX[i] for i in range(3)]
return R, t
def p3p(Xw: Sequence[Sequence[float]], y: Sequence[Sequence[float]],
eps_d: float = 1e-6) -> List[Tuple[Matrix, Vector]]:
"""All poses (R, t) for three world points Xw and their normalized
image points y. Each pose puts the three points on their rays with a
positive depth. Raises ValueError if the world points are collinear.
If |D(v)| is below eps_d times its scale, u is not fixed by u = N / D;
then both positive roots of the quadratic (A) in u are tried. Poses
that agree within 1e-7 (a root found twice) are kept once."""
X = [[float(c) for c in p] for p in Xw]
if norm(cross(sub(X[1], X[0]), sub(X[2], X[0]))) == 0.0:
raise ValueError("p3p: the world points are collinear")
f = [bearing(yi) for yi in y] # @line L1
ca, cb, cg = dot(f[1], f[2]), dot(f[0], f[2]), dot(f[0], f[1]) # @line L2
a = norm(sub(X[1], X[2])) # @line L3
b = norm(sub(X[0], X[2])) # @line L3
c = norm(sub(X[0], X[1])) # @line L3
g, num, den = grunert_polynomials(ca, cb, cg, a, b, c) # @line L4
sols: List[Tuple[Matrix, Vector]] = []
for v in polyroots_real(g): # @line L5
if v <= 0.0:
continue
d = _peval(den, v)
if abs(d) > eps_d * (abs(ca) * v + abs(cg)): # @line L6
us = [_peval(num, v) / d] # @line L6
else: # @line L7
disc = cg * cg - 1.0 + (c * c) / (b * b) * (v * v - 2.0 * cb * v + 1.0)
if disc < -1e-9: # @line L7
continue
r = math.sqrt(max(disc, 0.0)) # @line L7
us = [cg - r, cg + r] if r > 0.0 else [cg] # @line L7
for u in us:
if u <= 0.0: # @line L8
continue
s1 = b / math.sqrt(1.0 + v * v - 2.0 * v * cb) # @line L9
s = [s1, u * s1, v * s1] # @line L9
if not _laws_of_cosines_hold(s, ca, cb, cg, a, b, c): # @line L9
continue
Y = [[s[i] * f[i][k] for k in range(3)] for i in range(3)] # @line L10
R, t = rigid_from_triangles(X, Y) # @line L11
if all(norm(sub(R, R2)) + norm(sub(t, t2)) > 1e-7 * (1.0 + norm(t))
for R2, t2 in sols): # @line L12
sols.append((R, t)) # @line L12
return sols # @line L13
def reprojection_error(R: Sequence[Sequence[float]], t: Sequence[float],
Xw: Sequence[float], y: Sequence[float]) -> float:
"""Distance in normalized coordinates between y and the image of Xw.
A point behind the camera gets an infinite error."""
Xc = [a + b for a, b in zip(matvec(R, Xw), t)]
if Xc[2] <= 0.0:
return math.inf
return math.hypot(Xc[0] / Xc[2] - y[0], Xc[1] / Xc[2] - y[1])
def p3p_select(Xw: Sequence[Sequence[float]], y: Sequence[Sequence[float]]
) -> Tuple[Matrix, Vector]:
"""Solve with the first three points and keep the pose with the
smallest reprojection error on the remaining points (at least one)."""
sols = p3p(Xw[:3], y[:3]) # @line L14
if not sols:
raise ValueError("p3p_select: no pose with positive depths")
def err(sol):
R, t = sol
return sum(reprojection_error(R, t, Xw[i], y[i]) ** 2 for i in range(3, len(Xw)))
return min(sols, key=err) # @line L15
test_p3p.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/p3p/. The authors are listed in prov/E145BQ.jsonl.
"""Tests of P3P by Grunert's elimination."""
import math
import random
import pytest
from cvgeom import random_scene, rot_x, rot_y
from cvla import det, dot, matvec, mul, norm, polyroots_real, sub, transpose
from p3p import (bearing, grunert_polynomials, p3p, p3p_select,
reprojection_error)
I3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
K1 = I3
# The worked example of the page.
X_EX = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.3, 1.0, 0.0], [1.0, 1.0, 1.0]]
R_EX = mul(rot_y(0.3), rot_x(0.2))
T_EX = [0.2, -0.1, 4.0]
def image(R, t, X):
xc = [a + b for a, b in zip(matvec(R, X), t)]
return [xc[0] / xc[2], xc[1] / xc[2]]
def rotation_angle(R1, R2):
"""The angle of R1^T R2, as 2 asin(||R1 - R2||_F / (2 sqrt 2)), which
keeps its accuracy near 0."""
d = norm(sub(R1, R2)) / (2.0 * math.sqrt(2.0))
return 2.0 * math.asin(min(1.0, d))
def pose_error(R, t, sol):
Rs, ts = sol
return rotation_angle(R, Rs) + norm(sub(t, ts)) / max(1.0, norm(t))
def root_gap(X, y):
"""The smallest distance between two positive real roots of G."""
f = [bearing(v) for v in y[:3]]
ca, cb, cg = dot(f[1], f[2]), dot(f[0], f[2]), dot(f[0], f[1])
a, b, c = norm(sub(X[1], X[2])), norm(sub(X[0], X[2])), norm(sub(X[0], X[1]))
g, _, _ = grunert_polynomials(ca, cb, cg, a, b, c)
r = sorted(v for v in polyroots_real(g) if v > 0)
return min((r[i + 1] - r[i] for i in range(len(r) - 1)), default=math.inf)
def test_worked_example():
y = [image(R_EX, T_EX, X) for X in X_EX]
sols = p3p(X_EX[:3], y[:3])
assert len(sols) == 2
errs = sorted(pose_error(R_EX, T_EX, s) for s in sols)
assert errs[0] <= 1e-8 and errs[1] > 0.1
# the other pose misses the fourth point by about 0.18
other = [s for s in sols if pose_error(R_EX, T_EX, s) > 0.1][0]
assert abs(reprojection_error(other[0], other[1], X_EX[3], y[3]) - 0.1798) <= 1e-4
Rb, tb = p3p_select(X_EX, y)
assert pose_error(R_EX, T_EX, (Rb, tb)) <= 1e-8
def test_quartic_of_the_example():
y = [image(R_EX, T_EX, X) for X in X_EX]
f = [bearing(v) for v in y[:3]]
ca, cb, cg = dot(f[1], f[2]), dot(f[0], f[2]), dot(f[0], f[1])
g, _, _ = grunert_polynomials(ca, cb, cg, math.sqrt(1.49), math.sqrt(1.09), 1.0)
roots = polyroots_real(g)
assert len(roots) == 2
assert abs(roots[0] - 0.867775) <= 1e-6 and abs(roots[1] - 1.055802) <= 1e-6
@pytest.mark.parametrize("seed", range(4))
def test_all_solutions_are_valid(seed):
rng = random.Random(seed)
for _ in range(8):
sc = random_scene(rng, n=3, n_cams=1, K=K1)
X, y = sc["X"], sc["x"][0]
sols = p3p(X, y)
assert 1 <= len(sols) <= 4
for R, t in sols:
assert abs(det(R) - 1.0) <= 1e-9
assert norm(sub(mul(transpose(R), R), I3)) <= 1e-9
for i in range(3):
assert reprojection_error(R, t, X[i], y[i]) <= 1e-7
@pytest.mark.parametrize("seed", range(4, 8))
def test_true_pose_is_among_the_solutions(seed):
rng = random.Random(seed)
for _ in range(8):
sc = random_scene(rng, n=3, n_cams=1, K=K1)
X, y = sc["X"], sc["x"][0]
R, t = sc["R"][0], sc["t"][0]
best = min(pose_error(R, t, s) for s in p3p(X, y))
# near a double root of G the roots lose half of their digits
tol = 1e-8 if root_gap(X, y) > 0.05 else 1e-4
assert best <= tol
def test_select_with_a_fourth_point():
rng = random.Random(21)
for _ in range(12):
sc = random_scene(rng, n=4, n_cams=1, K=K1)
X, y = sc["X"], sc["x"][0]
R, t = sc["R"][0], sc["t"][0]
if root_gap(X, y) <= 0.05:
continue
assert pose_error(R, t, p3p_select(X, y)) <= 1e-8
def test_pixel_input_after_normalization():
# Pixels are mapped by K^-1 before the solver is called.
rng = random.Random(22)
K = [[800.0, 0.0, 320.0], [0.0, 800.0, 240.0], [0.0, 0.0, 1.0]]
sc = random_scene(rng, n=4, n_cams=1, K=K)
y = [[(u - 320.0) / 800.0, (v - 240.0) / 800.0] for u, v in sc["x"][0]]
Rb, tb = p3p_select(sc["X"], y)
assert pose_error(sc["R"][0], sc["t"][0], (Rb, tb)) <= 1e-8
def test_common_root_of_n_and_d_is_rejected():
# Here cos(alpha) = cos(beta) cos(gamma), so N and D share a root and G
# has a double root that is not a solution. Only two poses remain.
R = [[1.0, 0.0, 0.0], [0.0, 0.8, -0.6], [0.0, 0.6, 0.8]]
t = [0.0, 0.0, 4.0]
X = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
y = [image(R, t, p) for p in X]
sols = p3p(X, y)
assert len(sols) == 2
assert min(pose_error(R, t, s) for s in sols) <= 1e-8
for Rs, ts in sols:
for i in range(3):
assert reprojection_error(Rs, ts, X[i], y[i]) <= 1e-9
def test_zero_denominator_uses_the_quadratic():
# Ray 2 is orthogonal to the side X1 X3 at the true pose, so D(v) = 0
# there; the solver must still return the true pose.
R = [[0.8, 0.0, 0.6], [0.0, 1.0, 0.0], [-0.6, 0.0, 0.8]]
t = [0.0, 0.0, 4.0]
X = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
y = [image(R, t, p) for p in X]
sols = p3p(X, y)
assert min(pose_error(R, t, s) for s in sols) <= 1e-8
def test_noise_gives_a_close_pose():
# sigma = 0.0005 in normalized coordinates (0.4 pixel at f = 800).
rng = random.Random(23)
sc = random_scene(rng, n=6, n_cams=1, K=K1)
y = [[c + rng.gauss(0.0, 0.0005) for c in p] for p in sc["x"][0]]
Rb, tb = p3p_select(sc["X"], y)
assert rotation_angle(sc["R"][0], Rb) <= 0.05
assert norm(sub(tb, sc["t"][0])) <= 0.1 * norm(sc["t"][0])
def test_collinear_points_raise():
X = [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]
y = [[0.0, 0.0], [0.1, 0.1], [0.2, 0.2]]
with pytest.raises(ValueError):
p3p(X, y)
History
Grunert (1841) solved the problem of finding the position of a point from the angles under which it sees three known points, the extended Pothenot problem of surveying, by a quartic in a ratio of distances. Photogrammetry used the same problem for space resection, and Thompson (1966) described its failure on the danger cylinder. Fischler and Bolles (1981) brought it into computer vision as the location determination problem and used it as the solver inside RANSAC. Wolfe and coauthors (1991) explained the geometry of the multiple solutions, and Haralick and coauthors (1994) reviewed the classical direct solutions and their numerical stability. Gao and coauthors (2003) classified the number of real solutions completely. Kneip and coauthors (2011) and Persson and Nordberg (2018) gave faster and more stable solvers.
References
- Robert M. Haralick, Chung-Nan Lee, Karsten Ottenberg and Michael Nolle, Review and analysis of solutions of the three point perspective pose estimation problem, International Journal of Computer Vision 13(3), 1994, 331-356, Grunert's solution, the other classical direct solutions and their numerical behavior
- Martin A. Fischler and Robert C. Bolles, Random sample consensus, a paradigm for model fitting with applications to image analysis and automated cartography, Communications of the ACM 24(6), 1981, 381-395, the location determination problem with three points, its quartic and its use inside RANSAC
- Xiao-Shan Gao, Xiao-Rong Hou, Jianliang Tang and Hang-Fei Cheng, Complete solution classification for the perspective-three-point problem, IEEE Transactions on Pattern Analysis and Machine Intelligence 25(8), 2003, 930-943, the number of real solutions as a function of the data
- William J. Wolfe, Donald Mathis, Cheryl Weber Sklair and Michael Magee, The perspective view of three points, IEEE Transactions on Pattern Analysis and Machine Intelligence 13(1), 1991, 66-73, the geometry of the multiple solutions
- Laurent Kneip, Davide Scaramuzza and Roland Siegwart, A novel parametrization of the perspective-three-point problem for a direct computation of absolute camera position and orientation, CVPR 2011, 2969-2976, the direct computation of the pose without the distances
- Mikael Persson and Klas Nordberg, Lambda Twist, an accurate fast robust perspective three point (P3P) solver, ECCV 2018, Lecture Notes in Computer Science, 334-349, the solver through one real root of a cubic
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag E145BQ Edit this page History Report an error Markdown