Scribbling in the Transform Domain: A JavaScript Guide to Image Distortion and Restoration
This article explores how applying perturbations inside an image's transform domain, rather than directly on pixels, changes what gets damaged when the image is reconstructed. It covers four reversible representations implemented in pure browser-side JavaScript: inverse-matrix transforms, the magnitude and phase spectra of the 2D DFT, and row-wise derivative (difference) signals. For each mode, it explains the underlying math, what the restored image looks like after scribbling, and key implementation pitfalls such as conjugate symmetry in the spectrum and display normalization. It then presents a unified interaction framework with undo and reset, followed by performance and usability optimizations, common mistakes, and possible extensions. All code uses basic canvas pixel access and numeric arrays, with no backend or GPU APIs required.
1. Why Scribble in the Transform Domain?
Drawing directly in the spatial domain (the pixel grid we normally see) changes local brightness and color. It is visually intuitive, but it alters the image’s information structure only slightly. If you first map the image into another representation, apply a local perturbation there, and then invert the transform back to the spatial domain, interesting things happen: some representations carry mainly texture and energy distribution, some carry almost all recognizable structure, and others turn the image into a set of additive difference signals.
These three behaviors correspond to the three families of representations discussed here: inverse-matrix transforms, the magnitude and phase spectra in the frequency domain, and derivative (difference) representations in the spatial domain. Understanding the differences between them is the prerequisite for designing a “scribble-and-restore” interaction.
Note that every implementation in this article runs entirely in the browser as pure front-end code. No backend service is required, and no additional graphics acceleration API is needed; basic canvas pixel read/write and numeric computation are enough.
2. Mathematical Setup: From Pixel Matrix to Reversible Mapping
A grayscale image can be treated as a matrix A (size N×N, with N chosen as a power of two for convenience). A “reversible mapping” means there exists a transform T and its inverse T⁻¹ such that T⁻¹(T(A)) = A. Scribbling happens in the transform domain: compute B = T(A), apply a perturbation δ to a subset of B to get B’ = B + δ, then restore A’ = T⁻¹(B’).
What matters is not how complex the transform is, but how the sparsity and location of the perturbation determine the look of the restored image. The more concentrated the perturbation and the closer it sits to structural information, the more obvious the visual damage; a perturbation landing in an energy-redundant region is nearly invisible to the eye.
Skeleton code (matrix and reversible transform):
function toMatrix(gray, n) {const A = new Float64Array(n * n);for (let i = 0; i < n * n; i++) A[i] = gray[i] / 255;return A;}function applyT(A, n) { /* forward transform, returns an array of the same size */ }function applyInvT(B, n) { /* inverse transform, must be strictly inverse to applyT */ }function scribble(B, n, cx, cy, r) {for (let y = Math.max(0, cy - r); y < Math.min(n, cy + r); y++)for (let x = Math.max(0, cx - r); x < Math.min(n, cx + r); x++)B[y * n + x] += 0.5; // perturbation strength is adjustablereturn B;}
3. Mode 1: Scribbling with Inverse-Matrix Transforms
The most straightforward reversible transform is multiplication by a non-singular matrix: B = M·A·Mᵀ. As long as M is invertible, restoration is A’ = M⁻¹·B’·(Mᵀ)⁻¹. The value of this transform is its clear teaching value: it puts reversibility directly in the formula.
In practice, large dense matrices are not recommended (complexity O(N³), already unacceptable at N=512). A workable engineering compromise is a block-diagonal structure or a structured matrix (such as a block-DCT-style group average-and-difference matrix), which keeps reversibility while pushing complexity close to linear.
Place the scribble on low-frequency group blocks. Low-frequency components carry overall brightness and contours, so after perturbation the restored image shows obvious block-wise color shifts and structural drift, giving very direct interactive feedback.
4. Modes 2 and 3: Scribbling on the Magnitude and Phase Spectra
The 2D discrete Fourier transform splits an image into a magnitude spectrum |F| and a phase spectrum φ. Many experiments and teaching examples point to the same conclusion: the magnitude spectrum mainly describes how energy is distributed across frequencies, i.e. “where texture and edges are,” while the phase spectrum largely determines “where those structures appear.”
Therefore:
- Scribbling the magnitude spectrum: overall texture is smoothed out or periodic stripes appear, but the main outline remains;
- Scribbling the phase spectrum: structural positions become scrambled, with obvious “rearrangement” and “tearing,” and recognizability drops sharply;
- Scribbling both at once: the image becomes basically unrecognizable, close to noise.
One important implementation detail is the conjugate symmetry of the spectrum. The spectrum of a real image satisfies F(-u,-v) = conj(F(u,v)). If you modify only one half without mirroring the change to the other half, the inverse transform result carries an imaginary part, and taking the real part produces non-physical artifacts. The correct approach is to handle (-u,-v) in sync for every scribbled point (u,v).
function fft2(re, im, n, inverse) { /* 2D fast Fourier transform, in-place */ }function scribbleSpectrum(re, im, n, cx, cy, r, mode) {for (let y = cy - r; y <= cy + r; y++) {for (let x = cx - r; x <= cx + r; x++) {const u = (x + n) % n, v = (y + n) % n;const mu = (-u + n) % n, mv = (-v + n) % n; // conjugate symmetric pointconst i1 = v * n + u, i2 = mv * n + mu;const mag = Math.hypot(re[i1], im[i1]);const ph = Math.atan2(im[i1], re[i1]);const nm = mode === 'amp' ? mag * 0.2 : mag;const np = mode === 'phase' ? ph + 1.2 : ph;re[i1] = nm * Math.cos(np); im[i1] = nm * Math.sin(np);re[i2] = nm * Math.cos(-np); im[i2] = nm * Math.sin(-np);}}}
Engineering detail: spectral values span a far larger range than spatial values, so always normalize block by block before writing back to the canvas. Otherwise large areas overflow to pure white or pure black, which looks like “the implementation failed” but is actually a display-mapping issue.
5. Mode 4: Scribbling on the Row Derivative (Difference) Representation
Taking a first-order difference along each row, d[i] = A[i] - A[i-1] (keeping the first element unchanged), yields a reversible derivative representation; restoration is just a prefix-sum accumulation. Its trait is turning “absolute brightness” into “change between neighbors”: flat regions are almost 0, while edges show positive and negative spikes.
The scribbling strategy is therefore clear: adding a constant offset over a short interval in the derivative domain makes that interval uniformly brighter or darker after restoration, with a step at the boundaries; scattering points randomly in several places produces a mottled “scratch” effect. Because the difference is computed independently per row, this mode has the smallest computational cost and is well suited as the first tier of an interactive demo.
function rowDerivative(A, n) {const D = new Float64Array(n * n);for (let y = 0; y < n; y++) {D[y * n] = A[y * n];for (let x = 1; x < n; x++) D[y * n + x] = A[y * n + x] - A[y * n + x - 1];}return D;}function integrateRows(D, n) {const A = new Float64Array(n * n);for (let y = 0; y < n; y++) {A[y * n] = D[y * n];for (let x = 1; x < n; x++) A[y * n + x] = A[y * n + x - 1] + D[y * n + x];}return A;}
6. A Unified Interaction Framework for All Five Modes
Abstract the five modes behind the same interface, and the front end only needs to swap the “transformer” implementation while the scribble-and-restore flow is fully reused:
- Load the image, scale it to N×N, and convert to grayscale;
- Construct a transformer object (forward transform, inverse transform, visualization mapping);
- The user drags on the canvas to produce a sequence of scribble trajectory points;
- Discretize the trajectory into a set of centers and radii, and apply perturbations in the transform domain;
- Inverse-transform back to the spatial domain, apply the display mapping, and refresh the canvas;
- Provide “undo one step” and “reset”; undo works by saving the list of perturbations and rolling them back in reverse order.
The key to undo is saving δ rather than saving full intermediate results, which reduces memory use from O(k·N²) to O(k·r²), where k is the number of scribble steps.
7. Performance and Experience Optimization
- Size control: N of 256 or 512 is enough for a demo; going larger gives little benefit while cost rises sharply;
- Transform reuse: compute the forward transform only once at load time; the scribble phase only performs the inverse transform;
- Incremental updates: the derivative mode supports per-row incremental recomputation, avoiding a full-image refresh;
- Yielding frames: split the inverse transform into blocks and schedule them across frames to avoid freezing the UI;
- Numerical stability: use double-precision arrays for all intermediate values, and clip uniformly to [0,1] before display.
8. Common Pitfalls
First, treating “reversible” as “losslessly restoring any perturbation”; in fact, once a perturbation happens, what is restored is the perturbed version, not the original image. Second, ignoring conjugate symmetry, which causes artifacts in the spectral inverse transform. Third, judging transform-domain effects directly in the spatial domain, which leads to tuning in the wrong direction. Fourth, starting with dense matrix inversion, which quickly collapses performance.
9. Summary
The value of transform-domain scribbling is that the same “forward transform — perturb — inverse transform” skeleton intuitively demonstrates how different representations carry image information: inverse-matrix transforms emphasize reversibility itself, the magnitude and phase spectra reveal the division of labor between energy and structure, and row derivatives demonstrate reversible differencing at minimal cost. Once you master this framework, you can extend it to block transforms, multi-scale representations, and custom reversible mappings, forming a complete image-representation experiment platform.
