Image Frequency-Domain Doodling and Restoration in JavaScript

    This article explores five JavaScript approaches to frequency-domain image doodling and restoration, all running entirely in the browser: inverse-matrix transforms, magnitude-spectrum doodling, phase-spectrum doodling, combined magnitude-and-phase doodling, and row-derivative transforms. For each route it explains the underlying math, provides working code, and describes the characteristic artifacts that appear after restoration. It also covers practical engineering concerns such as floating-point precision, performance, interactive controls, and zero-doodle round-trip validation. Readers will learn how reversible transforms redistribute image information across structural layers, and why damaging a specific layer removes a specific kind of semantics.

    1. Why Run Transform–Doodle–Restore in the Browser

    Image restoration experiments are valuable because a controlled corruption process reveals which structural layer of an image actually carries information. Doing this in the browser offers three practical benefits: no server round trips, so interaction latency stays low; pixel data never leaves the local machine, which makes the setup suitable for teaching demos in privacy-sensitive contexts; and intermediate results can be inspected frame by frame during debugging, turning abstract mathematical transforms into visual feedback.

    The overall pipeline breaks into four steps: load pixels and normalize them, apply a reversible or approximately reversible forward transform, inject doodles in the transform domain, then apply the inverse transform and quantize back to 8-bit grayscale or RGB. The critical point is that step two and step four must be mathematical inverses of each other; otherwise the restored result shows structural distortion rather than random noise.

    2. Route 1: Inverse-Matrix Image Transforms

    Flatten the image into a vector by columns or rows, then left-multiply by an invertible matrix to obtain the transform-domain representation. Given original vector x and transform matrix A, the transform result is y = A·x, and restoration only requires x = A⁻¹·y.

    1. // Matrix inversion via Gaussian elimination, illustrative implementation
    2. function inverse(mat) {
    3. const n = mat.length;
    4. const a = mat.map((r, i) => [...r, ...Array.from({length: n}, (_, j) => i === j ? 1 : 0)]);
    5. for (let i = 0; i < n; i++) {
    6. let p = i;
    7. while (p < n && Math.abs(a[p][i]) < 1e-9) p++;
    8. [a[i], a[p]] = [a[p], a[i]];
    9. const d = a[i][i];
    10. for (let j = 0; j < 2 * n; j++) a[i][j] /= d;
    11. for (let k = 0; k < n; k++) {
    12. if (k === i) continue;
    13. const f = a[k][i];
    14. for (let j = 0; j < 2 * n; j++) a[k][j] -= f * a[i][j];
    15. }
    16. }
    17. return a.map(r => r.slice(n));
    18. }

    One engineering concern is the condition number: the closer a matrix is to singular, the more inversion error is amplified, and the restored image after doodling develops large patches of artifacts. In practice, keep the block size small (for example 8×8 or 16×16) and clamp the doodle amplitude.

    3. Route 2: Magnitude-Spectrum Doodling

    The 2D discrete Fourier transform decomposes an image into magnitude and phase. The magnitude spectrum describes the energy share of each frequency component and determines overall brightness distribution and texture strength. Blacking out the low-frequency region at the center of the magnitude spectrum makes the restored image look washed out with collapsed detail; doodling the high-frequency region instead produces blurred edges.

    1. function fft1d(re, im, inverse) {
    2. const n = re.length;
    3. for (let i = 1, j = 0; i < n; i++) {
    4. let bit = n >> 1;
    5. for (; j & bit; bit >>= 1) j ^= bit;
    6. j ^= bit;
    7. if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; }
    8. }
    9. for (let len = 2; len <= n; len <<= 1) {
    10. const ang = (inverse ? 2 : -2) * Math.PI / len;
    11. const wr = Math.cos(ang), wi = Math.sin(ang);
    12. for (let i = 0; i < n; i += len) {
    13. let cr = 1, ci = 0;
    14. for (let k = 0; k < len / 2; k++) {
    15. const ur = re[i + k], ui = im[i + k];
    16. const vr = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci;
    17. const vi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr;
    18. re[i + k] = ur + vr; im[i + k] = ui + vi;
    19. re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;
    20. const nr = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = nr;
    21. }
    22. }
    23. }
    24. if (inverse) for (let i = 0; i < n; i++) { re[i] /= n; im[i] /= n; }
    25. }

    Implementation notes: first apply a spectrum shift to move the DC component to the center so doodling can be positioned geometrically; pad the transform size up to a power of two; after the inverse transform, take the real part and apply normalization and clipping.

    4. Route 3: Phase-Spectrum Doodling

    The phase spectrum carries structural information, and the experimental conclusion is quite stable: keep the phase and destroy the magnitude, and the image outline remains recognizable; keep the magnitude and destroy the phase, and the image degrades into noise texture with no semantics. Doodling the phase spectrum therefore usually feels far more destructive than doodling the same proportion of the magnitude spectrum. For the implementation, write the complex spectrum in polar form, add a random offset to the phase or zero it out, then recombine into a complex value and run the inverse transform.

    5. Route 4: Doodling Magnitude and Phase Together

    Stacking the two routes produces compound corruption: damaged low-frequency magnitude causes an overall brightness shift, while damaged phase causes structural collapse. The restored image is both blurry and unrecognizable, which makes it suitable for verifying algorithm robustness under extremely degraded input. Try combining them at different ratios (for example 30% magnitude and 70% phase) and observe the nonlinear relationship between degradation level and doodle ratio.

    6. Route 5: Row-Derivative Transform

    Apply a first-order difference to each row to obtain a horizontal derivative image. The forward transform is differencing and the inverse is prefix-sum accumulation, which is naturally reversible and very cheap to compute:

    1. // Forward transform: first-order difference along rows
    2. for (let y = 0; y < h; y++)
    3. for (let x = w - 1; x > 0; x--) src[y * w + x] = src[y * w + x] - src[y * w + x - 1];
    4. // Inverse transform: prefix sum along rows
    5. for (let y = 0; y < h; y++)
    6. for (let x = 1; x < w; x++) dst[y * w + x] = dst[y * w + x - 1] + dst[y * w + x];

    The defining trait of this route is that error accumulates along the row direction: doodle a single point and the entire rest of that row shows a horizontal stripe-shaped offset. This is exactly a demonstration of error propagation in integral-type inverse transforms, and a hands-on case for understanding accumulated error.

    7. Engineering Practice Recommendations

    • Precision control: always use floating-point arrays for intermediate results and quantize to 0–255 only at the final stage, avoiding irreversible loss from intermediate rounding.
    • Performance optimization: row and column transforms can transpose and reuse the same 1D logic; large-scale computation can be moved into worker threads to avoid blocking rendering; where necessary, use graphics acceleration interfaces or runtime compilation capabilities.
    • Interaction design: expose the doodle brush, transform mode, and restoration strength as adjustable parameters with a live-refreshing preview, which gives the best teaching and debugging efficiency.
    • Validation method: first run a “zero-doodle” round-trip test to confirm the restored image differs from the original only at the quantization-noise level, then introduce doodling, so any observed distortion can be attributed to the doodle itself.

    Taken together, the five routes support one conclusion: a reversible image transform redistributes information across different structural layers, and whichever layer the doodle damages is the kind of semantics the restored result loses. Mastering this correspondence deepens understanding of frequency-domain analysis and provides a reusable experimental framework for image coding, watermarking, and robustness testing.