Frequency-Domain Doodle Restoration with the Fourier Transform: A Browser-Based Interactive Guide
This article explains how to build a browser-based interactive page for doodle-based image restoration in the frequency domain. It covers five transformation modes: matrix inverse, magnitude spectrum, phase spectrum, combined magnitude and phase, and row derivative. The page runs entirely in the browser using JavaScript, the Canvas API, and TypedArrays. Readers will see the core implementation steps, the performance trade-offs in a client-side setup, and what the tool shows about the properties of the Fourier transform.
1. Technical Background and Core Approach
Frequency-domain analysis is a classic and powerful tool in image processing. Spatial-domain methods operate directly on pixel values. Frequency-domain transforms instead represent an image as a superposition of frequency components, which lets developers view and edit an image in terms of frequency.
The interactive page works as follows. It decomposes the image into frequency-domain components using the discrete Fourier transform (DFT) or related matrix operations. Users doodle on these components by modifying their magnitude or phase information. An inverse transform then converts the modified data back into a viewable image. This shows the visual effects of frequency-domain operations and helps developers understand the properties of the Fourier transform.
The implementation runs entirely in the browser. It uses JavaScript, the Canvas drawing API, and TypedArrays for pixel-level computation. It does not depend on server-side resources or third-party libraries, which makes it highly portable and useful for learning.
2. Five Transformation Modes
The page offers five switchable modes, each with its own frequency-domain logic:
Doodling and restoration with the image matrix inverse: The page inverts the image matrix directly. Image matrices are usually not square, so the pseudo-inverse, such as the Moore-Penrose inverse, is often used as an approximation. After users doodle on some matrix elements, the image is rebuilt with the pseudo-inverse. This mode mainly helps users understand how the condition number and underdetermined problems affect reconstruction quality.
Doodling and restoration on the magnitude spectrum: The page performs a 2D DFT to get a complex spectrum, then separates the magnitude and phase. Users can only doodle on the magnitude spectrum, for example by brightening or darkening certain regions. The phase stays unchanged. During the inverse transform, the modified magnitude is combined with the original phase to form a new spectrum, which is then restored to an image. This mode shows how the magnitude spectrum determines the energy distribution of an image.
Doodling and restoration on the phase spectrum: This mode is the counterpart of the magnitude mode. Users can only modify the phase spectrum, and the magnitude keeps its original values. Phase carries structural information, so changing it usually distorts textures and contours noticeably. This makes the mode visually striking.
Simultaneous doodling on the magnitude and phase spectra: Users can edit both the magnitude and the phase. They can directly observe how the combined changes affect the restored result. This mode suits exploring the visual meaning of different frequency bands, including low, mid, and high frequencies.
Doodling and restoration on the row derivative: The page differentiates the image along the row direction to produce a gradient map. After users doodle in the gradient domain, the page reconstructs the original image by solving a Poisson equation. In the discrete case, this is a sparse linear system. This mode relates closely to practical applications such as edge enhancement and image inpainting.
3. Key Implementation Details
3.1 JavaScript Implementation of the 2D Discrete Fourier Transform
Implementing the DFT in JavaScript requires handling complex-number arithmetic. The following is a basic version of the core structure:
// Complex number objectclass Complex {constructor(re, im) { this.re = re; this.im = im; }add(o) { return new Complex(this.re + o.re, this.im + o.im); }mul(o) { return new Complex(this.re * o.re - this.im * o.im,this.re * o.im + this.im * o.re); }}// 1D FFT (iterative Cooley-Tukey)function fft(x) {const N = x.length;if (N <= 1) return x;// Butterfly operations and bit-reversal permutation (detailed code omitted here)// In practice, use the iterative version to avoid stack overflow from recursion}// 2D FFT: transform along rows first, then along columnsfunction fft2d(img) {let rows = img.length, cols = img[0].length;let res = Array.from({ length: rows }, () => Array(cols));// Apply a 1D FFT to each row// Apply a 1D FFT to each columnreturn res;}
Performance is a key bottleneck in the browser. A 2D FFT of a typical image, such as 512×512 pixels, requires millions of complex multiplications. Plain JavaScript may take seconds to finish. To keep the interaction smooth, you can use block-wise transforms or Web Workers for parallel computation.
3.2 Separating and Recombining Magnitude and Phase Spectra
Modifying the magnitude and phase requires working on the complex frequency-domain matrix. Let the spectrum be ( F(u,v) = R(u,v) + iI(u,v) ). Then:
- Magnitude: ( |F| = \sqrt{R^2 + I^2} )
- Phase: ( \phi = \arctan(I/R) )
When users doodle, they usually change the magnitude values directly, for example by increasing or decreasing the magnitude in a region. The phase remains unchanged. During the inverse transform, the complex values are rebuilt from the new magnitude and the original phase: ( F’ = |F|’ \cdot e^{i\phi} ).
// Assume mag and phase are Float32Array values, and mag2d and phase2d are their 2D views// Recombine with the new magnitude times exp(i * original phase)for (let i = 0; i < rows; i++) {for (let j = 0; j < cols; j++) {let newMag = mag2d[i][j]; // May be modified by user doodlinglet ph = phase2d[i][j];rf[i][j] = newMag * Math.cos(ph);ifr[i][j] = newMag * Math.sin(ph);}}
3.3 Implementing the Matrix Inverse
In JavaScript, matrix inversion usually relies on Gauss-Jordan elimination or LU decomposition. For non-square matrices, the pseudo-inverse ( A^+ = (A^TA)^{-1}A^T ) is used, where ( A^T ) is the transpose of ( A ). Computing a pseudo-inverse at pixel scale is very expensive. For teaching demonstrations, you can run this mode on small images or downsampled images.
3.4 Row Derivative and Poisson Reconstruction
The row derivative transform first computes the horizontal gradient ( \nablax f = f(x+1,y) - f(x,y) ). After users doodle on the gradient map, the page must recover the image ( f’ ) that corresponds to the edited gradient. This can be formulated as a least-squares problem: ( \min{f’} ||\nabla_x f’ - g||^2 ). Its solution satisfies the discrete Laplace equation. In practice, you can call an iterative solver directly, such as Jacobi iteration or the conjugate gradient method.
4. Complete Code Skeleton and Interaction Logic
The core of the page follows this workflow:
- Upload an image: Read the image file, draw it onto a Canvas, and get the pixel array from
ImageData. - Select a mode: Send the pixel array to the pipeline for the selected transform type to produce a frequency-domain or gradient-domain representation.
- Visualize the frequency domain: Draw the transformed result, such as a log-scaled magnitude spectrum, onto a second Canvas to serve as the doodle base layer.
- Doodle: Listen for mouse or touch events, draw white, black, or colored strokes on the Canvas, and update the values at the corresponding coordinates in the transform domain in real time.
- Inverse transform and restoration: Run the inverse transform required by the mode, then draw the restored pixel data back onto the main Canvas.
The following simplified code shows the main flow for magnitude-spectrum restoration:
async function processImage(mode) {const imgData = ctx.getImageData(0, 0, width, height);const gray = rgbToGray(imgData); // Extract the grayscale matrixlet transformDomain, inverseTransform;if (mode === 'magnitude') {transformDomain = fft2d(gray);// Separate the magnitude spectrum and normalize it for display// Let the user doodle on the magnitude spectrum// Combine with the original phase and run the inverse transform ifft2d} else if (mode === 'phase') {// Similar logic, but only the phase can be modified}// ...Pipelines for the other modesdrawToCanvas(inverseTransform);}
5. Performance Optimization and Interaction Considerations
Browser-side JavaScript has limited computing power, so the implementation requires the following trade-offs and optimizations:
- Downsampling: When processing large images, resize them to 128×128 or 256×256 before running the transform. This greatly reduces computational cost while keeping enough visual detail.
- Intensity scaling: The dynamic range of a magnitude spectrum is large, so the spectrum is often barely visible when displayed directly. Apply ( \log(1 + |F|) ) or normalization before display.
- Incremental updates: While a user keeps dragging to doodle, the page does not need to rerun the FFT on the whole image. It can update only the frequency coefficients in the modified region and then run the inverse transform. However, the DFT couples all coefficients globally, so local-update optimization has limited room. A full-image inverse transform is usually still required.
