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 restore it, using only browser-standard APIs and general math. It covers the 2D discrete Fourier transform, spectrum centering and log-compressed visualization, and five doodling modes: inverse-matrix domain, magnitude spectrum, phase spectrum, combined magnitude and phase, and row-derivative domain. For each mode it describes the perturbation, the visual effect, and how restoration works, followed by engineering notes on size selection, precision, pointer interaction, and worker-thread performance.

    1. Background: Why Doodle in a Transform Domain

    Scribbling directly on pixels in the spatial domain is intuitive and irreversible. But if you first apply a reversible transform that maps pixels into another representation, perturb a local region of the transform coefficients, and then apply the inverse transform to return to the spatial domain, you get a processing paradigm that looks destroyed yet can be restored. This is useful for image watermarking, reversible information hiding, teaching demos, and front-end graphics experiments. This article targets a pure front-end implementation and discusses five transform-domain doodling and restoration modes.

    All implementations here rely only on general mathematical definitions and browser-standard APIs, with no dependency on any specific third-party library or platform.

    2. Mathematical Basis: The 2D Discrete Fourier Transform

    Let the image be a grayscale matrix f(x,y) of size M×N. Its 2D discrete Fourier transform is:

    1. F(u,v) = Σ_x Σ_y f(x,y) · e^(-j2π(ux/M + vy/N))

    The inverse transform is:

    1. f(x,y) = (1/(MN)) Σ_u Σ_v F(u,v) · e^(j2π(ux/M + vy/N))

    In practice, nobody runs the four nested loops straight from the definition (O(M²N²) complexity). Instead, the separability property is used: apply a 1D transform to the rows, then to the columns, and combine it with a fast Fourier transform to bring the cost down to O(MN·log(MN)).

    The result F(u,v) is complex and can be written in polar form:

    1. F(u,v) = A(u,v) · e^(jφ(u,v))
    2. A(u,v) = |F(u,v)| // magnitude spectrum
    3. φ(u,v) = atan2(Im, Re) // phase spectrum

    One key conclusion: the magnitude spectrum determines the overall energy distribution and texture statistics of the image, while the phase spectrum determines structure, edges, and recognizable contours. This is exactly the theoretical basis for doodling on the magnitude and phase spectra separately later on.

    3. Spectrum Centering and Human-Readable Visualization

    In the raw transform output, the DC component sits in the top-left corner. For easier inspection, multiplying by (-1)^(x+y) centers the spectrum and moves low frequencies to the middle. Because the magnitude spectrum has an enormous dynamic range, visualization requires log compression:

    1. function visualizeSpectrum(re, im, size) {
    2. const out = new Float32Array(size * size);
    3. for (let i = 0; i < out.length; i++) {
    4. const mag = Math.hypot(re[i], im[i]);
    5. out[i] = Math.log(1 + mag); // log compression
    6. }
    7. return normalize(out); // normalize to 0~255
    8. }

    4. Five Doodling and Restoration Modes

    Mode 1: Inverse-Matrix Domain Doodling

    First apply a reversible linear transform to the image (such as an orthogonal matrix transform or multiplication by an invertible matrix) to obtain a coefficient matrix. Then pick a block in that matrix and scribble over it with a constant or random values. To restore, multiply back by the inverse matrix. Because the matrix is invertible, all untouched coefficients are recovered exactly, while the scribbled region shows up as local distortion. The implementation concern is numerical stability when inverting the matrix; normalizing the matrix beforehand is recommended to avoid an excessively large condition number.

    Mode 2: Magnitude Spectrum Doodling

    Zero out or scale a rectangular region of A(u,v) while leaving the phase unchanged, then recombine into a complex array and apply the inverse transform. The result is that the overall tone, brightness, and texture of the image change, but the contours remain recognizable. On restoration, if a backup of the region’s magnitudes was saved before doodling, the image can be restored exactly.

    Mode 3: Phase Spectrum Doodling

    Add a constant offset to a region of φ(u,v), or zero it out, keeping the magnitude unchanged. The effect is usually more dramatic: structure collapses and false contours appear, yet the energy distribution stays the same. This mode most directly demonstrates that phase dominates recognizability.

    Mode 4: Doodling Magnitude and Phase Together

    Perturbing both at once is the most thorough destruction, and restoration depends most heavily on the backup strategy. In practice, the backup data can be compressed and held in memory or local storage, forming a “reversible encoding.”

    Mode 5: Row-Derivative Domain Doodling

    Apply a first-order difference to each row, d(x,y)=f(x,y)-f(x,y-1), doodle in the derivative domain, then accumulate back. The derivative domain is sensitive to brightness jumps, so after doodling the result appears as stripe-like artifacts. Restoration only requires a prefix sum along each row.

    5. Engineering Implementation Notes

    1. // Complex arithmetic and transform skeleton (illustrative)
    2. function fft1d(re, im, inverse) { /* iterative butterfly operations */ }
    3. function fft2d(re, im, inverse) {
    4. fft1d(re, im, inverse); // row transform
    5. transpose(re, im); // transpose
    6. fft1d(re, im, inverse); // column transform
    7. transpose(re, im);
    8. if (inverse) scale(re, im, 1 / (re.length));
    9. }
    • Size selection: powers of two are the easiest choice; non-power-of-two sizes need zero padding or a mixed-radix approach.
    • Precision: store the real and imaginary parts in Float64Array to avoid accumulated error.
    • Interaction: use pointer events to record scribble rectangles on the canvas and trigger the forward transform → perturb → inverse transform pipeline in real time.
    • Performance: move the transforms into a worker thread so rendering is not blocked, and downsample the spectrum visualization.

    6. Use Cases and Boundaries

    These demos suit teaching about reversible image protection, front-end graphics experiments, and intuitively explaining how information redundancy supports recovery. This is not an encryption scheme; its security depends on how the backup data is kept. In real applications that need image protection and recovery, it should be combined with object storage versioning, operation auditing from logging services, and anomaly detection from monitoring and alerting to form a complete chain. If model-assisted generation or AI coding tools are involved in the workflow, the reversible transform should be treated as a general algorithmic capability rather than tied to any specific product.

    7. Summary

    All five modes share the same skeleton: forward transform → local perturbation in the domain → inverse transform → restore from backup. Once you understand the division of labor between magnitude and phase, along with the invertibility and numerical stability of the transform, you can build image restoration experiments in the browser that are both fun and rigorous.