A Practical Guide to Frequency-Domain Image Doodling and Restoration

    This article explores how to apply reversible transforms to images, add doodle-based perturbations to their coefficients, and restore them back to the spatial domain. It walks through five modes—inverse matrix, magnitude spectrum, phase spectrum, combined magnitude and phase, and row derivative—explaining the mathematical intuition and implementation details behind each. Readers will also find practical advice on mask drawing, intensity control, quality evaluation, performance, and numerical stability for building browser-based interactive demos.

    1. Background and Overall Approach

    Building a browser-based interactive demo of “image transform → doodle → restoration” is fundamentally about validating one core idea: visual information in an image is not distributed uniformly across different representation domains. If you treat the pixel matrix as a signal, apply a reversible transform to redistribute its energy into another domain, perturb a subset of the coefficients, and then apply the inverse transform back to the spatial domain, you can directly observe which components carry structure and which carry detail.

    The overall workflow can be abstracted into four steps:

    1. Load the image and convert it into a grayscale or per-channel 2D array.
    2. Apply a reversible transform to obtain a coefficient matrix.
    3. Add doodles (mask + perturbation values) to the coefficient matrix.
    4. Apply the inverse transform back to the spatial domain, compare with the original image, and evaluate restoration quality and residual error.

    From an engineering standpoint, it is best to implement each step as an independent function for easy replacement and unit testing. A sketch of the code looks like this:

    1. function pipeline(imageData, forward, corrupt, inverse) {
    2. const coeff = forward(imageData); // forward transform
    3. const damaged = corrupt(coeff); // doodle perturbation
    4. return inverse(damaged); // inverse transform for restoration
    5. }

    2. Mathematical Intuition and Implementation Notes for Five Modes

    2.1 Inverse Matrix Transform Domain

    Split the image into $n\times n$ blocks, flatten each block into a column vector, and multiply it by a well-constructed invertible matrix $A$ to obtain transform-domain coefficients. Doodling is equivalent to adding a perturbation vector $e$ to the coefficients, and restoration uses $A^{-1}$ to recover the original.

    The key factor is the matrix condition number: the larger the condition number, the more noticeably perturbations are amplified, and the less controllable the restoration error becomes. Therefore, for demos, prioritize orthogonal or near-orthogonal matrices to ensure energy conservation and numerical stability.

    1. // Forward and inverse transforms for a 2x2 block
    2. const A = [[1, 1], [1, -1]];
    3. const Ainv = [[0.5, 0.5], [0.5, -0.5]];
    4. function forwardBlock(block) { /* matrix multiplication */ }
    5. function inverseBlock(coeff) { /* multiply by Ainv */ }

    2.2 Magnitude Spectrum Doodling and Restoration

    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 and determines the image’s energy distribution and overall brightness and contrast. Doodling on the low-frequency region at the center of the magnitude spectrum significantly changes overall brightness and contrast; doodling on high-frequency regions mainly affects edges and textures.

    In implementation, first perform a spectrum shift to move low frequencies to the center, making it easy to target them with circular or rectangular masks; after doodling, shift back and apply the inverse transform. Because the magnitude spectrum is relatively sensitive to perturbations, the restoration result usually shows a perceptible overall shift—which is exactly what you need to explain that “low frequencies carry global information.”

    2.3 Phase Spectrum Doodling and Restoration

    The phase spectrum determines the alignment relationships among sinusoidal components and has a major impact on structure, edges, and recognizability. A commonly observed phenomenon in experiments is: keep the magnitude and scramble the phase, and the image becomes hard to recognize; keep the phase and perturb the magnitude, and the structural outline often remains.

    Therefore, phase spectrum doodling is well suited to demonstrating that “structural information is mainly hidden in the phase.” In implementation, pay special attention to phase wrapping and numerical normalization; before the inverse transform, the phase must be restored to the correct interval, otherwise a global misalignment will occur.

    2.4 Simultaneous Doodling of Magnitude and Phase

    Applying perturbations to both at the same time is the most severe case of information loss. It can be used to demonstrate progressive degradation: first apply a slight perturbation to the magnitude, then add a phase perturbation, and observe the process from “detail blurring” to “structural collapse.” From an engineering perspective, it is recommended to introduce an intensity parameter $\alpha$ to separately control the perturbation magnitude of the magnitude and phase, making comparison experiments and teaching explanations easier.

    2.5 Row Derivative Domain Doodling and Restoration

    Apply a first-order difference to each row to obtain a row derivative matrix; after doodling, restore it through accumulation (integration). This transform is linear and reversible, but it has accumulated error: a perturbation at the first point of a row propagates along the entire row. During demos, drift can be suppressed by fixing the first point or introducing a least-squares constraint—also excellent material for explaining “error propagation.”

    1. function rowDerivative(img) { /* first-order difference within each row */ }
    2. function rowIntegrate(deriv, firstCol) { /* accumulate and fill back the first column */ }

    3. Interaction and Engineering Implementation Tips

    • Mask drawing: capture strokes on an overlay canvas to generate a binary or Gaussian soft mask, avoiding hard edges that cause ringing.
    • Intensity control: provide a 0–1 slider for each mode, mapping in real time to the perturbation magnitude.
    • Restoration quality evaluation: use mean squared error or structural similarity for quantitative comparison, together with side-by-side views and difference heatmaps.
    • Performance optimization: keep the image size within 512; put forward and inverse transforms into a Web Worker to avoid blocking the main thread; use downsampling for previews when necessary.
    • Numerical stability: consistently use floating-point intermediate results, and clip to 0–255 only at the end to prevent overflow and truncation artifacts.

    4. Teaching Value and Extensible Directions

    These five modes form a progression from simple to advanced: from the invertibility of linear algebra, to the energy–phase division of labor in the frequency domain, and then to error propagation and constrained optimization. They can serve both as a classroom demonstration and as an introductory experiment for image coding, watermarking, and robustness research.

    Possible future extensions include: introducing multi-scale wavelet-like transforms for hierarchical doodling, adding combined perturbation of noise and compression, and connecting evaluation metrics to an automated comparison dashboard. If more computing power or large-scale asset management is needed, general cloud capabilities can be adopted—for example, object storage for assets, a container platform for deploying the demo service, and logging and monitoring services with alerting to track runtime metrics—turning a one-off frontend experiment into a sustainable online teaching and evaluation platform.