JavaScript Image Frequency-Domain Doodling and Restoration: A Practical Guide

    This article explores how to apply doodles in different transform domains and restore images using JavaScript. It covers five modes—inverse matrix, magnitude spectrum, phase spectrum, combined magnitude and phase, and row derivative—along with their mathematical foundations, implementation details, performance considerations, and best practices for numerical stability and reproducible experiments.

    1. Background and Overall Approach

    In image processing and front-end visualization, an interesting class of problems works like this: first transform an image into an intermediate domain, add artificial doodles there (occlusion, smearing, or random perturbation), and then try to recover the original image through an inverse transform. This process demonstrates the reversibility of transforms and reveals how sensitive different representations are to information loss.

    The five modes provided in the original material are the inverse matrix domain, magnitude spectrum domain, phase spectrum domain, simultaneous magnitude and phase doodling, and row derivative domain. Together they form an experimental framework of “transform—perturb—restore.” This article restructures that framework and fills in the mathematical principles, implementation details, and engineering considerations.

    The overall workflow can be abstracted into four steps:

    1. Read pixel data into a 2D numerical matrix.
    2. Apply a forward transform to enter the target domain.
    3. Write perturbations into the target domain along user-drawn trajectories.
    4. Apply an inverse transform to return to the spatial domain and render the restored result.

    2. Mathematical Foundations of the Five Modes

    2.1 Inverse Matrix Mode

    Treat the image as a matrix A and compute its inverse A⁻¹. The doodle is applied directly to the elements of the inverse matrix, and restoration requires inverting it once more. This mode is extremely sensitive to perturbations: small changes in inverse matrix elements are amplified during back-substitution, so the restored image often shows obvious numerical explosion or structural collapse. The implementation must handle numerical stability, for example by regularizing singular matrices to avoid division by zero and overflow.

    2.2 Magnitude Spectrum Mode

    The 2D discrete Fourier transform decomposes an image into a magnitude spectrum and a phase spectrum. Doodling only on the magnitude spectrum changes the strength of each frequency component. After restoration, most contours and structures remain, but brightness and texture are weakened. This is a typical case of “structure remains, details are lost.”

    2.3 Phase Spectrum Mode

    The phase spectrum carries key information about edges, positions, and alignment in an image. After doodling on the phase spectrum, even if the magnitude spectrum is completely unchanged, the restored image may suffer severe misalignment and structural breakdown. This mode best illustrates the dominant role of phase in perception.

    2.4 Simultaneous Magnitude and Phase Doodling

    When both are perturbed at the same time, information loss accumulates, and the restoration result is usually the worst. This mode is suitable as a control experiment to quantify the contribution weights of different domains.

    2.5 Row Derivative Mode

    Apply a first-order difference to each row to obtain a row derivative matrix. The doodle acts on the derivatives, and restoration reconstructs each row through accumulation (integration). Because integration accumulates errors, deviations caused by doodling spread along the row direction, forming stripe-like artifacts.

    3. JavaScript Implementation

    In the browser, you can use a canvas to obtain the pixel array and then convert it into a floating-point matrix. The following is illustrative code:

    1. function toMatrix(imageData, w, h) {
    2. const m = new Float64Array(w * h);
    3. for (let i = 0; i < w * h; i++) m[i] = imageData.data[i * 4] / 255;
    4. return m;
    5. }
    6. function dft2D(mat, w, h) {
    7. // Apply a 1D transform to each row first, then to each column
    8. // Return two matrices: { re, im }
    9. }
    10. function idft2D(re, im, w, h) {
    11. // Inverse transform; note the 1/(w*h) normalization
    12. }
    13. function applyMask(re, im, mask, w, h) {
    14. for (let i = 0; i < w * h; i++) {
    15. if (mask[i]) { re[i] = 0; im[i] = 0; }
    16. }
    17. }

    Three engineering points need attention. First, normalization and de-normalization between pixels and the floating-point matrix. Second, the normalization factor of the transform must be consistent before and after; otherwise the restored image will be overall too bright or too dark. Third, the doodle mask should be generated in real time from pointer events and then mapped to target-domain coordinates.

    4. Performance and Experience Optimization

    A pure front-end pixel-by-pixel 2D transform has high complexity. The following strategies are recommended: process in blocks with asynchronous scheduling to avoid blocking the main thread; reuse intermediate results between row and column transforms; downsample during the low-frequency preview stage and run full-resolution computation only after confirming the interaction is correct; update the mask incrementally and recompute only affected regions. For large data volumes, you can leverage general parallel computing capabilities or archive intermediate matrices with object storage and logging services to make experiments reproducible.

    5. Interpreting Results and Best Practices

    The comparison of the five modes reveals a clear pattern: the phase domain is the most fragile, the magnitude domain is next, the row derivative domain produces directional artifacts, and the inverse matrix domain is the most sensitive to numerical conditioning. In practice, prioritize numerical stability before discussing interaction smoothness. At the same time, record the mask, transform parameters, and restoration results together to form a reproducible experimental loop.