> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Homogeneous coordinates and projective points

> How one extra coordinate turns rotation and translation into a single matrix.

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pantelis/eng-ai-agents/blob/main/notebooks/sensor-models/homogeneous-coordinates/index.ipynb)

![Railway tracks receding to the horizon.](https://mintcdn.com/aegeanaiinc/y4QJG_qxjY_yF61c/aiml-common/lectures/sensor-models/homogeneous-coordinates/images/train-tracks.jpeg?fit=max\&auto=format\&n=y4QJG_qxjY_yF61c\&q=85\&s=dea4eec31a3439fc3c52fba6dc5c709b)

*Under perspective projection, the parallel tracks appear to meet at a point on the horizon.*

A photograph maps points from three-dimensional Euclidean space to a two-dimensional image plane. Perspective projection does not preserve circles, distances, angles or ratios of distances. A circle can appear as an ellipse. Straight lines stay straight, while parallel lines can appear to meet.

The camera models in this chapter describe that mapping with matrices that act on *homogeneous coordinates*. This section introduces them in the plane. Homogeneous coordinates append one entry to each vector. With that entry you can tell points from displacements, write a rotation and a translation as one matrix, and represent the point where two parallel lines meet.

## Points and displacements

In the plane, a rotation is linear: $p' = Rp$. A translation $p' = p + t$ is not linear, because a linear map sends the zero vector to zero. A rotation followed by a translation therefore has the form

$p' = Rp + t.$

Append one coordinate. A finite point gets a 1 and a displacement vector gets a 0:

$\tilde p = \begin{bmatrix} p_x \\ p_y \\ 1 \end{bmatrix}, \qquad \tilde v = \begin{bmatrix} v_x \\ v_y \\ 0 \end{bmatrix}.$

Rotation and translation now fit in one $3 \times 3$ matrix:

$$
\begin{aligned}
T &= \begin{bmatrix} R & t \\ 0 & 1 \end{bmatrix}, \\
T\tilde p &= \begin{bmatrix} Rp + t \\ 1 \end{bmatrix}, \\
T\tilde v &= \begin{bmatrix} Rv \\ 0 \end{bmatrix}.
\end{aligned}
$$

The translation column multiplies the last coordinate. It therefore moves points, which have $w = 1$, and has no effect on displacements, which have $w = 0$. The last coordinate marks whether a column is a point or a displacement, and it does not measure position along any axis. For example, translating by $t = (2, 1)^T$ sends the point $(1, 1)$ to $(3, 2)$, while the displacement $(1, 1)$ stays $(1, 1)$.

> [accordion] Code
>
> ```python theme={null}
> import numpy as np
> import matplotlib.pyplot as plt
> from cycler import cycler
> from matplotlib_inline.backend_inline import set_matplotlib_formats
> set_matplotlib_formats("svg")
> FIG_GRAY = "#808080"
> FIG_COLORS = ["#0072B2", "#D55E00", "#009E73", "#cb77a6", "#c28600", "#1d99e0", "#7f7f7f"]
> plt.rcParams.update({
>     "figure.facecolor": "none", "axes.facecolor": "none",
>     "savefig.facecolor": "none", "savefig.transparent": True,
>     "text.color": FIG_GRAY, "axes.labelcolor": FIG_GRAY, "axes.edgecolor": FIG_GRAY,
>     "xtick.color": FIG_GRAY, "ytick.color": FIG_GRAY,
>     "grid.color": FIG_GRAY, "grid.alpha": 0.25,
>     "legend.facecolor": "none", "legend.edgecolor": FIG_GRAY, "legend.framealpha": 0,
>     "axes.prop_cycle": cycler(color=FIG_COLORS),
>     "svg.hashsalt": "aiml", "svg.fonttype": "path",
> })
>
> # Translate by t = (2, 1): the point (1, 1) moves, the displacement (1, 1) does not.
> p = np.array([1.0, 1.0, 1.0])  # point, w = 1
> v = np.array([1.0, 1.0, 0.0])  # displacement, w = 0
> T = np.array([[1.0, 0.0, 2.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]])
> print("T p =", T @ p, "   T v =", T @ v)
> assert np.allclose(T @ p, [3, 2, 1])
> assert np.allclose(T @ v, [1, 1, 0])
> ```

```output theme={null}
T p = [3. 2. 1.]    T v = [1. 1. 0.]
```

The figure below applies a rigid transformation to a point $p$ and to a displacement $v$ drawn from it. Use the sliders to change the rotation and the translation. The point is first rotated to $Rp$ (the hollow circle) and then shifted by $t$ (the dashed arrow) to $Tp$. The displacement is only rotated, so $t$ changes neither its length nor its direction. The figure still draws it from the moved point, because its tip $p + v$ is a point and moves to $Tp + Rv$.

*A rigid transformation $T$ applied to the point $p = (1.5, 0.5)$ and the displacement $v = (1, 0.75)$. The readouts give $T\tilde p$ and $T\tilde v$ with their last coordinate.*

## Coordinates depend on the frame

![A point expressed in two different coordinate frames.](https://mintcdn.com/aegeanaiinc/y4QJG_qxjY_yF61c/aiml-common/lectures/sensor-models/homogeneous-coordinates/images/coord-sys-point.svg?fit=max\&auto=format\&n=y4QJG_qxjY_yF61c\&q=85\&s=20adce58b9433276074bbf3682f47794)

*The solid and dashed axes define two coordinate frames, so the same point has different coordinates in each. Its position in space does not change.*

An *affine frame* is an origin $o$ together with a basis $B = [u_1 \; u_2]$ of displacement vectors. A point has frame coordinates $q$ when

$$
\begin{aligned}
p_{\text{world}} &= o + Bq, \\
\tilde p_{\text{world}} &= T_{\text{world} \leftarrow \text{frame}} \, \tilde q, \\
T_{\text{world} \leftarrow \text{frame}} &= \begin{bmatrix} B & o \\ 0 & 1 \end{bmatrix}.
\end{aligned}
$$

This is a *passive* change of coordinates: the physical point does not move, only its description does. An *active* transformation uses the same kind of matrix but moves the point relative to a fixed frame. Writing the source and destination frames as subscripts on every matrix, as in $T_{\text{world} \leftarrow \text{frame}}$, shows which reading is meant.

When the basis is orthonormal, $B = R$ is a rotation, and the inverse goes the other way:

$T_{\text{frame} \leftarrow \text{world}} = T_{\text{world} \leftarrow \text{frame}}^{-1} = \begin{bmatrix} R^T & -R^T o \\ 0 & 1 \end{bmatrix}.$

> [!NOTE]
>
> An affine space of dimension $n$ consists of a set of points $\mathcal{A}$ and an associated vector space $V$ of dimension $n$. It supports two operations:
>
> * Point subtraction: $p - q \in V$ gives a vector.
> * Point translation: $p + v \in \mathcal{A}$ moves a point by a vector.
>
> You cannot add two points, and there is no zero point. An affine space has no fixed origin or basis until you choose a frame. A vector space has a built-in origin, the zero vector, and is closed under linear combinations. Euclidean space adds an inner product, which defines lengths and angles.

The code below expresses the point $q = (1, 0.5)$ of a frame rotated by $35°$ in world coordinates, then converts it back with the inverse matrix.

> [accordion] Code
>
> ```python theme={null}
> angle = np.deg2rad(35)
> R = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
> o = np.array([2.0, 1.0])  # frame origin in world coordinates
> q = np.array([1.0, 0.5])  # coordinates of the point in the frame
>
> T_world_frame = np.eye(3)
> T_world_frame[:2, :2] = R
> T_world_frame[:2, 2] = o
> p_world = (T_world_frame @ np.append(q, 1.0))[:2]
>
> T_frame_world = np.eye(3)
> T_frame_world[:2, :2] = R.T
> T_frame_world[:2, 2] = -R.T @ o
> q_back = (T_frame_world @ np.append(p_world, 1.0))[:2]
>
> print("frame coordinates q:", q, "  world coordinates:", np.round(p_world, 3))
> assert np.allclose(p_world, o + R @ q)
> assert np.allclose(q_back, q)
> assert np.allclose(T_frame_world @ T_world_frame, np.eye(3))
> ```

```output theme={null}
frame coordinates q: [1.  0.5]   world coordinates: [2.532 1.983]
```

![Output from cell 3](https://mintcdn.com/aegeanaiinc/y4QJG_qxjY_yF61c/aiml-common/lectures/sensor-models/homogeneous-coordinates/images/cell_3_output_1.svg?fit=max\&auto=format\&n=y4QJG_qxjY_yF61c\&q=85\&s=3fee535f064d44453f3fbd8d5261f03c)

*One physical point and two frames. The gray arrows are the world axes, the blue arrows the frame's basis, and the dashed line runs from the frame origin to the point.*

## Homogeneous scale and projective points

In projective geometry, a point is a class of nonzero vectors that differ only by scale:

$[x : y : w] = [\lambda x : \lambda y : \lambda w], \qquad \lambda \ne 0.$

When $w \ne 0$, the Cartesian point is $(x/w, \, y/w)$. The vectors $(2, 4, 2)$ and $(-1, -2, -1)$ therefore describe the same finite point $(1, 2)$. Each class is a line through the origin of $\mathbb R^3$, and the plane $w = 1$ cuts it at the Cartesian point.

When $w = 0$, the class $[d_x : d_y : 0]$ has no Cartesian point. It is an *ideal point*, a direction on the line at infinity. Adding these points gives the *projective plane*, in which every pair of distinct lines meets in exactly one point. Two parallel lines meet at the ideal point of their common direction (Hartley & Zisserman, 2004). The earlier sections used the same vector $(d_x, d_y, 0)^T$ for a displacement. Under a rigid or affine transformation it behaves as a displacement, and under a projective transformation it is a point at infinity.

Three-dimensional space works the same way with four coordinates. A point $(x, y, z)$ becomes $(x, y, z, 1)$, and

$(x, y, z, w) \equiv (x/w, \; y/w, \; z/w), \qquad w \ne 0.$

A camera maps these 3D homogeneous points to 2D homogeneous image points with a $3 \times 4$ matrix. The camera divides by the last coordinate after the matrix product. For a camera that coordinate is the depth of the point, so the division makes distant objects appear smaller. The [pinhole model](https://aegean.ai/aiml-common/lectures/sensor-models/cameras/pinhole-model.md) builds that matrix.

## Which properties a transformation keeps

All of the following act on column vectors $\tilde p = (x, y, 1)^T$.

| Family | Matrix | Preserves |
| - | - | - |
| Rigid, $SE(2)$ | $\begin{bmatrix} R & t \\ 0 & 1 \end{bmatrix}$, $R \in SO(2)$ | distances, angles, orientation |
| Similarity | $\begin{bmatrix} sR & t \\ 0 & 1 \end{bmatrix}$, $s > 0$ | angles, ratios of distances |
| Affine | $\begin{bmatrix} A & t \\ 0 & 1 \end{bmatrix}$, $\det A \ne 0$ | parallel lines, ratios along a line |
| Projective | $H \in GL(3)$, up to scale | straight lines, cross-ratio |

With these conventions the families are nested: rigid $\subset$ similarity $\subset$ affine $\subset$ projective. Each family keeps fewer properties than the one before it. A projective transformation, or *homography*, keeps lines straight but can make parallel lines converge, which is what the photograph of the tracks shows. Singular matrices collapse the plane and are left out of these groups.

To apply a homography, compute $z = H\tilde p$ and divide: $(z_1/z_3, \, z_2/z_3)$, as long as $z_3 \ne 0$. The first three families have a last row of $(0, 0, 1)$, so $z_3 = 1$ and the division does nothing. For a homography, $z_3$ depends on the point, so the division makes the map nonlinear in Cartesian coordinates.

The code below applies one transformation from each family to the unit square and checks which properties each one keeps.

> [accordion] Code
>
> ```python theme={null}
> def transform_points(H, xy):
>     """Apply a 3x3 homogeneous matrix to Cartesian points and divide by w."""
>     points = np.column_stack([xy, np.ones(len(xy))])
>     z = (H @ points.T).T
>     if np.any(np.isclose(z[:, 2], 0.0)):
>         raise ValueError("a point maps to the line at infinity")
>     return z[:, :2] / z[:, 2:3]
>
>
> def affine(A, t):
>     H = np.eye(3)
>     H[:2, :2] = A
>     H[:2, 2] = t
>     return H
>
>
> square = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]], dtype=float)
> a = np.deg2rad(35)
> R = np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]])
> transforms = {
>     "Rigid": affine(R, [1.2, 0.6]),
>     "Similarity": affine(1.5 * R, [0.7, 0.4]),
>     "Affine": affine([[1.2, 0.6], [0.15, 0.9]], [0.8, 0.5]),
>     "Projective": np.array([[1.2, 0.2, 0.5], [0.1, 1.0, 0.3], [0.32, 0.22, 1.0]]),
> }
> moved = {name: transform_points(H, square) for name, H in transforms.items()}
>
>
> def side_lengths(xy):
>     return np.linalg.norm(np.diff(xy, axis=0), axis=1)
>
>
> def opposite_sides_parallel(xy):
>     e = np.diff(xy, axis=0)
>     cross = lambda u, w: u[0] * w[1] - u[1] * w[0]
>     return bool(np.isclose(cross(e[0], e[2]), 0) and np.isclose(cross(e[1], e[3]), 0))
>
>
> for name, xy in moved.items():
>     print(f"{name:10s} sides {np.round(side_lengths(xy), 3)}  parallel: {opposite_sides_parallel(xy)}")
>
> assert np.allclose(side_lengths(moved["Rigid"]), 1.0)
> assert np.allclose(side_lengths(moved["Similarity"]), 1.5)
> assert opposite_sides_parallel(moved["Affine"])
> assert not opposite_sides_parallel(moved["Projective"])
> ```

```output theme={null}
Rigid      sides [1. 1. 1. 1.]  parallel: True
Similarity sides [1.5 1.5 1.5 1.5]  parallel: True
Affine     sides [1.209 1.082 1.209 1.082]  parallel: True
Projective sides [0.788 0.608 0.678 0.769]  parallel: False
```

![Output from cell 5](https://mintcdn.com/aegeanaiinc/y4QJG_qxjY_yF61c/aiml-common/lectures/sensor-models/homogeneous-coordinates/images/cell_5_output_1.svg?fit=max\&auto=format\&n=y4QJG_qxjY_yF61c\&q=85\&s=8f9ba77cf5a6a3a483b7da35b5287289)

*The unit square (dashed) under one transformation from each family. The rigid image keeps side length 1, the similarity scales every side by 1.5, the affine image is a parallelogram, and the projective image is a general quadrilateral with no parallel sides.*

## Composing transformations

If $T_{A \leftarrow B}$ maps coordinates in frame $B$ to frame $A$, and $T_{B \leftarrow C}$ maps frame $C$ to frame $B$, then

$T_{A \leftarrow C} = T_{A \leftarrow B} \, T_{B \leftarrow C}.$

The product is valid because the inner labels match: $T_{A \leftarrow B}$ takes coordinates in $B$, and $T_{B \leftarrow C}$ produces coordinates in $B$. The reversed product $T_{B \leftarrow C} T_{A \leftarrow B}$ does not correspond to any chain of frames. It is also a different matrix in general, because matrix multiplication does not commute. For example, rotating and then translating moves a point to a different place than translating and then rotating.

In the code below, frame $B$ is rotated by $90°$ and shifted by one unit in $A$, and frame $C$ is shifted two units along the $x$ axis of $B$. The origin of $C$ lands at $(1, 2)$ in $A$. The reversed product gives a different point.

> [accordion] Code
>
> ```python theme={null}
> def se2(theta_deg, tx, ty):
>     a = np.deg2rad(theta_deg)
>     return affine([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]], [tx, ty])
>
>
> T_AB = se2(90, 1.0, 0.0)   # frame B expressed in frame A
> T_BC = se2(0, 2.0, 0.0)    # frame C expressed in frame B
> p_C = np.array([0.0, 0.0, 1.0])  # origin of frame C
>
> print("T_AB T_BC p_C =", T_AB @ T_BC @ p_C)
> print("T_BC T_AB p_C =", T_BC @ T_AB @ p_C)
> assert np.allclose(T_AB @ T_BC @ p_C, [1, 2, 1])
> assert not np.allclose(T_AB @ T_BC, T_BC @ T_AB)
> ```

```output theme={null}
T_AB T_BC p_C = [1. 2. 1.]
T_BC T_AB p_C = [3. 0. 1.]
```

In three dimensions the same construction uses $4 \times 4$ matrices with $R \in SO(3)$ and $t \in \mathbb R^3$. They form the group $SE(3)$ of rigid motions (Kevin M. Lynch, 2017). The camera models that follow use it for the camera pose, and the [motion representations](https://aegean.ai/aiml-common/lectures/motion-algebras/motion-representations/index.md) section uses it for robot links.

## Exercises

1. Why does $T(1, 0, 0)^T$ ignore the translation column, while $T(1, 0, 1)^T$ includes it?
2. Show numerically that $[2 : 4 : 2]$ and $[-1 : -2 : -1]$ are the same projective point.
3. A square becomes a parallelogram. Which transformation families could have produced it, and which measurements are unchanged?
4. Why is $T_{A \leftarrow B} T_{B \leftarrow C}$ meaningful, while the reversed product generally is not?
5. Why can a homography make two parallel lines appear to converge?

## References

* Hartley, R., Zisserman, A. (2004). *Multiple View Geometry in Computer Vision*.
* Kevin M. Lynch, F. (2017). *Modern Robotics*. [Link](https://hades.mech.northwestern.edu/images/7/7f/MR.pdf)

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/sensor-models/homogeneous-coordinates).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.