Image Frequency-Domain Doodling and Restoration in JavaScript

    This article shows how to run image transform experiments entirely in the browser using native JavaScript APIs. It covers the shared three-stage pipeline of forward transform, controlled perturbation, and inverse transform, then walks through five modes: inverse matrix transforms, magnitude and phase spectra, and row derivatives. You will find implementation notes, code snippets, interaction and parameter recommendations, and troubleshooting tips for common artifacts such as darkened output, unreadable phase-doodled images, drift in row-derivative restoration, and numerical blow-up in the matrix approach.

    1. Why Run Image Transform Experiments in the Browser

    Image transform experiments used to depend on desktop numerical computing environments. With pixel-level access now available in the browser, the whole loop of transform, modify, and inverse transform can move into a web page. There are three immediate benefits: zero installation, since opening the page is enough to start interacting; instant feedback, with millisecond redraws after a slider moves; and easy sharing, since a single link lets anyone reproduce the experiment.

    Note that this article is not tied to any specific AI coding tool or third-party service. Everything here builds on native browser interfaces. If you later want to extend the experiment to the cloud, you can rely on general-purpose capability categories, such as object storage for the original and result images, logging services for recording parameter traces, and container platforms for batch compute jobs. These are common industry options and are not specific to any vendor.

    2. The Math: A Three-Stage Flow of Transform, Doodle, and Restore

    All five modes share the same skeleton:

    1. Forward transform: map the spatial-domain image into some transform domain.
    2. Doodle: apply controlled perturbation to the coefficients in that domain.
    3. Inverse transform: map the perturbed coefficients back to the spatial domain and observe the restoration result.

    2.1 Inverse Matrix Transform

    Let the forward transform matrix be A and the pixel column vector be x, so the transform-domain vector is y = A·x. Doodling means setting y’ = y + Δ, and restoration gives x’ = A⁻¹·y’. Since A⁻¹·A = I, x’ equals x exactly when nothing is perturbed. After perturbation, the error is linearly amplified by A⁻¹, and the amplification factor depends on the condition number of A. The larger the condition number, the more sensitive the doodling: even a tiny Δ can produce visible artifacts. In practice, verify the condition number with a small matrix first, then decide whether to use it on a large image.

    Sketch code (in the 2D case, one multiplication is needed for rows and one for columns):

    1. function matMul(A, B) { /* standard triple loop or blocked implementation */ }
    2. function inverse(A) { /* Gauss-Jordan elimination with pivoting */ }
    3. const y = matMul(A, imgVec);
    4. const yDirty = y.map((v, i) => v + noise[i]);
    5. const restored = matMul(inverse(A), yDirty);

    2.2 Magnitude Spectrum and Phase Spectrum

    The 2D discrete Fourier transform splits an image into a magnitude spectrum |F| and a phase spectrum φ. A widely observed rule in the field is that the magnitude spectrum carries texture and energy distribution, while the phase spectrum carries structure and position. Therefore:

    • Doodling only the magnitude spectrum: overall brightness and contrast are disturbed, but object outlines are largely preserved.
    • Doodling only the phase spectrum: structure is scrambled and the image becomes hard to recognize, while the energy distribution remains.
    • Doodling both: the two effects stack, making restoration the hardest and making this suitable for robustness stress testing.

    For the implementation, run a 2D FFT to get a complex matrix, take the modulus and argument separately, add noise, recombine in polar form, then run the inverse FFT. Note that spectrum centering (moving the zero frequency to the center) only affects visualization, not the numerical result.

    1. function fft2(re, im) { /* row transform + column transform */ }
    2. function ifft2(re, im) { /* inverse process, remember to divide by N */ }
    3. const { re, im } = fft2(srcRe, srcIm);
    4. const mag = re.map((v, i) => Math.hypot(v, im[i]));
    5. const pha = im.map((v, i) => Math.atan2(im[i], re[i]));
    6. const magDirty = mag.map(v => v * (1 + eps * (Math.random() - 0.5)));
    7. const re2 = magDirty.map((m, i) => m * Math.cos(pha[i]));
    8. const im2 = magDirty.map((m, i) => m * Math.sin(pha[i]));
    9. const out = ifft2(re2, im2);

    2.3 Row Derivative

    The row derivative takes a first-order difference along the vertical direction: d(x, y) = f(x, y+1) − f(x, y). It replaces absolute brightness with the rate of brightness change, so doodling the row derivative is equivalent to perturbing edge strength. Restoration first requires a cumulative sum over the doodled derivative, then adding back the boundary condition (the first-row pixels). Because the accumulation process accumulates error, tall images tend to drift. Block-wise accumulation is recommended, or inserting an absolute reference every N rows.

    1. const deriv = new Float32Array(w * (h - 1));
    2. for (let y = 0; y < h - 1; y++)
    3. for (let x = 0; x < w; x++)
    4. deriv[y * w + x] = data[(y + 1) * w + x] - data[y * w + x];
    5. // Restore after doodling
    6. const out = new Uint8ClampedArray(w * h);
    7. for (let x = 0; x < w; x++) out[x] = data[x]; // first row as the anchor
    8. for (let y = 1; y < h; y++)
    9. for (let x = 0; x < w; x++)
    10. out[y * w + x] = out[(y - 1) * w + x] + derivDirty[(y - 1) * w + x];

    3. Engineering Notes for the Five Modes

    1. Unified pipeline: wrap read pixels, forward transform, doodle, inverse transform, and write pixels into pluggable operators, so modes only swap the middle two steps.
    2. Doodle strength normalization: numerical magnitudes differ greatly across transform domains, so normalize by standard deviation before adding noise to avoid saturating any single path.
    3. Boundary handling: the FFT implies periodic boundaries, the row derivative implies a first-row anchor, and the inverse matrix implies matrix invertibility. All three should be surfaced as hints in the UI.
    4. Performance: a pure JavaScript 2D FFT is already usable at moderate resolutions. For larger images, use downsampled previews, block processing, or move heavy computation to a general-purpose container platform for batch jobs.
    5. Visualization: taking the log of the magnitude spectrum before normalizing, and mapping the phase spectrum with a color wheel, noticeably improves readability.

    4. Interaction Design and Parameter Suggestions

    • Mode switching: use tabs for the five modes to avoid page navigation.
    • Strength slider: 0 to 3 times the standard deviation, defaulting to 0.5.
    • Live comparison: split the screen left and right to show the original and restored images, with a difference heatmap overlaid.
    • Presets: offer light, medium, and heavy doodling for teaching demos.
    • Export: bundle parameters and results into one download for easy reproduction.

    5. Common Issues and Tuning

    • The restored image is overall too dark: usually the inverse transform is not divided by the number of points, so check the normalization.
    • The image is completely unreadable after phase doodling: this is expected and shows that structural information is concentrated in the phase.
    • Streak drift appears in row-derivative restoration: switch to block-wise accumulation or insert anchor rows.
    • The inverse matrix method blows up numerically: check the condition number, then switch to an orthogonal transform or add a regularization term.

    6. Summary

    The five modes are essentially different projections of the same methodology: pick a reversible or approximately reversible transform, apply controlled perturbation in the transform domain, then observe how robust the inverse process is. Once you grasp this framework, you can not only reproduce the doodle-and-restore experiment but also carry it over to image watermarking, robustness evaluation, and teaching demos. All code is implemented with native browser APIs, so it drops directly into any front-end project and can later connect to general-purpose cloud capabilities for scale-out as needed.