JavaScript Image Frequency-Domain Doodling and Restoration Principles
This article explains how to doodle on an image in the frequency domain and then restore it using JavaScript. It defines the core problem of how visual information is distributed across transform domains, outlines five implementation routes (inverse matrix, magnitude spectrum, phase spectrum, combined magnitude and phase, and row derivative), and shows the DFT code plus spectrum visualization steps. It also covers the implementation of each doodling mode and practical engineering advice on FFT, worker threads, quality metrics, and caching.
1. Problem Definition: Why “Restorable After Doodling” Is Worth Studying
Drawing a few strokes on an image in the browser and then asking a program to recover the original may look like a casual experiment. In practice, it touches a core question in digital image processing: how visual information is distributed across different transform domains, which components carry structure, which carry detail, and whether the remaining information is enough to support reconstruction after part of it is destroyed.
To make this experiment rigorous, three levels of questions need to be answered: how to map the pixel matrix into a reversible transform domain; how to introduce controllable, local damage in that domain (the “doodling”); and how to perform the inverse transform and quantify the residual distortion. Each is covered below.
2. Overview of the Technical Routes
Common implementations fall into five routes. The first three are frequency-domain methods; the last two are spatial-domain methods:
- Inverse matrix route: treat the image as a linear system, build a transform matrix and invert it, with doodling applied to the matrix elements.
- Magnitude spectrum route: destroy only the magnitude of the spectrum while keeping the phase.
- Phase spectrum route: destroy only the angle of the spectrum while keeping the magnitude.
- Destroying magnitude and phase together: simulate the most severe information loss.
- Row derivative route: apply a first-order difference to each row, then integrate to restore, with doodling applied to the difference sequence.
The essential difference between the frequency-domain and spatial-domain routes is this: frequency-domain methods reshuffle energy, so local doodling spreads into global distortion; spatial-domain methods preserve pixel neighborhood relationships, so the impact of local doodling is limited. This difference determines how strong the perceived “restorability” is.
3. Frequency-Domain Basics and Spectrum Visualization
For a grayscale image f(x,y) of size N×N, the two-dimensional discrete Fourier transform is defined as:
// Naive implementation, for teaching demonstration only; use divide-and-conquer FFT in practicefunction dft2(real, imag, N) {const R = new Float64Array(N * N), I = new Float64Array(N * N);for (let u = 0; u < N; u++) {for (let v = 0; v < vN(N); v++) {let sr = 0, si = 0;for (let x = 0; x < N; x++) {for (let y = 0; y < N; y++) {const a = -2 * Math.PI * (u * x / N + v * y / N);const p = real[x * N + y];sr += p * Math.cos(a);si += p * Math.sin(a);}}R[u * N + v] = sr; I[u * N + v] = si;}}return { R, I };}function vN(n) { return n; }
A spectrum image usually goes through three steps before it can be visualized: use fftshift to move the zero frequency to the center; take the magnitude with Math.hypot(R, I); then apply logarithmic compression with Math.log(1 + mag). Otherwise the dynamic range is too large and the image is almost entirely black.
One key conclusion: the magnitude spectrum determines “where edges are and how strong the texture is,” while the phase spectrum determines “where those things are located.” In the experiment, swapping the magnitude and phase of two images produces a result that shows the compositional outline of the latter combined with the textural quality of the former. This is the most direct evidence that phase carries structural information.
4. Implementation Points for the Five Doodling Modes
The shared interaction skeleton is as follows. The user paints directly on the canvas, and releasing the mouse triggers recomputation:
const mask = new Uint8Array(N * N); // 1 means doodledcanvas.onpointermove = e => { paint(mask, e.offsetX, e.offsetY, radius); };canvas.onpointerup = () => restore(mode, mask);
- Inverse matrix mode: doodling directly rewrites matrix elements. After inversion, the error is amplified by the condition number. When the system is numerically unstable, regularization
(AᵀA + λI)⁻¹Aᵀis needed to suppress noise. - Magnitude spectrum mode: only the magnitude in the doodled region is set to zero or multiplied by a decay factor, while the phase is kept as is. The outline remains in the restored image but the texture disappears.
- Phase spectrum mode: only the angle is perturbed. The restored image keeps the rough light and dark levels but shows severe positional scrambling and “ghosting.”
- Dual-spectrum mode: magnitude and angle are destroyed at the same time. The output is close to noise and gives an upper bound on information loss.
- Row derivative mode: first apply
d[i] = f[i] - f[i-1]to each row, then accumulate and sum to restore after doodling. The error accumulates along the row and appears as horizontal smearing.
5. Engineering Practice Recommendations
To host this kind of demonstration in a production environment or a teaching platform, four points are worth attention: keep N within 256 and switch to divide-and-conquer FFT to control main-thread time; move recomputation into a worker thread to avoid a frozen interface; use both mean squared error and structural similarity to quantify restoration quality; store image assets and result caches in object storage, and distribute recomputation tasks asynchronously through a message queue, with logging and monitoring alerts to locate performance bottlenecks. If an AI coding tool is used to generate the initial code, be sure to manually review numerical stability and boundary handling, especially the matrix inversion and phase unwrapping parts.
