Transforming images with matrices

Week 1 — Transforming images with matrices

Quantitative biology and integrative omics

About this lecture

In Matrices as transformations a matrix moved a handful of points. Today the same matrices move a whole image — a micrograph of a cell, 19 200 pixels at once.

  • An image is a 2 × N matrix of points, one pixel per column.
  • Rotation, scaling, and two new ones: shear and reflection — each read off from the matrix columns.
  • Why we multiply matrices: a pipeline of steps becomes one matrix, applied once — and the order of the steps shows.
  • Biology: undoing a misalignment between two images of the same specimen with solve(A).

You need the jpeg package: install.packages("jpeg").

An image is a matrix of points

A greyscale image is a grid of intensities. Each pixel sits at a coordinate (x, y), so the whole image is a 2 × N matrix of points — one pixel per column, exactly like a dataset of samples.

img <- jpeg::readJPEG("msc-small.jpg")            # 160 x 120 grey levels, 0..1
img <- t(img[nrow(img):1, ])                      # flip so up is up; now img[x, y]
xy  <- t(expand.grid(1:nrow(img), 1:ncol(img)))   # 2 x 19200: one pixel per COLUMN
col <- gray(img)                                  # the grey level of each pixel
plot(t(xy), col = col, pch = 15, asp = 1)

Download msc-small.jpg. Image: transmission electron micrograph of a mesenchymal stem cell, Robert M. Hunt, CC BY 3.0, via Wikimedia Commons.

Rotating an image

The rotation matrix R(\theta) from Matrices as transformations, applied to the positions of all 19 200 pixels using a single %*%:

theta <- pi/6                       # 30 degrees
R <- matrix(c(cos(theta), -sin(theta),
              sin(theta),  cos(theta)), nrow = 2, byrow = TRUE)
plot(t(R %*% xy), col = col, pch = 15, asp = 1)

Image: Robert M. Hunt, CC BY 3.0, via Wikimedia Commons.

A shear tips one axis over; the columns show which one

A shear (skew) slides each row sideways in proportion to its height:

H = \begin{pmatrix} 1 & 0.5 \\ 0 & 1 \end{pmatrix}: \quad H\begin{pmatrix} x \\ y \end{pmatrix} = \begin{pmatrix} x + 0.5\,y \\ y \end{pmatrix}

H <- matrix(c(1, 0.5,
              0, 1), nrow = 2, byrow = TRUE)
plot(t(H %*% xy), col = col, pch = 15, asp = 1)

The x-axis stays put (column 1 = (1,0)); the y-axis tips over to column 2 = (0.5, 1).

Image: Robert M. Hunt, CC BY 3.0, via Wikimedia Commons.

A matrix’s columns predict what it does to the image

Every panel is plot(t(A %*% xy), ...) with a different A. Predict each one from its columns first.

  • Reflection diag(c(-1, 1)): flips x — the cell is now mirrored.
  • Singular matrix(c(1, 1, 0.5, 0.5), 2, byrow = TRUE): both columns point the same way, so the whole image collapses onto a line. Information is lost and cannot be undone.
  • The area changes by the factor det(A) — 1 for rotation, shear and diag(c(2, 0.5)); −1 for the reflection (flipped); 0 for the singular matrix. See the determinant slide in Matrices as transformations.

Image: Robert M. Hunt, CC BY 3.0, via Wikimedia Commons.

Try it: transform a cell image

Rotating then shearing gives a different image than the reverse

Same two matrices, R (rotate 30°) and H (shear), applied in the two possible orders:

plot(t(H %*% R %*% xy), col = col, pch = 15, asp = 1)   # rotate, then shear
plot(t(R %*% H %*% xy), col = col, pch = 15, asp = 1)   # shear, then rotate

Image: Robert M. Hunt, CC BY 3.0, via Wikimedia Commons.

Multiplying the matrices first moves every pixel only once

Rotate, then shear, then resize. Either move every pixel three times, or multiply the three small matrices first and move every pixel once:

S <- diag(c(1.5, 0.75))                 # resize: wider and flatter
out1 <- S %*% (H %*% (R %*% xy))        # three passes over 19 200 pixels
M    <- S %*% H %*% R                   # one 2 x 2 matrix for the whole pipeline
out2 <- M %*% xy                        # one pass
all.equal(out1, out2)                   # TRUE
  • A whole chain of transformations is still just one 2 × 2 matrix M = SHR.
  • Combining costs a few multiplications of 2 × 2 matrices; the image is touched once. With millions of pixels (or genes), that matters.

Image: Robert M. Hunt, CC BY 3.0, via Wikimedia Commons.

solve(A) undoes the rotation of a tilted slide scan

A slide was scanned at an angle: all we have is the tilted scan. The label should be horizontal, and it is tilted by 20°, so the scanner applied a rotation A = R(20°) to every pixel. Its inverse undoes it — solve(A) from Linear systems in R.

theta <- pi/9                   # 20 degrees: read off from the tilted label
A <- matrix(c(cos(theta), -sin(theta),
              sin(theta),  cos(theta)), nrow = 2, byrow = TRUE)
restored <- solve(A) %*% scan   # scan: the 2 x N pixel positions of the tilted image

Image: Robert M. Hunt, CC BY 3.0, via Wikimedia Commons.

Summary

Concept Key fact R
Image as points pixel coordinates as a 2 × N matrix; colours ride along xy, col
Transform an image one %*% moves every pixel plot(t(A %*% xy), ...)
Shear one axis tips over: column 2 = (k, 1) matrix(c(1,k,0,1),2,byrow=TRUE)
Reflection mirror image; \det = -1 diag(c(-1, 1))
Singular columns parallel → image collapses to a line; cannot be undone det(A) == 0
Order HR \neq RH: rightmost acts first H %*% R vs R %*% H
Pipeline many steps = one product matrix, applied once M <- S %*% H %*% R
Undo inverse transformation solve(A)

Next (Compensation & spectral unmixing): undoing the colour mixing in flow cytometry with solve().