Image Transform-Domain Doodling and Reconstruction in JavaScript

    This article explores how to build a browser-based image transform-domain doodling experiment in pure JavaScript. It covers five representations—inverse matrix transforms, magnitude spectrum, phase spectrum, combined magnitude and phase, and row derivatives—and explains how perturbations in each domain affect reconstruction. It also provides a web implementation skeleton, key engineering details, numerical stability and performance practices, and quality evaluation metrics.

    1. Why Doodle in a Transform Domain?

    The source material is a single-page web experiment generated by an AI coding tool: users manually paint perturbations onto a representation of an image and then observe how the reconstruction changes. The value of the experiment is not the doodling itself, but that it visualizes a core fact in image processing—the same image can be described by multiple equivalent representations, and different representations carry different semantic information. Perturbations applied to different representations cause drastically different types of reconstruction degradation.

    Implementing this kind of experiment in a purely front-end environment requires solving three things at once: forward and inverse transforms for each representation, interactive perturbation injection, and numerical stability and performance. The sections below go through each representation type.

    2. Four (Plus One) Representations and Their Doodling Semantics

    2.1 Inverse Matrix Transform Representation

    Treat the image as a block matrix, apply a reversible linear transform (such as an orthogonal basis transform) to each block, perturb the transform coefficients, and then reconstruct with the inverse matrix. The mathematical skeleton is:

    1. // Apply a reversible transform to a single block and reconstruct; coeff is the perturbed coefficient
    2. function inverseTransform(block, basis) {
    3. const coeff = matMul(basis, block); // forward transform
    4. const dirty = coeff.map((v, i) => v + noise[i]); // inject perturbation
    5. return matMul(transpose(basis), dirty); // inverse transform
    6. }

    The intuitive takeaway: the perturbation lands in the coefficient domain, and the reconstruction error is “spread out” across the whole block of pixels by the basis matrix, so the doodle looks blurry and global.

    2.2 Magnitude Spectrum Doodling

    After a 2D discrete Fourier transform of the image, take the magnitude of the complex spectrum to get the magnitude spectrum. The magnitude spectrum describes “the strength of each frequency component,” and doodling out a region is equivalent to erasing textures and structures at certain scales. Reconstruction uses the original phase and the modified magnitude:

    1. const F = fft2(image); // complex spectrum
    2. const mag = Math.hypot(F.re, F.im);
    3. const phase = Math.atan2(F.im, F.re);
    4. const dirtyMag = paint(mag); // doodle on the magnitude spectrum
    5. const rec = ifft2(polar(dirtyMag, phase));

    Empirical rule: painting over low-frequency regions destroys the overall tone and light/dark structure of the image; painting over high-frequency regions makes the image blurry but the main subject is still recognizable.

    2.3 Phase Spectrum Doodling

    Phase describes “the relative position of each frequency component” and is key to structural localization. Keeping the original magnitude and perturbing the phase usually preserves the original colors and energy distribution, but object contours shift and structures rearrange, producing an eerie “right texture, wrong structure” effect. The implementation is symmetric to the magnitude spectrum mode—just swap the object being doodled.

    2.4 Doodling Magnitude and Phase Simultaneously

    Injecting perturbations into both at once produces a reconstruction that is closest to “complete destruction,” used to verify whether the conclusions from the previous two groups are additive. One engineering caveat: after the phase is modified, the magnitude and phase no longer satisfy the original conjugate symmetry, so conjugate symmetry must be explicitly reconstructed; otherwise the inverse transform output will have residual imaginary parts.

    2.5 Row Derivative Doodling

    Apply a first-order difference to each row to get a row-derivative representation, doodle on it, and then reconstruct by cumulative summation. Row derivatives are extremely sensitive to abrupt changes in the horizontal direction, so painting in this domain produces horizontally elongated, streak-like artifacts:

    1. // Row derivative forward transform and cumulative reconstruction
    2. const d = image.map(row => row.slice(1).map((v, i) => v - row[i]));
    3. paint(d);
    4. const rec = d.map(row => { const out = [row[0] ?? 0]; for (let i = 1; i < row.length; i++) out[i] = out[i-1] + row[i]; return out; });

    3. Web Implementation Skeleton

    A usable experiment bench has four layers: a canvas layer for side-by-side display of the original and the result; a representation layer for forward/inverse transforms; an interaction layer that maps mouse trajectories to representation-domain coordinates; and a control layer for mode switching, brush radius, perturbation strength, and reset.

    1. const state = { mode: 'phase', radius: 12, strength: 0.6 };
    2. function onStroke(pt) {
    3. const layer = currentRepresentation(); // current representation domain
    4. applyBrush(layer, pt, state.radius, state.strength);
    5. render(if reconstruct(layer));
    6. }

    Three key engineering details: first, forward and inverse transforms must be implemented as pairs and checked for round-trip consistency, with errors within floating-point tolerance; second, complex spectra should uniformly use either real/imaginary or magnitude/argument pairs to avoid type confusion; third, brush strength should be normalized to prevent accumulation overflow.

    4. Numerical Stability and Performance

    • Normalization: map inputs uniformly to [0,1] or [-1,1], and clip back to the valid range after the inverse transform to avoid overflow and clipping distortion.
    • Conjugate symmetry: the forward transform of a real image satisfies conjugate symmetry; after any manual modification, symmetry must be rebuilt to ensure the inverse transform output is real.
    • Complexity control: implement 2D transforms separably, reducing O(N⁴) to two 1D transforms at O(N²logN); during interaction, use downsampled previews and recompute at full resolution after the pointer is lifted.
    • Async and chunking: move heavy recomputation to a separate thread or split it across frames to avoid blocking interaction.

    5. Quality Evaluation and Teaching Value

    Evaluation can be done along three dimensions: mean squared error and peak signal-to-noise ratio measure overall degradation; structural similarity measures structure preservation; and spectral energy distribution measures whether the perturbation landed in the intended frequency band. Pedagogically, this experiment turns the abstract conclusion “representation choice determines semantic carriage” into an operable, comparable phenomenon, making it suitable as a cross-disciplinary practice for image processing and linear algebra. For larger-scale material or result retention, object storage can be used to save inputs and outputs, and a logging service can record parameter combinations for reproducibility and comparison.

    6. Summary

    The value of transform-domain doodling lies in using a minimal implementation to reveal the correspondence between representation and semantics: the inverse matrix domain produces global blur, the magnitude spectrum domain affects scale and structural strength, the phase spectrum domain determines structural localization, and the row derivative domain amplifies directional artifacts. Mastering the four engineering points—paired forward/inverse transforms, conjugate symmetry reconstruction, normalization, and complexity control—is enough to build a logically rigorous, reproducible image transform experiment platform in pure front-end code.