Throughout the course the camera has been an object we placed wherever we wanted. In virtual and augmented reality the camera is no longer ours: it is the user's head or the camera of their phone, and it moves without asking permission. The mathematical work consists of knowing at every instant where it is and where it is looking—its pose—and of drawing the scene so that it fits what the eyes perceive. No new tools are needed: a pose is a position and a quaternion, each eye has its own view matrix, lenses are described with a polynomial and a real camera is the perspective matrix of Module 5 written in another form. In this lesson we build the pieces of a virtual reality headset for the ship's cockpit and of an augmented reality application that places a scale model of the lighthouse on a table.
The code assumes that all the functions from the previous lessons have been imported (from mini3d import *).
Two inverse problems: VR, AR and MR
| Virtual reality (VR) | Augmented reality (AR) | Mixed reality (MR) | |
|---|---|---|---|
| What the user sees | Only the virtual world | The real world with virtual objects overlaid | Real and virtual integrated, occluding each other and interacting |
| Typical device | Opaque headset with two screens and lenses | Phone or tablet with a camera | Headset with cameras or transparent lenses |
| What has to be known | The pose of the head | The pose of the camera relative to the real world | In addition, the geometry of the surroundings |
| Central mathematical problem | From a pose, generate two images consistent with the two eyes and with the lenses | From an image, deduce the pose of the camera | Both, plus reconstructing surfaces |
| Direction of the calculation | 3D world → image | Image → 3D world | Both |
They are inverse problems of each other. In VR everything is known (the scene is ours) and we have to project very accurately and very fast. In AR the scene is the real world, of which we only have images, and we have to undo the projection to find out where the camera is and where the surfaces are. The industry's SDKs—OpenXR for headsets, ARCore and ARKit for phones—deliver these quantities already computed; here we are interested in what they are and where they come from.
The head pose: 3DoF, 6DoF and quaternions
A pose is the position and the orientation of a rigid body: a point \(\mathbf{p}\) and a unit quaternion \(q\), seven numbers for six degrees of freedom (DoF): three of translation and three of rotation.
| Tracking | What it measures | Sensors | Limitation |
|---|---|---|---|
| 3DoF | Only the orientation | Gyroscope and accelerometer (IMU) | If the user leans or walks, the image does not respond |
| 6DoF | Orientation and position | IMU and cameras that observe the surroundings | More computation; it needs visible reference points |
The gyroscope directly measures the angular velocity \(\boldsymbol{\omega}\) of the head, hundreds of times per second. The orientation is obtained by integrating it with the equation from "Physics Simulation", \(\dot{q} = \tfrac{1}{2},\boldsymbol{\omega},q\): the function integrate_orientation is, literally, the core of 3DoF tracking. Since every integrator accumulates error (drift), the accelerometer—which indicates where "down" is—and the cameras correct it periodically.
Why quaternions and not Euler angles? For the reasons given in Module 4, which are critical here:
- No gimbal lock. A user can look at the ceiling or lie down; with Euler angles, near ±90° of pitch the tracking would become unstable.
- Direct integration of the angular velocity, and trivial renormalization.
- Interpolation and extrapolation along the shortest path (
quaternion_slerp), needed to predict the pose.
Let us fix the example. The pilot is seated in the cockpit, with their head at the point \((0, 0.5, 1)\) of the ship, looking forward, along the nose. We will use the same convention for the head as for the camera: it looks toward its local \(-Z\), with \(+X\) to its right and \(+Y\) upward.
import numpy as np
from mini3d import *
np.set_printoptions(suppress=True)
ship = np.array([8.0, 3.0, 6.0])
ship_orientation = np.array([[0.6, 0.0, 0.8], [0.0, 1.0, 0.0], [-0.8, 0.0, 0.6]])
ship_world = model_matrix(ship, ship_orientation)
nose = ship_orientation[:, 2]
head = transform_point(ship_world, [0.0, 0.5, 1.0])
head_rotation = look_at_matrix(head, head + nose)[:3, :3].T
q_head = matrix_to_quaternion(head_rotation)
print(head, np.round(q_head, 4))
print(head_rotation + 0.0)The orientation of the head is the transpose of the rotation block of a look-at: its columns are the axes of the head in the world. The first, \((-0.6, 0, 0.8)\), is the pilot's right; the third, \((-0.8, 0, -0.6)\), is their "back", opposite to the nose.
Stereoscopic vision: two view matrices
We perceive depth, to a large extent, because each eye sees the scene from a slightly different point. A headset reproduces that situation by drawing two images, one per eye, with two cameras separated by the interpupillary distance (IPD), which in an adult is around 64 mm.
The two eyes share the orientation of the head; only the position changes, shifted half an IPD to each side along the head's "right" axis, \(\hat{\mathbf{d}}\) (the first column of its rotation matrix):
\[ \mathbf{e}{\text{left}} = \mathbf{p} - \tfrac{\text{IPD}}{2},\hat{\mathbf{d}} \qquad\qquad \mathbf{e}{\text{right}} = \mathbf{p} + \tfrac{\text{IPD}}{2},\hat{\mathbf{d}} \]
Each view matrix is the rigid inverse of the eye's world matrix, \([R \mid \mathbf{e}]\), just as in "Coordinate Spaces and the View Matrix".
def stereo_views(position, q, ipd=0.064):
"""View matrices (left, right) of the two eyes from the pose of the head."""
r = quaternion_to_matrix(q)
right = r[:, 0]
return tuple(rigid_inverse(affine_matrix(r, np.asarray(position) + side * 0.5 * ipd * right))
for side in (-1.0, 1.0))
view_left, view_right = stereo_views(head, q_head)
panel = transform_point(ship_world, [0.0, 0.3, 1.5]) # control panel
nose_tip = np.array([9.6, 3.0, 7.2]) # the nose of the hull
for name, p in (("panel", panel), ("nose", nose_tip)):
print(name, np.round(transform_point(view_left, p), 3) + 0.0,
np.round(transform_point(view_right, p), 3) + 0.0)In the view space of each eye, the same point has the same \(y\) and \(z\) and an \(x\) that differs by exactly the IPD, 0.064: for the left eye, whatever is right in front of the nose lies 3.2 cm to the right; for the right eye, 3.2 cm to the left. The two cameras are parallel: they do not turn to "go cross-eyed" toward the object. Convergence is taken care of by the user's real eyes, not by the matrices.
Disparity and perceived depth
Let us project that point with the same perspective matrix for both eyes. The horizontal coordinate in NDC was \(x_{\text{ndc}} = P_{00},x_v / Z\), with \(Z = -z_v\) the depth. Since \(x_v\) differs by the IPD between one eye and the other, the two images of the point are separated horizontally by an amount, the disparity, which in pixels equals:
\[ d = \frac{f,b}{Z} \qquad\text{with}\qquad f = P_{00},\frac{\text{width}}{2} \]
where \(b\) is the separation between cameras (the IPD) and \(f\) is the focal length in pixels, which will appear again in the second half of the lesson. The disparity is inversely proportional to the depth: it is the information from which the brain extracts distance, and the relationship can be inverted, \(Z = f,b / d\), which is how stereo cameras measure depth.
With a headset of 1440 × 1600 pixels per eye and a vertical field of view of 90° (\(P_{00} = 1/(0.9 \cdot \tan 45°) = 1.111\)), \(f = 800\) pixels:
eye_projection = perspective_matrix(np.radians(90.0), 1440.0 / 1600.0, 0.1, 100.0)
focal = eye_projection[0, 0] * 1440.0 / 2.0
x_left = project_point(eye_projection @ view_left, nose_tip)[0] * 720.0
x_right = project_point(eye_projection @ view_right, nose_tip)[0] * 720.0
print(round(focal, 1), round(x_left - x_right, 2))
for z in (0.5, 1.0, 2.0, 10.0, 50.0, 100.0):
print(z, round(focal * 0.064 / z, 2))| Object | Depth | Disparity |
|---|---|---|
| Control panel | 0.5 m | 102.4 px |
| Nose of the ship | 1 m | 51.2 px |
| An object 2 m away | 2 m | 25.6 px |
| The lighthouse, seen from orbit | 10 m | 5.1 px |
| A distant asteroid | 100 m | 0.5 px |
The disparity plummets with distance: between 0.5 and 1 m it changes by 51 pixels; between 50 and 100 m, by half a pixel. That is why stereoscopic vision is very precise within arm's reach and useless for telling whether an asteroid is 100 or 200 m away: beyond a few tens of meters, depth is perceived through other cues (apparent size, perspective, relative motion when the head moves).
Asymmetric frustums
The perspective_matrix matrix describes a symmetric frustum: the axis of the camera passes through the center of the image. In a headset that does not hold. Each eye sees more of the field outward (toward the temple) than inward (toward the nose), and the lens is not centered on its screen. The frustum of each eye is asymmetric (off-axis): it is defined with four independent limits on the near plane, \(l\), \(r\) (left and right), \(b\), \(t\) (bottom and top).
Repeating the derivation of "Projections and Views" without assuming \(l = -r\) or \(b = -t\), two new terms appear in the third column:
\[ P = \begin{pmatrix} \dfrac{2n}{r - l} & 0 & \dfrac{r + l}{r - l} & 0 \\ 0 & \dfrac{2n}{t - b} & \dfrac{t + b}{t - b} & 0 \\ 0 & 0 & -\dfrac{f + n}{f - n} & -\dfrac{2fn}{f - n} \\ 0 & 0 & -1 & 0 \end{pmatrix} \]
The two new terms multiply \(z\) and, after dividing by \(w = -z\), become a constant offset of the image: the point that is right in front of the eye no longer lands at the center. If the frustum is symmetric, \(r + l = 0\), \(t + b = 0\) and we recover the familiar matrix.
def asymmetric_perspective_matrix(left, right, bottom, top, near, far):
"""General perspective: frustum limits measured on the near plane."""
m = np.zeros((4, 4))
m[0, 0] = 2.0 * near / (right - left)
m[0, 2] = (right + left) / (right - left)
m[1, 1] = 2.0 * near / (top - bottom)
m[1, 2] = (top + bottom) / (top - bottom)
m[2, 2] = -(far + near) / (far - near)
m[2, 3] = -2.0 * far * near / (far - near)
m[3, 2] = -1.0
return m
t30 = np.tan(np.radians(30.0))
print(np.allclose(asymmetric_perspective_matrix(-16.0 / 9.0 * t30, 16.0 / 9.0 * t30, -t30, t30, 1.0, 100.0),
perspective_matrix(np.radians(60.0), 16.0 / 9.0, 1.0, 100.0)))
def tangent(degrees):
return np.tan(np.radians(degrees))
near = 0.1 # left eye: 50 degrees outward, 40 toward the nose
p_left = asymmetric_perspective_matrix(-near * tangent(50.0), near * tangent(40.0),
-near * tangent(45.0), near * tangent(45.0), near, 100.0)
p_right = asymmetric_perspective_matrix(-near * tangent(40.0), near * tangent(50.0),
-near * tangent(45.0), near * tangent(45.0), near, 100.0)
far_point = head + 1000.0 * nose # a very distant point, straight ahead
print(np.round(p_left[0], 4))
print(np.round(project_point(p_left @ view_left, far_point)[:2], 4) + 0.0,
np.round(project_point(p_right @ view_right, far_point)[:2], 4) + 0.0)The first line confirms the symmetric case. For the left eye, with 50° to the left and 40° to the right, the new term equals \(-0.1736\) and a distant point located straight ahead is drawn at \(x_{\text{ndc}} = +0.174\): to the right of the center of its image, because that image extends farther to the left. In the right eye, symmetrically, at \(-0.174\). The same kind of matrix is used when the "window" onto the virtual world is a fixed screen and the user moves in front of it: the frustum goes from the eye to the edges of the screen and stops being symmetric as soon as the eye is not centered.
Latency and pose prediction
Between the instant at which the sensors measure the pose and the instant at which the image reaches the eyes, some time passes: the latency (measuring, simulating, drawing, sending to the screen). During that time the head has kept moving, and the image is shown for a pose that is no longer the real one. The effect is that the virtual world seems to "swim" when the head turns, a classic cause of motion sickness.
Let us run the numbers. A normal head turn reaches 120°/s. With 20 ms of latency, the error is \(120 \cdot 0.02 = 2.4°\), which with our focal length of 800 pixels means an offset of \(800 \cdot \tan 2.4° \approx 34\) pixels: very visible.
The remedy is to predict: we do not draw for the measured pose, but for the one the head will have when the image is shown. If the angular velocity \(\boldsymbol{\omega}\) holds during \(\Delta t\), the head will have rotated through an angle \(\lVert \boldsymbol{\omega} \rVert,\Delta t\) about \(\hat{\boldsymbol{\omega}}\):
\[ q_{\text{pred}} = \Delta q ; q \qquad \Delta q = \text{quaternion with axis } \hat{\boldsymbol{\omega}} \text{ and angle } \lVert \boldsymbol{\omega} \rVert,\Delta t \qquad\qquad \mathbf{p}_{\text{pred}} = \mathbf{p} + \mathbf{v},\Delta t \]
It is an extrapolation: the same integration step as in the previous lesson, taken toward the future.
def predict_pose(position, velocity, q, omega, dt):
"""Extrapolates the pose by a time dt with constant linear and angular velocity."""
speed = norm(omega)
if speed > 1e-9:
q = quaternion_product(quaternion_from_axis_angle(omega, speed * dt), q)
return np.asarray(position) + np.asarray(velocity) * dt, q
omega = np.array([0.0, np.radians(120.0), 0.0]) # head turning to the left
latency, braking = 0.020, np.radians(-600.0) # the head is slowing down: -600 degrees/s^2
true_rotation = np.radians(120.0) * latency + 0.5 * braking * latency ** 2
q_true = quaternion_product(quaternion_from_axis_angle([0.0, 1.0, 0.0], true_rotation), q_head)
_, q_predicted = predict_pose(head, np.zeros(3), q_head, omega, latency)
for name, q in (("without prediction", q_head), ("with prediction", q_predicted)):
error = angle_between_orientations(q, q_true)
print(name, round(np.degrees(error), 3), round(focal * np.tan(error), 1))In this example the head does not hold its velocity: it is slowing down. Even so, the prediction reduces the error from 2.28° (32 pixels) to 0.12° (less than 2 pixels). The error that remains is that of the term the extrapolation ignores, \(\tfrac{1}{2},\alpha,\Delta t^2\), and it grows with the square of the latency: predicting works well at 20 ms and badly at 100 ms. Headsets add one last correction, reprojection: just before showing the image already drawn, they shift it with a rotation according to the most recent pose.
Lens distortion
The screens of a headset are a few centimeters from the eyes; lenses make it possible to focus on them and widen the field of view. In exchange, they deform the image: a point that should be seen at a distance \(r\) from the center of the lens is seen at a different distance, all the more so the farther it is from the center. This is a radial distortion, and it is modeled with a polynomial in \(r^2\):
\[ \mathbf{p}' = \mathbf{p},\left(1 + k_1,r^2 + k_2,r^4\right) \qquad r^2 = \lVert \mathbf{p} \rVert^2 = x^2 + y^2 \]
with \(\mathbf{p}\) measured from the center of the lens. Only even powers appear because the distortion depends on the distance to the center, not on the direction; since the vector is multiplied by a scalar, each point moves along its radius.
| Sign of \(k_1\) | Effect | Name |
|---|---|---|
| Positive | Points move away from the center, more so at the edges: straight lines bend inward | Pincushion distortion |
| Negative | Points move toward the center: straight lines bulge outward | Barrel distortion |
The lenses of a headset produce pincushion distortion. The solution is to apply the opposite distortion to the image in software before showing it, so that the lens undoes it: a pre-correction. For that we have to invert the polynomial—find the \(\mathbf{p}\) whose distortion is a given point—and there is no closed formula. It is solved by fixed-point iteration: from \(\mathbf{p}' = \mathbf{p},s(r)\) we solve for \(\mathbf{p} = \mathbf{p}'/s(r)\) and repeat, evaluating \(s\) with the previous estimate.
def radial_distortion(point, k1, k2=0.0):
"""Applies the factor 1 + k1 r^2 + k2 r^4 to the 2D point (measured from the center of the lens)."""
point = np.asarray(point, dtype=float)
r2 = dot_product(point, point)
return point * (1.0 + k1 * r2 + k2 * r2 * r2)
def correct_distortion(point, k1, k2=0.0, iterations=20):
"""Inverse of radial_distortion by fixed-point iteration."""
target = np.asarray(point, dtype=float)
p = target.copy()
for _ in range(iterations):
r2 = dot_product(p, p)
p = target / (1.0 + k1 * r2 + k2 * r2 * r2)
return p
K1, K2 = 0.22, 0.24 # headset lens (pincushion)
for r in (0.2, 0.5, 0.8):
pre = correct_distortion([r, 0.0], K1, K2)
print(r, np.round(radial_distortion([r, 0.0], K1, K2), 4), np.round(pre, 4),
np.round(radial_distortion(pre, K1, K2), 4))0.2 [0.2018 0. ] [0.1982 0. ] [0.2 0. ] 0.5 [0.535 0. ] [0.4714 0. ] [0.5 0. ] 0.8 [0.9913 0. ] [0.6901 0. ] [0.8 0. ]
Each row shows, for a point at distance \(r\) from the center: where the lens would take it (second column), where it has to be drawn to compensate (third) and the check that the lens returns that corrected point to its place (fourth). Near the center the distortion is about 1%; at \(r = 0.8\) the lens pushes the point 24% farther out, and it has to be drawn at 0.69 for it to be seen at 0.8. In practice the correction is done in a fragment shader, or by deforming a mesh onto which the image is pasted as a texture.
The pinhole camera model: intrinsics and extrinsics
We move on to augmented reality, where the camera is a physical object. The standard model is the pinhole camera: all the rays pass through one point and form the image by similar triangles, exactly the perspective projection we derived in Module 5. Computer vision writes it with a different notation and a different axis convention:
| This course (OpenGL style) | Computer vision | |
|---|---|---|
| The camera looks toward | \(-Z\) | \(+Z\) |
| Y axis | Upward | Downward (like the rows of the image) |
| World → camera | 4×4 view matrix | Extrinsics: rotation \(R\) and translation \(\mathbf{t}\), \(\mathbf{p}_c = R,\mathbf{p} + \mathbf{t}\) |
| Camera → image | Projection matrix and viewport | Intrinsics: 3×3 matrix \(K\) |
| Result | NDC and then pixels | Pixels \((u, v)\) directly |
The intrinsic matrix gathers what depends only on the camera:
\[ K = \begin{pmatrix} f_x & 0 & c_x \ 0 & f_y & c_y \ 0 & 0 & 1 \end{pmatrix} \qquad\qquad \begin{pmatrix} u,z \ v,z \ z \end{pmatrix} = K,(R,\mathbf{p} + \mathbf{t}) \quad\Longrightarrow\quad u = f_x,\frac{x_c}{z_c} + c_x \qquad v = f_y,\frac{y_c}{z_c} + c_y \]
- \(f_x\), \(f_y\): focal lengths in pixels. They say how many pixels the image of a point moves for each unit of \(x/z\). They are the \(f\) of the disparity formula.
- \((c_x, c_y)\): the principal point, the pixel where the optical axis passes through the image; ideally, the center.
The product \(K,[R \mid \mathbf{t}]\) is a 3×4 matrix that takes a homogeneous point of the world to a homogeneous pixel: the final "division by \(z\)" is our division by \(w\). And the relationship with the matrices of the course is direct: chaining the projection with the viewport we get
\[ f_x = P_{00},\frac{\text{width}}{2} \qquad f_y = P_{11},\frac{\text{height}}{2} \qquad c_x = \frac{\text{width}}{2} \qquad c_y = \frac{\text{height}}{2} \]
and the extrinsics are the view matrix with the signs of the \(Y\) and \(Z\) axes flipped, \(R = \operatorname{diag}(1, -1, -1),R_{\text{view}}\). An off-center principal point corresponds, in the language of the course, to an asymmetric frustum.
def intrinsics_from_projection(projection, width, height):
"""Matrix K equivalent to a symmetric perspective matrix plus the viewport."""
return np.array([[projection[0, 0] * width / 2.0, 0.0, width / 2.0],
[0.0, projection[1, 1] * height / 2.0, height / 2.0],
[0.0, 0.0, 1.0]])
def extrinsics_from_view(view):
"""Rotation R and translation t (computer vision convention) of a view matrix."""
flip = np.diag([1.0, -1.0, -1.0]) # flips the sign of the Y and Z axes
return flip @ view[:3, :3], flip @ view[:3, 3]
def project_with_intrinsics(K, R, t, p):
"""Pixel (u, v) at which the camera K [R | t] sees the 3D point p."""
c = K @ (R @ np.asarray(p, dtype=float) + t)
return c[:2] / c[2]
initial_view = rigid_inverse(translation_matrix(0.0, 5.0, 20.0))
projection = perspective_matrix(np.radians(60.0), 16.0 / 9.0, 1.0, 100.0)
K_game = intrinsics_from_projection(projection, 1280, 720)
R_game, t_game = extrinsics_from_view(initial_view)
print(np.round(K_game, 2))
print(R_game @ ship + t_game, np.round(project_with_intrinsics(K_game, R_game, t_game, ship), 1))The game's usual camera (60° FOV, 1280 × 720) is equivalent to a real camera with a focal length of 623.5 pixels and the principal point at the center. In its system, the ship is at \((8, 2, 14)\): 8 m to the right, 2 m downward (positive \(y\) goes down) and 14 m ahead. And it projects onto the pixel \((996.3, 449.1)\), the same one we obtained in "From Clip Space to the Screen: Viewport, Rasterization and Z-buffer" with the view-projection-viewport chain.
Estimating the pose with a marker: PnP and homography
In AR, \(K\) is known (it is calibrated once per device), but \(R\) and \(\mathbf{t}\) change every frame and have to be computed from the image. The classic formulation is the PnP problem (Perspective-n-Point): we know \(n\) points of the world \(\mathbf{p}_i\) and the pixels \((u_i, v_i)\) where they appear, and we look for \(R\) and \(\mathbf{t}\) such that \(K,(R,\mathbf{p}_i + \mathbf{t})\) reproduces those pixels. There are 6 unknowns (3 of rotation and 3 of translation) and each point contributes 2 equations: at least 3 points are needed, and in practice 4 or more are used and the error is minimized by least squares. The system is not linear in general, because the nine entries of \(R\) are not free: they must form an orthogonal matrix.
There is one case that can be solved with a linear system: when the known points lie in a plane, like the four corners of a printed marker. We choose the world system with the origin at the center of the marker, lying on the table: \(X\) and \(Z\) on the table, \(Y\) upward. A point of the marker is \((a, 0, b)\), and when it is projected the second column of \(R\) plays no part:
\[ z \begin{pmatrix} u \ v \ 1 \end{pmatrix} = K,\big(a,\mathbf{r}_1 + b,\mathbf{r}_3 + \mathbf{t}\big) = \underbrace{K \begin{pmatrix} \mathbf{r}_1 & \mathbf{r}3 & \mathbf{t} \end{pmatrix}}{H} \begin{pmatrix} a \ b \ 1 \end{pmatrix} \]
The 3×3 matrix \(H\) is called a homography: it is the projective transformation that takes the points of the plane to the image. It is only defined up to a factor (multiplying it by a constant changes neither \(u\) nor \(v\)), so we set \(h_{33} = 1\) and 8 unknowns remain. Dividing the first two rows by the third and clearing denominators, each correspondence gives two equations that are linear in the \(h_{ij}\):
\[ h_{11},a + h_{12},b + h_{13} - u,(h_{31},a + h_{32},b) = u \qquad h_{21},a + h_{22},b + h_{23} - v,(h_{31},a + h_{32},b) = v \]
Four corners give 8 equations: a system \(A,\mathbf{h} = \mathbf{b}\) like those of "Systems of Linear Equations". With more points, or with noisy measurements, it is solved by least squares with np.linalg.lstsq. Then we undo the product: \(K^{-1} H = \lambda,(\mathbf{r}_1\ \mathbf{r}_3\ \mathbf{t})\). The factor \(\lambda\) is found by requiring \(\mathbf{r}_1\) to be a unit vector, and the missing column is a cross product, \(\mathbf{r}_2 = \mathbf{r}_3 \times \mathbf{r}_1\).
def estimate_homography(plane_points, pixels):
"""3x3 homography (with h33 = 1) that takes points (a, b) of a plane to pixels (u, v)."""
rows, rhs = [], []
for (a, b), (u, v) in zip(plane_points, pixels):
rows.append([a, b, 1.0, 0.0, 0.0, 0.0, -u * a, -u * b])
rows.append([0.0, 0.0, 0.0, a, b, 1.0, -v * a, -v * b])
rhs += [u, v]
h, *_ = np.linalg.lstsq(np.array(rows), np.array(rhs), rcond=None)
return np.append(h, 1.0).reshape(3, 3)
def pose_from_homography(K, H):
"""Extrinsics (R, t) of the camera from the homography of the world plane Y = 0."""
m = np.linalg.inv(K) @ H
scale = 1.0 / norm(m[:, 0])
if m[2, 2] < 0.0: # the marker must be in front (t_z > 0)
scale = -scale
r1, r3, t = scale * m[:, 0], scale * m[:, 1], scale * m[:, 2]
return np.column_stack([r1, cross_product(r3, r1), r3]), t
K_phone = np.array([[1000.0, 0.0, 640.0], [0.0, 1000.0, 360.0], [0.0, 0.0, 1.0]])
corners = np.array([[-0.1, 0.0, 0.1], [0.1, 0.0, 0.1], [0.1, 0.0, -0.1], [-0.1, 0.0, -0.1]])
# True pose of the phone (unknown to the application): it only serves to generate the image
phone_view = look_at_matrix([0.3, 0.5, 0.6], [0.0, 0.05, 0.0])
R_true, t_true = extrinsics_from_view(phone_view)
detected = np.array([project_with_intrinsics(K_phone, R_true, t_true, c) for c in corners])
print(np.round(detected, 1))
H = estimate_homography(corners[:, [0, 2]], detected)
R_est, t_est = pose_from_homography(K_phone, H)
print(np.allclose(R_est, R_true), np.round(t_est, 4), np.round(-R_est.T @ t_est, 4))
R_noisy, t_noisy = pose_from_homography(K_phone, estimate_homography(corners[:, [0, 2]],
np.round(detected)))
print(np.round(-R_noisy.T @ t_noisy, 4), round(dot_product(R_noisy[:, 0], R_noisy[:, 2]), 4))[[472. 443.2] [701.8 520.5] [793.7 379. ] [592.8 324.9]] True [-0. 0.0415 0.8356] [0.3 0.5 0.6] [0.31 0.4906 0.6014] 0.0159
The marker is a 20 cm square; the phone (1280 × 720, focal length of 1000 pixels) photographs it from \((0.3, 0.5, 0.6)\). From the four detected pixels and \(K\) alone, the application recovers the exact rotation and the position of the camera, \(-R^T \mathbf{t} = (0.3, 0.5, 0.6)\): the rigid inverse formula.
The last line repeats the calculation with the corners rounded to the whole pixel, as a real detector would give them. The position is off by about a centimeter and the columns \(\mathbf{r}_1\) and \(\mathbf{r}_3\) no longer come out exactly perpendicular (their dot product is 0.016 instead of 0). That is why real systems detect the corners to a precision of tenths of a pixel, use many more points, re-orthogonalize the rotation and refine the pose by minimizing the reprojection error. ARCore and ARKit do not need markers: they track hundreds of natural points in the image and combine them with the IMU, but the problem they are solving underneath is this one.
Placing an object: from the screen tap to the anchor
With the pose of the camera known, the application can draw. What remains is to decide where: the user taps the screen and the scale model of the lighthouse must appear at the point of the table that lies under their finger. A pixel does not determine a 3D point, but a ray: all the points that project onto it. To obtain it, the pixel is unprojected with the inverse of the view-projection matrix:
- From the pixel to NDC, inverting the viewport.
- Two NDC points with those \(x\), \(y\) are taken: one on the near plane (\(z = -1\)) and another on the far plane (\(z = 1\)).
- They are multiplied by \((P,V)^{-1}\) and divided by \(w\): the inverse of a projection also produces \(w \ne 1\).
- The ray leaves the first one in the direction of the second.
Then the intersection of the ray with the plane of the table (ray_plane) gives the point we are looking for.
def projection_from_intrinsics(K, width, height, near, far):
"""The course's projection matrix equivalent to K (an asymmetric frustum if cx, cy are off-center)."""
return asymmetric_perspective_matrix(-K[0, 2] * near / K[0, 0], (width - K[0, 2]) * near / K[0, 0],
-(height - K[1, 2]) * near / K[1, 1], K[1, 2] * near / K[1, 1],
near, far)
def view_from_extrinsics(R, t):
"""The course's 4x4 view matrix from the computer vision extrinsics."""
flip = np.diag([1.0, -1.0, -1.0]) # the same sign flip, which is its own inverse
return affine_matrix(flip @ R, flip @ t)
def ray_from_screen(x_px, y_px, width, height, view, projection):
"""World ray (origin on the near plane, unit direction) that passes through a pixel."""
x_ndc, y_ndc = 2.0 * x_px / width - 1.0, 1.0 - 2.0 * y_px / height
vp_inverse = np.linalg.inv(projection @ view)
near = from_homogeneous(vp_inverse @ np.array([x_ndc, y_ndc, -1.0, 1.0]))
far = from_homogeneous(vp_inverse @ np.array([x_ndc, y_ndc, 1.0, 1.0]))
return near, normalize(far - near)
ar_view = view_from_extrinsics(R_est, t_est)
ar_projection = projection_from_intrinsics(K_phone, 1280, 720, 0.05, 20.0)
table = plane_from_point_normal([0.0, 0.0, 0.0], [0.0, 1.0, 0.0])
origin, direction = ray_from_screen(800.0, 500.0, 1280, 720, ar_view, ar_projection)
t_table = ray_plane(origin, direction, table)
anchor = origin + t_table * direction
print(np.round(origin, 4), np.round(direction, 4), round(t_table, 4))
print(np.round(anchor, 4) + 0.0, np.round(project_with_intrinsics(K_phone, R_est, t_est, anchor), 2))The tap on the pixel \((800, 500)\) corresponds to the point \((0.156, 0, 0.047)\) of the table, about 16 cm from the center of the marker. The check is the usual one: projected again with \(K,[R \mid \mathbf{t}]\), that point lands exactly on the tapped pixel.
That point is stored as an anchor: a fixed pose in the real world. It is, quite simply, a world matrix; virtual objects hang from it as children, with the hierarchy of "Composition of Transformations". The scale model of the lighthouse, at 1:100 scale, has as its model matrix \(M = A,S(0.01)\), with \(A\) the anchor's matrix. The essential point is that the anchor does not move when the phone moves: every frame \(R\) and \(\mathbf{t}\) change, and with them the pixel where it is drawn, but not \(A\).
anchor_matrix = translation_matrix(*anchor)
miniature_model = anchor_matrix @ scaling_matrix(0.01, 0.01, 0.01)
miniature_lamp = transform_point(miniature_model, [0.0, 12.0, 0.0])
print(np.round(miniature_lamp, 4) + 0.0)
R2, t2 = extrinsics_from_view(look_at_matrix([-0.2, 0.4, 0.7], [0.0, 0.05, 0.0]))
for name, (R, t) in (("before", (R_est, t_est)), ("after", (R2, t2))):
print(name, np.round(project_with_intrinsics(K_phone, R, t, anchor), 1),
np.round(project_with_intrinsics(K_phone, R, t, miniature_lamp), 1))The lamp of the scale model ends up 12 cm above the anchor. With the phone in its first position, the base is drawn at the tapped pixel and the lamp about 134 pixels higher up; when the user moves half a meter to the left, the two points are drawn at other pixels, but they are still the same points of the world: the lighthouse seems nailed to the table.
Occlusion and lighting consistency
For the object to seem to be there, it is not enough for the geometry to fit. Two more problems, which we only mention:
- Occlusion. If a real hand passes in front of the scale model, it must hide it. It is the z-buffer problem, with one drawback: the depth of the real world is not known. Devices estimate it with depth sensors or with the disparity between frames itself (\(Z = f,b/d\)) and write it into the z-buffer before drawing the virtual content.
- Lighting consistency. The virtual object must be lit like its surroundings: the direction and the color of the dominant light are estimated from the camera image and used in the model of "Lighting and Shading"; a shadow cast onto the plane of the table (a shadow ray against the plane, or a projection onto it) is what contributes most to making the object "have weight".
Common Mistakes and Tips
- Turning the eye cameras toward the object (toe-in). It produces vertical disparity and eye strain. The two views are parallel; what is asymmetric is the frustum.
- Using an IPD in the wrong units. If the scene is not in meters, 0.064 means nothing: an IPD that is too large makes the world look like a scale model, and one that is too small makes it look gigantic. The scale of the world matters in VR.
- Mixing camera conventions. Computer vision uses \(+Z\) forward and \(Y\) downward; the course, \(-Z\) forward and \(Y\) upward. Forgetting the sign flip produces flipped images or mirrored poses.
- Forgetting the division by \(w\) when unprojecting. The inverse of \(P,V\) returns homogeneous coordinates with \(w \ne 1\).
- Confusing the focal length in pixels with the field of view. They are related by \(f_y = \tfrac{\text{height}}{2} / \tan\tfrac{\text{fov}}{2}\); if the resolution changes, \(K\) changes.
- Applying the distortion with pixel coordinates. The polynomial works with coordinates centered on the axis of the lens and normalized; with pixels, the coefficients make no sense.
- Predicting too far ahead. The error of the extrapolation grows with the square of the time: it is a patch for latency, not a substitute for reducing it.
- Storing the position of an AR object in camera coordinates. It would move with the phone. Objects are anchored to the world.
- Tip. Check every unprojection by projecting again: the point obtained must land on the pixel you started from. It is the cheapest test and it catches almost every convention error.
Exercises
Exercise 1. A headset has a focal length of 800 pixels and the IPD is 0.064 m.
a) What is the disparity of the escort drone, 4 m away? b) An object shows a disparity of 8 pixels. How far away is it? c) If the disparity is perceived with an uncertainty of ±0.5 pixels, between what distances can an object that shows 12.8 pixels (4 m) be? And one that shows 1.28 pixels (40 m)?
Exercise 2. A camera has \(f_x = f_y = 1000\), \(c_x = 640\), \(c_y = 360\), and is at the origin with no rotation (\(R = I\), \(\mathbf{t} = \mathbf{0}\), computer vision convention).
a) At which pixel is the point \((0.2, -0.1, 2)\) seen? Is it above or below the center of the image? b) What is the direction of the ray that corresponds to the pixel \((940, 560)\)? c) The ground is the plane \(y = 0.4\) (remember: \(Y\) downward). At what point does that ray hit it?
Exercise 3. In the AR application, the user has moved and the detector now gives these corners of the marker (in the same order): \((554.0, 436.9)\), \((726.0, 436.9)\), \((714.5, 360.0)\) and \((565.5, 360.0)\).
a) Estimate the pose of the camera. Where is the phone? b) At which pixels do the base and the lamp of the scale model have to be drawn now? c) The user taps the pixel \((640, 30)\), in the upper part of the image. Which point of the table's plane is under their finger? Is it reasonable to create an anchor there?
Solutions
Solution 1.
a) \(d = \dfrac{f,b}{Z} = \dfrac{800 \cdot 0.064}{4} = \dfrac{51.2}{4} = 12.8\) pixels.
b) \(Z = \dfrac{51.2}{8} = 6.4\) m.
c) With 12.8 ± 0.5 pixels: between \(51.2/13.3 = 3.85\) m and \(51.2/12.3 = 4.16\) m, a range of 31 cm. With 1.28 ± 0.5 pixels: between \(51.2/1.78 = 28.8\) m and \(51.2/0.78 = 65.6\) m, a range of almost 37 m. The uncertainty in depth grows approximately with the square of the distance.
Solution 2.
a) \(u = 1000 \cdot \dfrac{0.2}{2} + 640 = 740\); \(v = 1000 \cdot \dfrac{-0.1}{2} + 360 = 310\). Since \(v < 360\) and the rows grow downward, the point is seen above the center: it has a negative \(y\), and in this convention that is "up".
b) We invert \(K\): \(x/z = \dfrac{940 - 640}{1000} = 0.3\), \(y/z = \dfrac{560 - 360}{1000} = 0.2\). The ray leaves the origin with direction \((0.3, 0.2, 1)\).
c) The points of the ray are \(s,(0.3, 0.2, 1)\). We impose \(y = 0.4\): \(0.2,s = 0.4\), \(s = 2\). The point is \((0.6, 0.4, 2)\).
Solution 3.
print(800.0 * 0.064 / 4.0, 51.2 / 8.0, np.round([51.2 / 13.3, 51.2 / 12.3, 51.2 / 1.78, 51.2 / 0.78], 2))
K_ex = np.array([[1000.0, 0.0, 640.0], [0.0, 1000.0, 360.0], [0.0, 0.0, 1.0]])
print(project_with_intrinsics(K_ex, np.eye(3), np.zeros(3), [0.2, -0.1, 2.0]),
np.linalg.inv(K_ex) @ [940.0, 560.0, 1.0])
new_corners = np.array([[554.0, 436.9], [726.0, 436.9], [714.5, 360.0], [565.5, 360.0]])
R3, t3 = pose_from_homography(K_phone, estimate_homography(corners[:, [0, 2]], new_corners))
print(np.round(-R3.T @ t3, 2) + 0.0)
print(np.round(project_with_intrinsics(K_phone, R3, t3, anchor), 0),
np.round(project_with_intrinsics(K_phone, R3, t3, miniature_lamp), 0))
origin3, direction3 = ray_from_screen(640.0, 30.0, 1280, 720, view_from_extrinsics(R3, t3),
ar_projection)
t3_table = ray_plane(origin3, direction3, table)
print(np.round(direction3, 3) + 0.0, round(t3_table, 2), np.round(origin3 + t3_table * direction3, 2) + 0.0)12.8 6.4 [ 3.85 4.16 28.76 65.64] [740. 310.] [0.3 0.2 1. ] [0. 0.6 1.1] [769. 414.] [775. 324.] [ 0. -0.143 -0.99 ] 4.12 [ 0. 0. -3.03]
a) The camera is at \((0, 0.60, 1.10)\): the user has moved to face the marker head-on, somewhat higher and considerably farther away than before. The fact that the corners appear in two horizontal rows, with the far side shorter, already suggested it.
b) The base of the scale model is drawn at the pixel \((769, 414)\) and the lamp at \((775, 324)\).
c) The ray descends very little (its \(y\) component is \(-0.143\)) and reaches the plane 4.12 m from the phone, at the point \((0, 0, -3.03)\): three meters beyond the marker. Mathematically there is an intersection, because a plane is infinite; physically, it is almost certain that the table does not reach that far. That is why AR applications do not use the infinite plane, but the portion they have detected, and they also reject very grazing rays, for which an error of one pixel shifts the point by tens of centimeters. If the ray pointed above the horizon, ray_plane would return None.
Conclusion
Virtual and augmented reality are the same camera pipeline traveled in opposite directions. In VR we start from a pose—position and quaternion, integrated from the angular velocity and extrapolated to compensate for latency—and generate two view matrices separated by the interpupillary distance; the disparity \(d = f,b/Z\) between the two images is what the brain reads as depth; the frustums of each eye are asymmetric and the deformation of the lenses is compensated with the inverse radial polynomial. In AR we start from the image: the real camera is the perspective matrix written as \(K,[R \mid \mathbf{t}]\); the pose is deduced from known points (PnP), which for a planar marker reduces to a homography solvable by least squares; and a tap on the screen becomes, with the inverse of \(P,V\), a ray whose intersection with a plane defines an anchor in the world. mini3d gains stereo_views, asymmetric_perspective_matrix, predict_pose, radial_distortion, correct_distortion, intrinsics_from_projection, extrinsics_from_view, project_with_intrinsics, estimate_homography, pose_from_homography, projection_from_intrinsics, view_from_extrinsics and ray_from_screen.
In these last two lessons the motion came from outside: from the laws of physics or from a user's head. The third source remains, the oldest in the trade: designed motion, the kind an animator decides frame by frame. In the next lesson, "3D Animation", we will make transformations depend on time in a controlled way: keyframes, easing curves, smooth trajectories, skeletons and the deformation of a mesh by its bones.
