Image Frequency-Domain Doodling and Restoration in JavaScript

    This article presents a browser-based experiment for image frequency-domain doodling and restoration, implemented entirely in vanilla JavaScript. It covers five modes: inverse-matrix mapping, magnitude spectrum, phase spectrum, joint magnitude-and-phase doodling, and row-derivative domain. For each mode, it explains the transform logic, masking strategy, expected visual degradation, and key implementation details, along with the overall data flow, interaction design, performance considerations, and common pitfalls. All computation runs locally with no image uploads, making it suitable for teaching demos, algorithm prototyping, and interactive lab pages.

    Image Frequency-Domain Doodling and Restoration in JavaScript

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

    Image processing has a counterintuitive but critical property: the visual information in an image is not spread evenly across pixels. Instead, it is highly redundant across different representation spaces. If you transform an image into another representation space, keep or destroy only a subset of the coefficients, and then transform it back, the result may look almost unchanged or may become completely unrecognizable. Building a “doodle-and-restore” experiment around this phenomenon is the most intuitive way to understand image representation, compression coding, and robustness.

    This article implements the full experiment in the browser using vanilla JavaScript, with five modes: restoration after doodling in an inverse-matrix mapping domain, in the magnitude spectrum, in the phase spectrum, in both magnitude and phase jointly, and in the row-derivative domain. All computation happens locally, no image is uploaded, and the result works well as a teaching demo, an algorithm prototype, or an interactive experiment page.

    2. Overall Architecture and Data Flow

    An interactive experiment page is best split into four layers with clear responsibilities, so any implementation can be swapped out:

    • Capture layer: load the user-selected image, resize it to a fixed working size (for example, 256×256 or 512×512), and convert it to grayscale or per-channel floating-point arrays.
    • Transform layer: map pixel-domain data into the target representation domain (spectrum, derivative domain, or matrix-mapping domain).
    • Doodling layer: modify coefficients in the target domain using a mask drawn by the user or generated programmatically.
    • Inverse transform and presentation layer: transform the modified coefficients back to the pixel domain, clip and normalize the values, and draw them to a canvas.

    The data flow can be summarized as:

    1. original image -> preprocessing -> forward transform -> coefficient-domain doodling -> inverse transform -> post-processing -> display

    Three engineering constraints matter: the forward and inverse transforms must be strictly inverse to each other; intermediate data must use floating-point arrays rather than 8-bit integers to avoid accumulated truncation error; and every step needs its own debug visualization entry point so you can pinpoint which layer a problem comes from.

    3. Mode 1: Doodling and Restoration in the Inverse-Matrix Mapping Domain

    Inverse-matrix mapping applies a reversible linear transform matrix to image blocks or to the flattened whole-image vector to rearrange and mix values. You then doodle on the transformed coefficients and multiply by the inverse matrix to restore. Its value is that it demonstrates energy diffusion: a local change in the original pixels is mixed by the matrix across many coefficients, so after restoration a local doodle appears as a global, soft degradation rather than a local color patch.

    Implementation sketch:

    1. // Reversible linear mixing per block; A is invertible, invA is its inverse
    2. function forward(block, A) { /* matrix multiply: A * block */ }
    3. function inverse(coef, invA) { /* matrix multiply: invA * coef */ }
    4. // Doodling: attenuate coefficients according to the mask
    5. coef[i] *= mask[i] ? 0.0 : 1.0;

    Numerically, pay attention to the stability of matrix inversion. For slightly larger sizes, avoid constructing an explicit inverse matrix; use pivoted Gaussian elimination or an orthogonal construction instead, and reproduce the inverse operation from the same transform parameters so the round-trip error stays within an acceptable range.

    4. Mode 2: Magnitude Spectrum Doodling and Restoration

    The 2D discrete Fourier transform decomposes an image into magnitude and phase. The magnitude spectrum describes “which frequency components exist and how much energy each carries,” and visually appears as bright spots arranged symmetrically around the center or the corners. The observed behavior is very stable: blacking out the central region of the magnitude spectrum weakens overall contrast and texture, but outlines and recognizability often remain; destroying the magnitude spectrum over a large area makes the image hazy and collapses detail.

    It is recommended to implement a separable 2D transform yourself instead of depending on an external library:

    1. function fft1D(re, im) { /* in-place 1D fast Fourier transform */ }
    2. function fft2D(re, im, inverse) {
    3. // Transform every row with the 1D transform, then every column
    4. }
    5. // Magnitude spectrum doodling: keep phase, attenuate magnitude
    6. const mag = Math.hypot(re[k], im[k]);
    7. const scale = mask[k] ? 0 : 1;
    8. re[k] *= scale; im[k] *= scale;

    Engineering details: spectrum shifting (moving low frequencies to the center) only affects visualization and mask coordinates, not the inverse transform; the mask should preserve conjugate symmetry about the origin, otherwise the inverse transform output contains an imaginary part, and you need to take the real part separately and explain where the error comes from.

    5. Mode 3: Phase Spectrum Doodling and Restoration

    The phase spectrum determines “where the structure is.” Destroying only the phase while keeping the magnitude usually produces an image that preserves the original energy distribution but has completely scrambled structure. This contrasts directly with the magnitude experiment and is the most convincing conclusion in this article: for most natural images, phase contributes more to recognizability than magnitude.

    The phase mask therefore needs to be designed differently from the magnitude experiment: the magnitude experiment can use concentric rings by radius, while the phase experiment is better suited to angular sectors or local patches, so you can observe how structural misalignment changes with position. Compute phase with the four-quadrant arctangent, and when reconstructing, recover the real and imaginary parts through cosine and sine, avoiding the wrap-around jumps caused by linearly interpolating angles directly.

    6. Mode 4: Joint Magnitude and Phase Doodling

    Joint doodling verifies whether the two degradations add up. In practice, light magnitude attenuation combined with light phase perturbation degrades the image by roughly the sum of the two effects acting alone; but once both enter the heavy-destruction range, the result quickly saturates into an almost uniform noise field, showing that the remaining information is no longer enough to support reconstruction. This mode is well suited to explaining the “information bottleneck” and threshold effects, and it is a reminder not to judge robustness by the energy share of a single domain alone.

    7. Mode 5: Row-Derivative Domain Doodling and Restoration

    The row derivative (a first-order difference along the horizontal direction) is a minimal high-pass representation that emphasizes vertical edges and suppresses flat regions. Doodling in the derivative domain selectively removes horizontal gradient information, and after restoration vertical edges are blurred while horizontal edges are preserved. Because differencing and accumulation are naturally inverse to each other, the round-trip error in this mode comes almost only from numerical precision, making it an ideal “zero-dependency, zero-error” baseline experiment for teaching.

    1. // Forward transform: first-order difference within each row
    2. d[i] = x[i] - x[i - 1];
    3. // Inverse transform: prefix sum; the first element must be stored separately
    4. x[0] = d[0]; x[i] = x[i - 1] + d[i];

    8. Interaction Design and Performance

    • Size and real-time behavior: spectrum-type transforms are about O(n log n); 512×512 completes in real time in mainstream browsers. For larger sizes, downsample before demonstrating.
    • Mask interaction: overlay a semi-transparent drawing layer on the canvas, write mouse or touch trajectories directly into the mask array, and trigger the inverse transform on release for instant feedback.
    • Numerical post-processing: clip inverse-transform results to [0,255] and optionally apply histogram normalization so a few out-of-range values do not skew the display.
    • Error visualization: provide a “round-trip error” view that shows the maximum absolute error of the forward and inverse transforms with no doodling applied, used to verify implementation correctness.
    • Accessibility and fallback: provide static result images for environments without canvas, and a “grayscale only, 256 size” fallback switch for low-end devices.

    9. Common Pitfalls

    1. Forgetting the correspondence between spectrum shifting and mask coordinates, so the painted area does not match expectations.
    2. Breaking conjugate symmetry with the mask, producing a visible imaginary part and artifacts after the inverse transform.
    3. Converting to 8-bit integers too early in the intermediate stages, amplifying error into blocky noise.
    4. Missing the base value of the first element in the difference inverse transform, causing a constant offset across the whole image.
    5. Validating conclusions on a single image only, ignoring differences caused by varying texture statistics.

    10. Summary

    Together, the five modes show one thing: redundancy varies greatly across representation domains, and doodling experiments are a low-cost way to quantify that variation. Running the whole pipeline in the browser with vanilla JavaScript for the forward and inverse transforms, mask drawing, and error checking yields a demo page with zero deployment cost, and it also serves as an experimental foundation for further work on image compression, watermark robustness, and feature stability.