Canvas Transform Domains: Inverse Matrices and Spectral Restoration
This article walks through a browser-based experiment that lets you apply a forward transform to an image, draw on the transformed result, and then restore the original image. It covers five transform modes—matrix inversion, magnitude spectrum, phase spectrum, joint spectrum, and row derivatives—explaining their mathematical foundations, reversibility limits, and JavaScript implementations. You’ll learn the practical details of Gaussian–Jordan elimination, 2D FFT, gradient-domain reconstruction, and the brush-based editing workflow, including undo/redo and performance considerations. The goal is to help you understand exactly why some transforms are perfectly invertible while others are only approximate after user edits.
Introduction
This article presents a set of interactive browser tools that let you complete the full cycle of forward transformation, user scribbling, and inverse restoration on an image. The underlying mathematics involves matrix inversion, the Fourier transform, and finite differences. Before diving into code, we need to understand when each operation can be reversed. The table below summarizes the five modes and their reversibility boundaries.
| Mode | Forward Transform | Inverse Transform | Reversibility Boundary |
|---|---|---|---|
| Inverse Matrix | Compute the inverse T = A⁻¹ of the image matrix A | Compute the inverse of the scribbled T′ | Matrix must be square and non‑singular; unstable when the condition number is large |
| Magnitude Spectrum | 2D FFT, keep only the magnitude | Reconstruct using the original phase and the modified magnitude | Phase must be fully preserved; otherwise exact restoration is impossible |
| Phase Spectrum | 2D FFT, keep only the phase angle | Set magnitudes to 1, inverse FFT, take the real part | Approximate restoration; scribbling destroys conjugate symmetry |
| Joint Spectrum | Keep both magnitude and phase | Combine into complex numbers, inverse FFT | Exact when untouched; after scribbling, taking the real part is approximate |
| Row Derivative | Difference along each row | Cumulative sum along each row | Exact when untouched; after scribbling, errors propagate to the right along rows |
Before any transform, the image is either cropped to a square (for matrix inversion) or zero‑padded to a power‑of‑two size (for FFT modes). Padding changes the actual dimensions, so the program records the original width and height and crops back after restoration.
Data Structure and Grayscale Preprocessing
All transforms share a simple 2D matrix class. Values are stored in a Float64Array because FFT intermediate results require high precision. For display, values are normalized to 0–255.
class Matrix2D {constructor(w, h) {this.w = w;this.h = h;this.data = new Float64Array(w * h);}get(x, y) {return this.data[y * this.w + x];}set(x, y, val) {this.data[y * this.w + x] = val;}clone() {const m = new Matrix2D(this.w, this.h);m.data.set(this.data);return m;}}function grayscaleFromImageData(imgData) {const { width: w, height: h, data } = imgData;const gray = new Matrix2D(w, h);for (let y = 0; y < h; y++) {for (let x = 0; x < w; x++) {const i = (y * w + x) * 4;gray.set(x, y, 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2]);}}return gray;}
The grayscale weights follow ITU‑R BT.601. Green has the highest weight because human vision is most sensitive to green light.
Mode 1: Gaussian–Jordan Elimination for Matrix Inversion
This mode uses an augmented matrix [A | I]. The left half holds A, the right half the identity matrix. After elimination, the left half becomes the identity and the right half becomes A⁻¹. Partial pivoting reduces round‑off errors amplified by division.
function invertMatrix(src) {const n = src.w;if (n !== src.h) throw new Error('Matrix must be square');// Augmented matrix with width 2n and height n: left half A, right half identity Iconst aug = new Matrix2D(2 * n, n);for (let y = 0; y < n; y++) {for (let x = 0; x < n; x++) aug.set(x, y, src.get(x, y));aug.set(n + y, y, 1);}for (let col = 0; col < n; col++) {// Partial pivoting: find the row with the largest absolute value in this columnlet maxRow = col;let maxVal = Math.abs(aug.get(col, col));for (let row = col + 1; row < n; row++) {const v = Math.abs(aug.get(col, row));if (v > maxVal) { maxVal = v; maxRow = row; }}if (maxVal < 1e-12) throw new Error('Matrix is singular and cannot be inverted');// Swap rowsif (maxRow !== col) {for (let x = 0; x < 2 * n; x++) {const tmp = aug.get(x, col);aug.set(x, col, aug.get(x, maxRow));aug.set(x, maxRow, tmp);}}// Normalize the pivot rowconst pivot = aug.get(col, col);for (let x = 0; x < 2 * n; x++) aug.set(x, col, aug.get(x, col) / pivot);// Eliminate other rows in the current columnfor (let row = 0; row < n; row++) {if (row === col) continue;const factor = aug.get(col, row);if (factor === 0) continue;for (let x = 0; x < 2 * n; x++) {aug.set(x, row, aug.get(x, row) - factor * aug.get(x, col));}}}const inv = new Matrix2D(n, n);for (let y = 0; y < n; y++)for (let x = 0; x < n; x++) inv.set(x, y, aug.get(n + x, y));return inv;}
The fixed threshold 1e-12 is appropriate when input values have comparable magnitudes. If the matrix elements vary greatly in scale, a relative threshold – for example, the maximum element times machine epsilon – should be used instead.
Scribbling and restoration: The canvas displays T = A⁻¹. The user scribbles on T to obtain T′, and restoration computes invertMatrix(T′). When untouched, invertMatrix(invertMatrix(A)) should equal A, which you can verify with a unit test.
Condition number detection: The infinity norm of a matrix is the maximum row sum of absolute values. The condition number can be estimated as cond = ‖A‖∞ × ‖A⁻¹‖∞.
function infNorm(m) {let best = 0;for (let y = 0; y < m.h; y++) {let rowSum = 0;for (let x = 0; x < m.w; x++) rowSum += Math.abs(m.get(x, y));if (rowSum > best) best = rowSum;}return best;}function conditionNumber(a, invA) {return infNorm(a) * infNorm(invA);}
After testing on real images, you might set a threshold of 1e6 as a starting point. When the condition number exceeds the threshold, the interface should indicate “approximate restoration”. Truncated SVD can be used as an alternative, but it yields an approximate solution and cannot be claimed to be exactly the original.
Modes 2–4: Two‑Dimensional FFT
JavaScript has no built‑in FFT, so we implement one. The 1D FFT below uses a recursive divide‑and‑conquer approach and requires an input length that is a power of two.
class Complex {constructor(re, im) { this.re = re; this.im = im; }}const cAdd = (a, b) => new Complex(a.re + b.re, a.im + b.im);const cSub = (a, b) => new Complex(a.re - b.re, a.im - b.im);const cMul = (a, b) => new Complex(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re);// Input length must be a power of twofunction fft1D(input) {const n = input.length;if (n === 1) return [input[0]];const even = [], odd = [];for (let i = 0; i < n; i += 2) {even.push(input[i]);odd.push(input[i + 1]);}const fe = fft1D(even);const fo = fft1D(odd);const out = new Array(n);for (let k = 0; k < n / 2; k++) {const angle = -2 * Math.PI * k / n;const t = cMul(new Complex(Math.cos(angle), Math.sin(angle)), fo[k]);out[k] = cAdd(fe[k], t);out[k + n / 2] = cSub(fe[k], t);}return out;}
The 2D FFT first applies a 1D FFT to each row, then to each column. The grid is organized as grid[y][x].
function fft2D(grid) {const H = grid.length, W = grid[0].length;const rows = grid.map(row => fft1D(row));const out = Array.from({ length: H }, () => new Array(W));for (let x = 0; x < W; x++) {const col = [];for (let y = 0; y < H; y++) col.push(rows[y][x]);const f = fft1D(col);for (let y = 0; y < H; y++) out[y][x] = f[y];}return out;}// Inverse transform: ifft(x) = conj(fft(conj(x))) / Nfunction ifft2D(grid) {const H = grid.length, W = grid[0].length;const conj = grid.map(row => row.map(c => new Complex(c.re, -c.im)));const f = fft2D(conj);const N = W * H;return f.map(row => row.map(c => new Complex(c.re / N, -c.im / N)));}
For an N×N image, each 1D FFT costs O(N log N) and about 2N such transforms are performed, giving a total complexity of O(N² log N). Here N is the side length; the total number of pixels is N². Zero‑padding increases the side length and consequently the computation time.
Displaying magnitude and phase: The magnitude is Math.hypot(re, im). To compress the dynamic range, we display log(1 + magnitude) normalized to 0–255. The phase is Math.atan2(im, re) and ranges from –π to π, linearly mapped to 0–255.
Mode 3: Phase‑spectrum scribbling: Keep the phase and set every frequency magnitude to 1, then perform the inverse transform.
const phaseOnly = spectrum.map(row => row.map(c => {const phi = Math.atan2(c.im, c.re);return new Complex(Math.cos(phi), Math.sin(phi));}));const restored = ifft2D(phaseOnly);// Take the real part, clamp to [0,255], and crop to the original dimensions
The human visual system is far more sensitive to phase than to magnitude, so this restoration still shows the approximate structure of the original. It is an approximation, not an exact reconstruction.
Mode 4: Joint spectrum: The page stores both magnitude and phase. Reconstruction forms complex numbers using re = magnitude × cos(phase) and im = magnitude × sin(phase), then applies the inverse FFT. When untouched, the imaginary part is nearly zero, and taking the real part gives the exact original. After scribbling, the imaginary part is no longer zero, and taking the real part yields only an approximation.
Mode 5: Row Derivatives and Gradient‑Domain Reconstruction
Row derivatives are computed in the spatial domain. The first column retains its original value; every other column stores the difference from the left neighbor.
function rowDerivative(src) {const out = new Matrix2D(src.w, src.h);for (let y = 0; y < src.h; y++) {out.set(0, y, src.get(0, y));for (let x = 1; x < src.w; x++) {out.set(x, y, src.get(x, y) - src.get(x - 1, y));}}return out;}function rowIntegrate(d) {const out = new Matrix2D(d.w, d.h);for (let y = 0; y < d.h; y++) {out.set(0, y, d.get(0, y));for (let x = 1; x < d.w; x++) {out.set(x, y, out.get(x - 1, y) + d.get(x, y));}}return out;}
Flat regions produce differences close to zero, while edges show clear positive or negative peaks. Hence the derivative image looks like a pencil sketch.
The first column must be preserved. Integration starts from that column; if it is missing, the DC (average) component of each row is lost.
Scribbling changes the difference values. If an offset is added at a particular position, the inverse transform sums that offset along the entire row to the right, creating horizontal streaks. Similarly, rounding derivative values to integers before integration causes each pixel’s rounding error to accumulate along the row. Therefore, the derivative image should be stored in floating point.
Brush Engine, Undo, and Redo
Coordinate mapping: Mouse events give screen pixel coordinates. The canvas display size and matrix size usually differ, so we scale proportionally.
function canvasToMatrix(e, canvas, mat) {const rect = canvas.getBoundingClientRect();const mx = Math.floor((e.clientX - rect.left) * mat.w / rect.width);const my = Math.floor((e.clientY - rect.top) * mat.h / rect.height);return { x: mx, y: my };}
When to compute the inverse: Scribbling on the magnitude or phase spectrum affects almost every spatial pixel after the inverse transform. Recomputing on every mouse move would be slow. A more efficient approach is to recompute only when the mouse is released, updating only the spectral display during movement.
Undo and redo: Snapshotting is simple but memory‑intensive. A 64×64 Float64 matrix snapshot is about 32 KB; a 512×512 snapshot is about 2 MB. A more memory‑efficient approach is the command pattern: each stroke records only the indices and old/new values of the changed pixels.
const undoStack = []; // each entry is one stroke: [{ index, before, after }, ...]const redoStack = [];const MAX_HISTORY = 100;function commitStroke(changes) {undoStack.push(changes);if (undoStack.length > MAX_HISTORY) undoStack.shift();redoStack.length = 0;}function undo(mat) {const changes = undoStack.pop();if (!changes) return;for (const c of changes) mat.data[c.index] = c.before;redoStack.push(changes);}
Redo is symmetric, replacing before with after.
Display normalization: Before rendering a matrix to the canvas, find its minimum and maximum values, then linearly map them to 0–255 and write them into a Uint8ClampedArray.
Performance and Practical Suggestions
Images larger than 512×512 will cause visible main‑thread stutter during FFT operations. Consider the following measures.
- Run the FFT in a Web Worker. Transfer the image data as a transferable object, and send the result back when computation finishes.
- For intermediate results that do not need real‑time display, pre‑render using
OffscreenCanvas. - In high‑frequency loops, access the
dataarray directly instead of callinggetandsetrepeatedly. - Use performance timers to confirm bottlenecks rather than guessing.
const t0 = performance.now();runTransform();console.log(`Elapsed ${(performance.now() - t0).toFixed(1)} ms`);
Timing results depend on the device, browser, and image size. Measure in your own environment before deciding whether to introduce a worker.
Project Organization and Testing
A practical project can be structured as follows:
matrix.js: Matrix2D and grayscale conversion;transforms.js: matrix inversion, FFT, and row derivatives;brush.js: coordinate mapping, scribbling, and undo/redo;index.html: interface and event bindings.
Because workers must be loaded over HTTP, opening the page directly via file:// may fail. Use a local server such as python -m http.server or npx serve.
When testing, start with built‑in test patterns like checkerboards, gradients, and circles. Verification criteria:
- When untouched, the inverse‑matrix mode’s restoration should have a maximum absolute difference from the original below
1e-6, provided the condition number is not large; - When untouched, the joint‑spectrum mode should reconstruct the original exactly;
- After scribbling, the interface should clearly indicate whether the restoration is exact or approximate.
This experimental toolkit is ideal for observing the relationship between the frequency and spatial domains. It is not a replacement for professional image processing libraries, but it helps you understand exactly what each transform does and why some steps can only yield approximate results.
