Image Frequency-Domain Doodling and Restoration in JavaScript

    This article presents a browser-only JavaScript framework for a hands-on image processing experiment: transform an image into an intermediate representation, draw doodles on that representation, then invert the transform and observe what survives. It covers a four-layer architecture (capture, transform, doodle, presentation), five transform modes (inverse affine matrix mapping, magnitude spectrum, phase spectrum, magnitude plus phase, and row derivative), brush and mask handling, performance optimizations, and a checklist of common pitfalls. Everything is implemented with native Canvas and TypedArray, with no third-party libraries required.

    1. Why Doodle-then-Restore Is Worth Doing

    In any learning path for image processing and computer vision, the Fourier transform, matrix mapping, and differential operators are unavoidable foundations. Pure formula derivation, however, rarely builds intuition. A highly effective way to teach and verify these ideas is to move an image into some intermediate representation, add artificial doodles there (occlusions, smears, random noise blocks), and then apply the inverse transform back to the pixel domain. You can then observe which doodles are preserved, which are “absorbed,” and what artifacts appear in the restored result.

    The value of this approach is threefold:

    1. It turns abstract transform properties into visible phenomena.
    2. It makes it easy to tell where structural information and where texture information actually live.
    3. It provides a reusable experimental framework for later work on image inpainting, watermarking, and robustness testing.

    Nothing here depends on a specific third-party library or online service. Every capability can be built with the browser’s native Canvas and TypedArray, so it can be embedded in any frontend project or teaching page.

    2. Overall Architecture

    A maintainable implementation splits the pipeline into four layers that communicate only through data contracts:

    • Capture layer: read pixels from an <input type=file> or a <canvas> into a Uint8ClampedArray, convert them to a grayscale Float32Array, and pad the dimensions to powers of two (which makes the FFT easier).
    • Transform layer: each of the five modes implements a matching pair of forward and inverse functions with identical signatures.
    • Doodle layer: takes the current intermediate representation plus brush parameters, returns the modified representation, and records the doodle mask.
    • Restoration and presentation layer: runs the inverse transform, normalizes, optionally pastes the mask back, and writes the result to a display canvas.

    A sketch of the interface contract:

    1. // Unified transform contract
    2. const MODES = {
    3. invMatrix: { forward, inverse, label: 'Inverse matrix mapping' },
    4. ampSpec: { forward, inverse, label: 'Magnitude spectrum' },
    5. phaseSpec: { forward, inverse, label: 'Phase spectrum' },
    6. bothSpec: { forward, inverse, label: 'Magnitude + phase' },
    7. rowDeriv: { forward, inverse, label: 'Row derivative' },
    8. };

    Writing the contract first means the UI layer never needs to know the internal math. Adding a mode is just registering one more object.

    3. Math Intuition and Implementation Notes for the Five Modes

    3.1 Inverse Matrix Mapping

    Mapping pixel coordinates (x, y) to new positions through an invertible 2D affine matrix is equivalent to applying a combination of rotation, scaling, and shear. The key requirement is a non-zero determinant; otherwise the mapping is not invertible.

    The implementation uses inverse mapping to avoid holes: for every pixel in the target image, multiply by the inverse matrix to get the source coordinate, then sample with bilinear interpolation. Doodling happens on the transformed image, and the inverse transform is simply “multiply by the inverse matrix once more.”

    1. function makeAffine(a,b,c,d,tx,ty){
    2. const det = a*d - b*c;
    3. if (Math.abs(det) < 1e-8) throw new Error('Matrix is not invertible');
    4. return { a,b,c,d,tx,ty, det,
    5. inv: { a:d/det, b:-b/det, c:-c/det, d:a/det,
    6. tx:(c*ty-d*tx)/det, ty:(b*tx-a*ty)/det } };
    7. }

    Practical tip: for pixels outside the bounds, prefer edge extension over zero padding, otherwise the restored image shows obvious black borders.

    3.2 Magnitude Spectrum Doodling

    Apply a 2D discrete Fourier transform to the grayscale image to get a complex matrix; its modulus is the magnitude spectrum. The magnitude spectrum describes the strength of each frequency component, with low frequencies clustered at the center (after fftshift) and high frequencies toward the periphery.

    The doodling strategy directly determines the look:

    • Doodle the low frequencies at the center: overall brightness and contours are erased, and the restored image keeps only scattered edges.
    • Doodle the high frequencies at the periphery: texture and sharpness drop, and the restored image turns blurry but remains recognizable.

    The implementation reuses the same phase, replaces only the magnitude, and then applies the inverse transform. Because the magnitude changed, the inverse result must be renormalized to 0–255.

    3.3 Phase Spectrum Doodling

    The phase spectrum describes the alignment relationship among frequency components. A classic result in cognitive science is that phase carries more recognizable structure. Doodling the phase can therefore cause large-scale misalignment, ghosting, and structural collapse even when only a small region is modified, whereas doodling the magnitude usually just blurs the image.

    This is the comparison the article emphasizes most: blurring means information is smoothed, while misalignment means information is rearranged. They look completely different.

    3.4 Doodling Magnitude and Phase Together

    Modifying both at once is a “compound perturbation” in the frequency domain. In practice, record two separate masks and paste them back separately after restoration to compare single-factor and dual-factor damage. This mode is best suited for robustness demonstrations.

    3.5 Row Derivative Doodling

    Take a first-order difference along each row, d(x) = f(x+1) - f(x), to get a horizontal derivative image. This removes the DC component (average brightness) of each row, so restoration requires storing each row’s starting value or mean as an “integration constant.”

    This is the only one of the five modes that must keep extra state, which makes it ideal for explaining the boundary conditions of invertibility:

    1. // Forward: store each row's first value
    2. const base = new Float32Array(h);
    3. for (let y=0;y<h;y++){ base[y]=row[y*w]; for(let x=0;x<w-1;x++) row[y*w+x]=row[y*w+x+1]-row[y*w+x]; }
    4. // Inverse: accumulate from the first value
    5. for (let y=0;y<h;y++){ let v=base[y]; row[y*w]=v; for(let x=1;x<w;x++){ v+=row[y*w+x-1]; row[y*w]=v; } }

    4. Doodle Layer and Mask Pasting Details

    • Abstract every brush as (cx, cy, radius, hardness), which internally generates a Float32Array weight map where 0 means untouched and 1 means fully covered.
    • The intermediate representation may be complex-valued or a derivative (containing negative values), so doodling should be a blend rather than an assignment: out = rep*(1-w) + src*w.
    • The mask must be scaled in both directions between the transform domain and the pixel domain. Store it in normalized [0,1] coordinates to avoid misalignment when sizes change.
    • Provide a “show mask area only” toggle so you can verify that differences between the restored result and the original really come from the doodles.

    5. Performance and UX Optimizations

    1. Implement the FFT iteratively with radix-2 and precompute the twiddle factor table to avoid repeated trigonometric calls; pad dimensions to powers of two.
    2. Downsample large images to an edge length of at most 1024 pixels for interactive preview, then run once at full resolution after the mouse is released.
    3. Move all heavy computation into a Web Worker so the main thread only draws and frames are not dropped.
    4. Use Float32Array instead of plain arrays for intermediate representations to reduce boxing overhead.
    5. Key the result cache by “original image hash + mode + brush sequence” to support undo and replay.
    6. If you need to persist experiment records, use general-purpose category capabilities (for example, object storage for images and a logging service for the operation sequence). Do not hardcode any vendor-specific API in the client.

    6. Common Pitfalls

    • Forgetting fftshift, so low frequencies are not centered and doodle positions do not match expectations.
    • Not taking the real part after the inverse transform, which produces colored noise.
    • Not handling masked regions specially during normalization, causing extreme value overflow where the doodles are.
    • Not saving the integration constant in row derivative mode, so the overall brightness of the restored image drifts.
    • An affine matrix close to singular, where interpolation amplifies error into radial artifacts.
    • Applying a 0–255 brush strength directly to a floating-point intermediate representation, which is a magnitude mismatch.

    7. Conclusion

    “Transform, doodle, restore” is an extremely low-cost, high-information-density paradigm for teaching and validating image processing. The five modes cover five typical cases: invertible mapping, frequency-domain magnitude, frequency-domain phase, compound perturbation, and differential invertibility. Decouple the architecture into the four layers of capture, transform, doodle, and presentation, register modes through a unified contract, and you can reliably reproduce every experiment in a pure frontend environment while building a reusable code base for later image inpainting and robustness evaluation.