Image Frequency-Domain Doodling and Restoration in JavaScript
This article explains how to build an interactive JavaScript image-processing experiment that transforms an image into a representation space, applies doodles or noise, and reconstructs it with an inverse transform. It presents a unified pipeline covering five representations—inverse-matrix transforms, magnitude spectrum, phase spectrum, joint magnitude-and-phase editing, and row derivatives—along with browser implementation details, performance practices, and common numerical pitfalls. Readers will learn what information each representation carries and how to extend the framework to other transforms.
1. Background and Overall Approach
In digital image processing, there is a highly intuitive teaching and experimental exercise: first transform an image into another “representation space,” freely scribble, mask, or add noise in that space, then transform it back to the original space to observe how badly the image is destroyed—or preserved. The source material lists five modes: inverse-matrix-based transforms, the magnitude spectrum, the phase spectrum, joint magnitude-and-phase processing, and row derivatives. They look different on the surface, but they all share the same underlying flow.
We can abstract this flow into three steps:
- Forward transform
T: map the spatial-domain imagef(x,y)to a representationF = T(f); - Perturbation
D: apply doodling, zeroing, noise, or cropping toFin the representation space, producingF' = D(F); - Inverse reconstruction
f' = T⁻¹(F'): convert the perturbed representation back into a spatial-domain image.
As long as T is an invertible (or approximately invertible) linear transform, this framework holds. Once this is clear, the five modes are no longer five unrelated pieces of code but instances of the same abstraction under different bases. The rest of this article first establishes a unified engineering skeleton, then examines each representation’s information content, implementation details, and common pitfalls one by one.
2. A Unified Engineering Skeleton
In the browser, an image is carried by ImageData, whose data is a Uint8ClampedArray of length width * height * 4, arranged pixel by pixel in RGBA order. Every transform needs to first convert pixels into a floating-point array, then quantize back to 0–255 after processing.
// Extract a single-channel grayscale floating-point matrix from ImageDatafunction toGray(img) {const { width: w, height: h, data } = img;const g = new Float64Array(w * h);for (let i = 0, p = 0; i < data.length; i += 4, p++) {// Use the industry-standard luminance weighting coefficientsg[p] = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];}return { w, h, g };}// Quantize a floating-point matrix back to ImageData, with clamping and roundingfunction toImageData({ w, h, g }, ctx) {const out = ctx.createImageData(w, h);for (let p = 0, i = 0; p < g.length; i += 4, p++) {const v = Math.max(0, Math.min(255, Math.round(g[p])));out.data[i] = out.data[i + 1] = out.data[i + 2] = v;out.data[i + 3] = 255;}return out;}
A unified dispatcher can be written as follows; adding a new mode only requires registering a forward/inverse transform pair:
const MODES = {// key: mode name, forward: forward transform, inverse: inverse transform};function pipeline(img, mode, draw) {const gray = toGray(img);const F = MODES[mode].forward(gray);draw(F); // doodle in the representation spacereturn toImageData(MODES[mode].inverse(F), ctx);}
3. Information-Carrying Differences Among the Five Representations
3.1 Inverse-Matrix-Based Transform
This refers to flattening the image into vectors block by block, then multiplying by an invertible matrix to rearrange or mix them, and multiplying back by its inverse after processing. Let each block after partitioning be a column vector x and the transform matrix be A; the forward transform is y = A x, and reconstruction is x' = A⁻¹ y'. If several components of y are zeroed, the reconstruction is equivalent to projecting the original block onto a subspace of A, and the image shows directional blur or stripes.
Implementation notes:
Amust be numerically invertible; the size is usually a small block such as 8×8 or 16×16 to control the computational cost;- Inversion can use Gauss–Jordan elimination with partial pivoting to avoid numerical blow-up caused by small pivots;
- Doodles should act on the coefficients rather than directly on pixels, so the meaning of “transform-domain perturbation” is preserved.
3.2 Doodling and Restoration on the Magnitude Spectrum
The 2D discrete Fourier transform decomposes an image into a magnitude spectrum |F(u,v)| and a phase spectrum φ(u,v). The magnitude spectrum describes the energy strength of each frequency component and determines the overall brightness gradation and coarse texture detail. Painting the central (low-frequency) region of the magnitude spectrum black makes the reconstructed image look gray overall with details gone; erasing the periphery (high frequency) blurs the edges.
Engineering-wise, note spectrum centering: after the transform, shift the zero-frequency point to the array center so the doodle positions match intuition, then shift it back before the inverse transform.
function fftShift(re, im, w, h) {const out = new Float64Array(w * h);for (let y = 0; y < h; y++)for (let x = 0; x < w; x++) {const sx = (x + (w >> 1)) % w, sy = (y + (h >> 1)) % h;out[y * w + x] = re[sy * w + sx]; // handle the imaginary part the same way}return out;}
3.3 Doodling and Restoration on the Phase Spectrum
The phase spectrum carries structural information. The classic result is: keeping only the phase with a constant magnitude still yields a recognizable outline, while keeping only the magnitude with the phase zeroed makes the content nearly unrecognizable. Therefore, doodling on the phase spectrum is usually far more destructive than on the magnitude spectrum; smearing a local phase region causes geometric dislocation and a tearing sensation in the corresponding area.
3.4 Joint Doodling on Magnitude and Phase
Perturbing both at once is the most thorough mode of destruction, suitable for demonstrating the extreme case where “information redundancy is destroyed.” In implementation, simply apply masks to the two arrays separately within the same loop, keeping the mask shapes in one-to-one correspondence for easy comparison experiments.
3.5 Doodling and Restoration on Row Derivatives
The row derivative is the first-order difference along the horizontal direction, d(x,y) = f(x,y) − f(x,y−1); it highlights vertical edges and suppresses slow horizontal variation. Its inverse transform is accumulation along the row direction, which requires an initial value for each row (usually 0 or the first-row pixel). Doodling on the derivative is equivalent to injecting a constant bias into certain rows; after reconstruction, those rows show an overall staircase-like brightness jump, while the horizontal texture is barely affected. This intuitively demonstrates the property that “the difference representation is sensitive to vertical-direction perturbations.”
function rowDiff(g, w, h) {const d = new Float64Array(w * h);for (let y = 0; y < h; y++)for (let x = 0; x < w; x++)d[y * w + x] = g[y * w + x] - (y ? g[(y - 1) * w + x] : 0);return d;}function rowIntegrate(d, w, h) {const g = new Float64Array(w * h);for (let y = 0; y < h; y++)for (let x = 0; x < w; x++)g[y * w + x] = d[y * w + x] + (y ? g[(y - 1) * w + x] : 0);return g;}
4. Interactive Page and Performance Practices
A complete experiment page usually contains an original-image canvas, a representation canvas, a reconstruction canvas, plus mode switching, brush radius, and strength sliders. The brush uses a circular mask on the representation canvas to zero or scale values; on release, it triggers the inverse transform and refreshes the reconstruction canvas.
For performance, note:
- The naive 2D DFT has O(n⁴) complexity; use separable 1D transforms applied row by row and column by column to reduce it to O(n² log n);
- Use power-of-two sizes where possible to ease radix-2 butterfly operations;
- Throttle redraws with
requestAnimationFrameto avoid blocking the main thread while dragging the brush; - For large-scale or real-time scenarios, hand canvas data to
OffscreenCanvasor compute-intensive threads to keep the interface responsive.
5. Common Pitfalls and Summary
Numerically, dynamic-range stretching or clamping must be applied after the inverse transform; otherwise accumulation-type inverse transforms overflow easily. Evaluate the condition number before inverting the transform matrix. For spectrum doodling, prefer smooth transitions over hard edges in the mask to reduce ringing artifacts.
Overall, the value of the five modes lies not in the “doodling” itself but in interactively revealing the division of information across representations: magnitude handles energy, phase handles structure, differences handle direction, and invertible matrices handle subspace projection. Once you master the unified “transform–perturb–inverse transform” paradigm, you can freely extend it with more modes such as wavelets and the cosine transform, building your own image-representation experiment bench.
