JavaScript Image Frequency-Domain Doodling and Restoration: Principles and Implementation

    This article explains how to doodle on an image in a transform domain and still recover the original through an inverse transform, using a pure front-end JavaScript approach. It covers the pixel data foundation built on ImageData, then walks through five technical paths: doodling in an invertible matrix domain, the magnitude spectrum, the phase spectrum, both magnitude and phase together, and the row-derivative domain. It also summarizes performance and engineering practices, and concludes that magnitude carries most of the energy while phase carries structure.

    1. Background: Why “Doodle It, Then Restore It” Is Worth Studying

    In image processing and front-end visualization, there is a particularly interesting class of problems: apply a reversible transform to an image, expose the result on a canvas, let users scribble, occlude, or destroy part of the data, and then recover the original through the inverse transform. This kind of demo vividly reveals how image information is distributed—not all pixels are equally important, and energy and structural information are highly unevenly distributed across different transform domains.

    From an engineering perspective, it involves three capabilities at once: pixel-level data manipulation, an implementation of a 2D frequency-domain transform, and interactive rendering performance control. Using a pure front-end approach as the example, the next sections break down five technical paths one by one.

    2. Foundation Layer: Reading and Writing Pixel Data

    Everything is built on top of ImageData. The core flow is always four steps:

    1. // 1. Read pixels
    2. const src = ctx.getImageData(0, 0, w, h);
    3. // 2. Build complex arrays (real + imaginary)
    4. const re = new Float32Array(w * h);
    5. const im = new Float32Array(w * h);
    6. for (let i = 0; i < w * h; i++) {
    7. re[i] = src.data[i * 4] / 255; // normalize to [0,1]
    8. im[i] = 0;
    9. }
    10. // 3. Process in the transform domain (see paths below)
    11. // 4. Write back after the inverse transform
    12. for (let i = 0; i < w * h; i++) {
    13. const v = Math.max(0, Math.min(255, re[i] * 255));
    14. src.data[i * 4] = src.data[i * 4 + 1] = src.data[i * 4 + 2] = v;
    15. }
    16. ctx.putImageData(src, 0, 0);

    Engineering notes: first, you must normalize and clamp, otherwise the tiny negative values produced by the inverse transform will cause color inversion; second, choose dimensions that are powers of two whenever possible, which greatly simplifies the transform implementation; third, converting to grayscale cuts the computation by two-thirds, while color processing must run separately on all three channels.

    3. Path One: Doodling and Restoration in the Inverse-Matrix Domain

    Treat the image as an $N \times N$ matrix $A$. Doodling is equivalent to applying a known linear operator $T$ to the matrix, producing $B = T A$. Restoration means solving $A = T^{-1} B$.

    The key is the choice of operator. If $T$ is an invertible matrix (for example, a discrete cosine transform matrix or a Hadamard matrix), doodling happens on the transform coefficients, and restoration only requires multiplying by the inverse matrix. A sketch implementation:

    1. // Using the DCT-II matrix as an example; T is orthogonal, so the inverse is its transpose
    2. function applyMatrix(data, T, N, inverse) {
    3. const tmp = new Float32Array(N * N);
    4. const out = new Float32Array(N * N);
    5. // Row transform
    6. for (let r = 0; r < N; r++)
    7. for (let c = 0; c < N; c++) {
    8. let s = 0;
    9. for (let k = 0; k < N; k++) s += T[k * N + c] * data[r * N + k];
    10. tmp[r * N + c] = s;
    11. }
    12. // Column transform
    13. for (let c = 0; c < N; c++)
    14. for (let r = 0; r < N; r++) {
    15. let s = 0;
    16. for (let k = 0; k < N; k++) s += T[k * N + r] * tmp[k * N + c];
    17. out[r * N + c] = inverse ? s : s;
    18. }
    19. return out;
    20. }

    The complexity is $O(N^3)$, so once $N$ exceeds 128 you should switch to a fast transform. The strength of this path is that it is mathematically the cleanest, with doodling and restoration being strictly inverse to each other; the drawback is the heavy computation and the fact that the mapping between doodle position and visual effect is not very intuitive.

    4. Path Two: Doodling and Restoration on the Magnitude Spectrum

    The 2D discrete Fourier transform decomposes an image into a magnitude spectrum $|F(u,v)|$ and a phase spectrum $\phi(u,v)$. The magnitude spectrum describes the strength of each frequency component and determines the overall energy distribution and tonal layering of the image.

    Doodling strategy: visualize the magnitude spectrum as a log-magnitude map $\log(1+|F|)$, let the user scribble on it, set the magnitude in the scribbled region to zero or to the neighborhood mean, then combine it with the original phase spectrum and apply the inverse transform.

    1. // Shift the spectrum so low frequencies are centered, making it easier to doodle on
    2. function fftshift(re, im, w, h) {
    3. const outRe = new Float32Array(w * h), outIm = new Float32Array(w * h);
    4. for (let y = 0; y < h; y++)
    5. for (let x = 0; x < w; x++) {
    6. const nx = (x + (w >> 1)) % w, ny = (y + (h >> 1)) % h;
    7. outRe[y * w + x] = re[ny * w + nx];
    8. outIm[y * w + x] = im[ny * w + nx];
    9. }
    10. return { re: outRe, im: outIm };
    11. }
    12. // Restoration: doodled magnitude + original phase
    13. function recombine(mag, phase) {
    14. return { re: mag * Math.cos(phase), im: mag * Math.sin(phase) };
    15. }

    Empirical rule: scribbling uniformly across the magnitude spectrum makes the whole image blur and lowers contrast, but the outline stays recognizable; destroying only the low-frequency center region degrades the image into a “skeleton” with only edges left. This shows that the magnitude spectrum carries most of the energy.

    5. Path Three: Doodling and Restoration on the Phase Spectrum

    The phase spectrum determines the relative positional relationships between pixels and is the carrier of structural information. If you doodle on the phase spectrum (for example, by adding random perturbation or zeroing it) and then recombine it with the original magnitude spectrum, you get obvious spatial misalignment, drifting object positions, or even an unrecognizable image.

    1. // Phase doodling: inject random phase noise into the selected region
    2. function doodlePhase(phase, mask, strength) {
    3. for (let i = 0; i < phase.length; i++)
    4. if (mask[i]) phase[i] += (Math.random() - 0.5) * strength * Math.PI;
    5. return phase;
    6. }

    A comparison experiment yields a clear conclusion: phase destruction harms recognizability far more than an equal degree of magnitude destruction. This conclusion has practical reference value in feature design for tasks such as face recognition and image retrieval—methods that rely on texture statistics and methods that rely on structural alignment fail in completely different ways.

    6. Path Four: Doodling on Magnitude and Phase Together

    Destroying both at once produces a restoration result closest to a “noise image,” retaining only a very small amount of low-frequency outline. In implementation, you only need to process the two arrays in parallel before the inverse transform; note that they share the same coordinate system and fftshift offset, otherwise a half-pixel-level misalignment will appear.

    Engineering advice: give each of the two paths its own independent doodle-strength slider to make it easy to observe the division of labor—“magnitude dominates energy, phase dominates structure”; also overlay a semi-transparent spectrum underlay on the canvas so users clearly know which region they are scribbling on.

    7. Path Five: Doodling and Restoration in the Row-Derivative Domain

    The first four paths are based on the frequency domain; the fifth returns to the spatial domain but from a different angle: apply a first-order difference to each row, $D(x,y)=I(x,y)-I(x-1,y)$, producing a row-derivative image. Doodling happens on the derivative image, and restoration is done by cumulative integration along the row direction:

    1. // Row-derivative forward transform
    2. function rowDerivative(src, w, h) {
    3. const d = new Float32Array(w * h);
    4. for (let y = 0; y < h; y++)
    5. for (let x = 0; x < w; x++)
    6. d[y * w + x] = x === 0 ? src[y * w] : src[y * w + x] - src[y * w + x - 1];
    7. return d;
    8. }
    9. // Inverse transform: accumulate within the row, keeping the first pixel as the integration constant
    10. function rowIntegrate(d, w, h) {
    11. const out = new Float32Array(w * h);
    12. for (let y = 0; y < h; y++) {
    13. let acc = d[y * w];
    14. out[y * w] = acc;
    15. for (let x = 1; x < w; x++) { acc += d[y * w + x]; out[y * w + x] = acc; }
    16. }
    17. return out;
    18. }

    The characteristic of this path is that “error propagates along the row”: doodling on one point causes every subsequent pixel in that row to accumulate an offset, forming a horizontal smear. This vividly demonstrates the instability of integration-type inverse problems—tiny perturbations get amplified through accumulation—so real systems need to introduce regularization or boundary constraints to suppress the drift.

    8. Performance and Engineering Practices

    • Prefer divide-and-conquer fast algorithms for transform implementations, reducing a naive $O(N^2)$ implementation to $O(N \log N)$; put unavoidable high-complexity paths into a worker thread to avoid blocking rendering.
    • Downsample during interaction (for example, longest side 256), then recompute at the original resolution after the pointer is released, balancing smoothness and quality.
    • The doodle brush on the frequency-domain canvas should perform coordinate mapping, converting canvas coordinates into spectrum indices while keeping the fftshift state in sync.
    • Always apply numerical clipping and a gamma-consistency check to restoration results to prevent color shifts caused by overflow.
    • If you need to save intermediate states, store a parameterized doodle description in browser storage or object storage rather than the whole bitmap, which significantly reduces size.

    9. Summary

    The five paths together make one point: image information is highly redundant and unevenly distributed across different transform domains. The magnitude spectrum dominates energy, the phase spectrum dominates structure, the derivative domain amplifies perturbations, and the invertible-matrix domain provides strict invertibility. Bringing these rules into front-end implementation still comes down to three things—correct complex arithmetic and normalization, interactive spectrum visualization, and putting heavy recomputation into a worker thread. Once you master this framework, you can freely swap the transform kernel and treat it as a general-purpose “transform-domain interaction playground.”