JavaScript Image Frequency-Domain Doodling and Restoration: Five Reversible Transform Techniques

    This article explores how to add controlled disturbances (doodles) to an image in a transformed domain and then restore it using JavaScript in the browser. It presents five reversible routes: matrix inversion, magnitude spectrum perturbation, phase spectrum perturbation, combined magnitude-and-phase perturbation, and a row-derivative domain. For each route, it explains the forward transform, doodling step, inverse transform, and restoration behavior, along with JavaScript code snippets. It also covers engineering considerations such as performance, numerical precision, interactive controls, and visualization, showing how reversible transforms support decomposition and reconstruction for filters, watermarking, and image quality assessment.

    1. Background and Overall Approach

    Image processing in the browser used to rely on server-side code or native plugins. With the maturity of TypedArray, WebGL, and the Canvas 2D API, pure front-end code can now handle a substantial amount of numerical computation. This article discusses a problem that is both fun and instructive: first transform an image into a certain “domain,” add artificial doodles (disturbances) in that domain, then apply the inverse transform to observe how the image is “destroyed” and “restored.”

    A “domain” refers to the coordinate space of the image under a different mathematical representation. The original pixel space is the most intuitive domain, while linear algebra and Fourier analysis offer more choices. The overall workflow can be abstracted into four steps:

    1. Forward transform: map the pixel matrix to the target domain.
    2. Doodling: add artificial disturbances in the target domain.
    3. Inverse transform: map the disturbed data back to pixel space.
    4. Restoration: erase the doodles and apply the inverse transform again to verify reversibility.

    The key prerequisite is that the transform must be reversible and the inverse transform must be numerically stable. The five routes below are built around “reversibility” and “sensitivity to disturbances.”

    2. Route 1: Doodling and Restoration Based on Matrix Inversion

    Treat the image as a matrix A, choose an invertible matrix M, and construct B = M·A. Doodling on B is equivalent to adding a disturbance matrix E to some elements, yielding B’ = B + E. During restoration, compute A’ = M⁻¹·B’. If E is zero, A’ should strictly equal A.

    1. function matMul(A, B) {
    2. const n = A.length, m = B[0].length, k = B.length;
    3. const C = Array.from({length: n}, () => new Float64Array(m));
    4. for (let i = 0; i < n; i++)
    5. for (let p = 0; p < k; p++) {
    6. const a = A[i][p];
    7. for (let j = 0; j < m; j++) C[i][j] += a * B[p][j];
    8. }
    9. return C;
    10. }

    From an engineering perspective, matrix inversion is sensitive to the condition number: the closer M is to singular, the more numerical errors are amplified. It is recommended to orthogonalize M or use Gaussian elimination with partial pivoting, and to clamp pixels to 0–255 after the inverse transform.

    3. Route 2: Magnitude Spectrum Doodling

    The 2D discrete Fourier transform decomposes an image into a magnitude spectrum and a phase spectrum. The magnitude spectrum describes the strength of each frequency component, with low frequencies concentrated at the center (if fftshift has been applied) and high frequencies distributed around the edges. A common approach to doodling on the magnitude spectrum is to multiply it by a smooth mask or add random noise, then apply the inverse transform.

    The magnitude spectrum determines the “brightness and contrast structure,” so after doodling the image usually becomes blurry and washed out overall, but the outlines remain recognizable. Restoration only requires restoring the magnitude spectrum to its original values; the inverse transform then reconstructs the image losslessly (ignoring floating-point errors).

    4. Route 3: Phase Spectrum Doodling

    The phase spectrum determines “position and edge alignment.” In experiments, disturbing only the phase while keeping the magnitude causes the image to degrade into noise texture; keeping only the phase while flattening the magnitude still reveals the rough outline. This shows that the human eye is more sensitive to phase.

    In implementation, it is recommended to extract the phase separately as atan2(Im, Re), add the disturbance, and recombine it with the magnitude:

    1. const mag = Math.hypot(re, im);
    2. const ph = Math.atan2(im, re) + delta;
    3. re2 = mag * Math.cos(ph);
    4. im2 = mag * Math.sin(ph);

    5. Route 4: Simultaneous Magnitude and Phase Doodling

    Disturbing both at the same time causes the most thorough destruction, making the image completely unreadable. The restoration strategy is to save the original magnitude and phase separately, erase the doodles, reconstruct the complex spectrum, and apply the inverse transform. This route is suitable for demonstrating the engineering pattern of “separate information storage + reversible reconstruction.”

    6. Route 5: Row-Derivative Domain Doodling

    Apply a first-order difference to each row, d[i] = x[i] - x[i-1], to obtain the row-derivative domain. Doodling means adding disturbances to the difference sequence. Restoration can be done exactly by prefix-sum accumulation, which reconstructs the first row plus an offset. This is an integer lossless reversible transform with the best numerical stability, making it suitable for teaching demonstrations.

    1. // Forward transform
    2. for (let y = 0; y < h; y++)
    3. for (let x = w - 1; x > 0; x--)
    4. d[y*w+x] = src[y*w+x] - src[y*w+x-1];
    5. // Inverse transform
    6. for (let y = 0; y < h; y++)
    7. for (let x = 1; x < w; x++)
    8. out[y*w+x] = out[y*w+x-1] + d[y*w+x];

    7. Engineering Best Practices

    • Performance: 2D transforms in pure JavaScript have relatively high complexity. It is recommended to limit the resolution, use TypedArray, and move heavy computation into a Web Worker when necessary to avoid blocking rendering.
    • Precision: for floating-point transforms, always retain intermediate results (magnitude, phase, or matrices) and do not repeatedly quantize to 8 bits.
    • Interaction: provide an independent slider for each mode to control doodle intensity, and display a “restoration error” metric (such as root mean square error) to verify reversibility.
    • Visualization: use Canvas to draw the original image, the transform domain, the doodled result, and the restored result in layers for easy comparison.

    8. Summary

    The five routes together illustrate one principle: the value of reversible image transforms lies not in “hiding” but in “decomposition and reconstruction.” Matrix inversion emphasizes linear algebra stability, the two frequency-domain routes reveal the semantic division of labor between magnitude and phase, and the row-derivative domain provides a lossless integer solution. Once readers master these patterns, they can transfer the same framework to more practical scenarios such as filter design, watermark embedding, and image quality assessment.