Image Frequency-Domain Doodling and Restoration in JavaScript

    This article explores how to implement interactive image doodling and restoration in the frequency domain using native browser APIs in JavaScript. It explains why modifying a transformed representation changes structural information rather than local brightness, and presents a unified processing pipeline shared by five modes: inverse matrix, magnitude spectrum, phase spectrum, combined magnitude and phase, and row derivative. For each mode, it covers the underlying math, the visual behavior after doodling and inverse transformation, and key engineering concerns such as FFT implementation, mask generation, numerical robustness, performance, and accessibility. The experiments turn abstract transform-domain concepts into hands-on, verifiable phenomena for teaching and further extension.

    1. Why Doodle in a Transform Domain

    In image processing, painting a blob of ink directly onto pixels in the spatial domain changes only local brightness. Transforming an image into another representation space before doodling, however, usually alters structural information. An interesting phenomenon is that destroying the magnitude spectrum makes an image lose texture and contrast layers, while destroying the phase spectrum can completely misalign object contours. The two have an asymmetric impact on recognizability. Around this phenomenon, we can build a set of interactive web experiments: apply a reversible transform to an image, let the user freely draw on the transformed result, then run the inverse transform to observe the restored picture. The five modes provided by the original material—inverse matrix, magnitude spectrum, phase spectrum, combined magnitude and phase, and row derivative—cover three main threads: linear algebra, Fourier analysis, and differential operators. This makes them well suited for teaching demonstrations.

    It is worth emphasizing that this article does not depend on any specific online service or third-party product. All logic can be completed in the browser using native capabilities: the canvas API to read pixels, typed arrays to hold floating-point data, and web drawing APIs to render results. If the data scale is large, intermediate results can also be cached in object storage or a content delivery network, compute-heavy work can be offloaded to containerized tasks for asynchronous execution, and latency distributions can be observed through logging and monitoring services.

    2. A Unified Processing Pipeline

    All five modes share the same pipeline; the only differences are in the “transform” and “inverse transform” stages:

    1. Loading and grayscale conversion: draw the image onto an offscreen canvas, read the pixel data, and convert it into a single-channel floating-point array using a luminance-weighted formula.
    2. Size normalization: take an edge length of no more than 512 and pad or crop it to a power of two, balancing transform efficiency and memory usage.
    3. Forward transform: choose matrix inversion, a 2D Fourier transform, or row differencing according to the mode.
    4. Mask generation: listen for pointer events, accumulate strokes on the transform-domain canvas, and export them as a 0/1 mask.
    5. Applying the doodle: zero out, set to the mean, or add perturbation to the transform coefficients according to the mask.
    6. Inverse reconstruction: run the corresponding inverse transform, take the real part, and normalize to 0–255.
    7. Presentation and export: write the result back to the canvas, with support for before/after comparison and download.

    The following sample code illustrates how data is held:

    1. const N = 512;
    2. const re = new Float64Array(N * N);
    3. const im = new Float64Array(N * N);
    4. function toGray(img) {
    5. const c = document.createElement('canvas');
    6. c.width = N; c.height = N;
    7. const ctx = c.getContext('2d');
    8. ctx.drawImage(img, 0, 0, N, N);
    9. const d = ctx.getImageData(0, 0, N, N).data;
    10. for (let i = 0; i < N * N; i++) {
    11. re[i] = 0.299 * d[i * 4] + 0.587 * d[i * 4 + 1] + 0.114 * d[i * 4 + 2];
    12. }
    13. }

    3. The Math and Behavior of the Five Modes

    Inverse matrix mode. The image is treated block by block as several small matrices. User doodling is equivalent to modifying matrix elements, and restoration first computes the inverse and then back-substitutes. This demonstrates numerical stability: when a matrix is close to singular, inversion amplifies errors, and doodle marks are significantly amplified into noise. In engineering, regularization or pseudo-inverse ideas should be introduced to avoid division by zero and overflow.

    Magnitude spectrum mode. After the 2D Fourier transform, complex coefficients are obtained; taking the modulus yields the magnitude spectrum, and log compression plus centered shifting makes it easier to observe. Doodling on the magnitude spectrum and zeroing it before the inverse transform usually preserves the rough outline but smooths away detail texture, showing that magnitude carries energy distribution and texture statistics.

    Phase spectrum mode. Keeping only the phase and setting the magnitude to one before the inverse transform often still allows object structures to be recognized, confirming the dominant role of phase in structural positioning. Doodling on the phase, however, causes edges to misalign and produces ghosting and a torn appearance.

    Combined magnitude and phase mode. Destroying both at once makes the restored result close to noise. It serves as a control experiment, verifying the superposition effect of information destruction.

    Row derivative mode. Applying a first-order difference to each row yields a gradient representation in the horizontal direction. Doodling on the gradient and then integrating to restore produces horizontal smearing and staircase-like breaks, intuitively showing the sensitivity of differential operators to local abrupt changes.

    4. Engineering Implementation Notes

    • Transform implementation: a 2D Fourier transform can first apply a 1D transform to rows and then to columns, using an iterative fast algorithm with bit-reversal reordering to avoid recursion overhead.
    • Mask and strokes: use a second offscreen canvas to draw a semi-transparent brush, binarize by threshold on export, and make the brush radius adjustable to control the granularity of destruction.
    • Numerical robustness: take the real part after the inverse transform, normalize using the global maximum and minimum, and provide fallback replacements for NaN and infinite values.
    • Performance strategy: put heavy computation in a worker thread so the main thread only handles events and drawing; cache intermediate floating-point results on demand to avoid repeated transforms.
    • Interaction and accessibility: provide mode switching, brush size, undo, and reset; preserve focus order for keyboard operation and give textual descriptions.

    5. Teaching Value and Extension Directions

    The value of these experiments lies in turning abstract transform-domain concepts into hands-on, verifiable phenomena. Students will find that “removing magnitude” and “scrambling phase” cause completely different degrees of destruction, and they can also understand the ill-posed nature of inversion and the noise-amplification effect of differential operators. Further extensions include color multi-channel processing, windowing to reduce spectral leakage, using masks for frequency-domain filtering comparisons, or packaging the pipeline into a reusable general transform module, with monitoring and alerting to track the time cost of each mode and provide tuning guidance for processing larger images.