Pure-Frontend Image Frequency-Domain Doodling and Restoration: A Hands-On Practice

    This article presents a fully client-side web demo that lets users doodle directly on frequency-domain and other mathematical transforms of an image, then invert the transforms to observe how the image degrades or recovers. It covers five transform modes—matrix inversion, magnitude-spectrum doodling, phase-spectrum doodling, combined magnitude/phase doodling, and row-wise differentiation—along with a radix-2 FFT implementation in JavaScript, spectrum visualization, canvas-based brush interaction, and engineering notes on performance, numerical precision, and boundary conditions. The experiments visually confirm classic signal-processing conclusions: phase dominates structure, low frequencies dominate energy, differentiation loses DC information, and ill-conditioned matrices amplify perturbations.

    Pure-Frontend Image Frequency-Domain Doodling and Restoration: A Hands-On Practice

    1. Background and Motivation

    Many classic conclusions in digital image processing only truly make sense when you “break something with your own hands and then fix it.” For example: does the phase spectrum of an image really carry more information than the magnitude spectrum? What happens to the inverse transform after you doodle occlusions over a local region of the frequency domain? With these questions in mind, the author used AI-assisted coding tools (the web-based conversational capability of large language models, combined with deep-reasoning modes) to quickly generate a purely frontend demo page: after uploading an image or loading a default one, the user picks a transform mode, doodles on the transform result with the mouse, and then runs the inverse transform to observe how the image is damaged and restored.

    Small projects like this are ideal for prototyping with generative coding tools: the core algorithms (FFT, matrix operations) are well-known public methods, the tool translates the math into runnable Canvas code, and the developer focuses on interaction design and result analysis.

    2. Technical Principles of the Five Transform Modes

    2.1 Matrix Inversion Mode

    A grayscale image is treated as an N×N matrix A, and its inverse A⁻¹ is computed. Doodling is applied to the visualization of the inverse matrix, and a second inversion restores the image. Because a matrix inverse is extremely sensitive to perturbations (the condition number can be large), even light doodling causes noticeable global distortion in the restored image. This mode vividly demonstrates the concept of an “ill-conditioned matrix” in linear algebra—the decisive impact of numerical stability on computational results.

    2.2 Magnitude-Spectrum Doodling and Restoration

    The image undergoes a 2D discrete Fourier transform (DFT), and the result is decomposed into a magnitude spectrum |F(u,v)| and a phase spectrum φ(u,v). The user doodles on the magnitude spectrum (effectively zeroing or altering the magnitude of certain frequency components) while keeping the original phase, then runs the inverse DFT. Experiments show that painting over the low-frequency region (the center of the spectrum) severely destroys the overall brightness and contours of the image, while painting over high-frequency regions only costs detail and sharpness. This confirms the classic conclusion that “low frequencies determine structure, high frequencies determine detail.”

    2.3 Phase-Spectrum Doodling and Restoration

    This mode mirrors the previous one: the magnitude is kept intact and only the phase spectrum is tampered with. The result is often surprising—even destroying a small amount of phase makes the restored image almost unrecognizable, with edge structures completely scrambled. This shows that phase carries the geometric structure of an image, and its importance even exceeds that of magnitude. It is a highly persuasive set of experiments for signal-processing education.

    2.4 Simultaneous Magnitude and Phase Doodling

    Both types of damage are stacked, and the restored result is nearly pure noise. This mode works well as a control group for the previous two experiments, helping to illustrate the coupling between magnitude and phase.

    2.5 Row-Derivative Mode

    A first-order difference is applied row by row (equivalent to convolution with [1, -1]), producing a horizontal gradient map. After doodling on the derivative map, restoration is attempted through row-wise integration (cumulative summation). Because differentiation discards the DC component of each row (the starting pixel value), restoration must keep the original first column as a boundary condition; errors in doodled regions accumulate along the row during integration, forming horizontal stripe artifacts. This mode vividly demonstrates the numerical behavior of “differentiation loses information, integration amplifies error.”

    3. Frontend Implementation Highlights

    The entire page runs without any backend service. The core modules are:

    • Image loading and grayscale conversion: read the image via FileReader, draw it to a hidden Canvas, extract pixels with getImageData, and convert to grayscale with a weighted average, normalized to [0, 1].
    • FFT implementation: crop or scale the image to a power-of-two size (e.g., 256×256), then apply a radix-2 FFT to the rows and columns separately. Example code:
    1. function fft1d(re, im) {
    2. const n = re.length;
    3. for (let i = 1, j = 0; i < n; i++) { // bit-reversal permutation
    4. let bit = n >> 1;
    5. for (; j & bit; bit >>= 1) j ^= bit;
    6. j ^= bit;
    7. if (i < j) { [re[i],re[j]]=[re[j],re[i]]; [im[i],im[j]]=[im[j],im[i]]; }
    8. }
    9. for (let len = 2; len <= n; len <<= 1) {
    10. const ang = -2 * Math.PI / len;
    11. const wr = Math.cos(ang), wi = Math.sin(ang);
    12. for (let i = 0; i < n; i += len) {
    13. let curR = 1, curI = 0;
    14. for (let k = 0; k < len / 2; k++) {
    15. const aR = re[i+k], aI = im[i+k];
    16. const bR = re[i+k+len/2]*curR - im[i+k+len/2]*curI;
    17. const bI = re[i+k+len/2]*curI + im[i+k+len/2]*curR;
    18. re[i+k] = aR + bR; im[i+k] = aI + bI;
    19. re[i+k+len/2] = aR - bR; im[i+k+len/2] = aI - bI;
    20. const tR = curR*wr - curI*wi; curI = curR*wi + curI*wr; curR = tR;
    21. }
    22. }
    23. }
    24. }

    The inverse transform only requires negating the imaginary part, running the forward transform, and dividing by N.

    • Spectrum visualization: the dynamic range of magnitudes is enormous, so a logarithm (log(1+|F|)) is applied and stretched to 0–255, with the zero-frequency component shifted to the center (fftshift).
    • Doodling interaction: mouse events are listened to, and a circular brush with adjustable radius paints a mask on the transform-domain canvas. The masked region’s frequency-domain data is zeroed out (or set to a specified value), while an untouched copy is kept for comparison.
    • Restoration and side-by-side comparison: the inverse-transform result, the original image, and the doodled transform-domain view are displayed in three side-by-side panels for intuitive comparison.

    4. Engineering Optimizations and Caveats

    1. Performance: a 256×256 FFT requires on the order of a million complex operations in pure JavaScript, which typically completes in one to two hundred milliseconds on the main thread. For larger sizes, the computation should be moved into a Worker to avoid blocking interaction.
    2. Numerical precision: for matrix inversion mode, Gaussian elimination with partial pivoting (or an off-the-shelf general numerical-computing approach) is recommended, and the matrix should be checked for near-singularity after doodling.
    3. Boundary conditions: row-derivative restoration must preserve the first pixel of each row, otherwise the entire row’s brightness drifts.
    4. Color handling: to keep the focus on principles, the demo only processes grayscale. Extending to RGB means transforming the three channels separately, and the conclusions remain the same.

    5. Development Experience with AI-Assisted Coding Tools

    The complete page of roughly four to five hundred lines had its skeleton generated in one pass by an AI coding tool, after which the developer refined it through follow-up prompts: adding fftshift, brush-size controls, comparison views, and so on. Practical experience shows that stating precise mathematical definitions in the prompt (such as “radix-2 iterative FFT” or “log magnitude spectrum”) significantly reduces rework. After generation, numerical correctness must be verified independently—for example, testing the FFT’s conjugate symmetry with a unit impulse or a known pattern.

    6. Conclusion and Future Directions

    Through the five “damage-and-restore” experiments, readers can verify several core signal-processing conclusions at zero cost in the browser: phase dominates structure, low frequencies dominate energy, differentiation discards DC information, and ill-conditioned matrices amplify perturbations. The project consists entirely of static files and can be deployed directly to general-purpose static hosting services such as object storage, serving as a teaching demo or an interactive component in a personal technical blog. Possible extensions include doodling experiments with 2D wavelet transforms, comparisons with intelligent inpainting of doodled regions, and multi-channel analysis of color images.