Image Frequency-Domain Scribbling and Restoration in JavaScript
This article explores a classic image processing experiment: transforming an image into a specific domain, scribbling on it there, and transforming it back to observe the result. It covers five modes—inverse matrix, magnitude spectrum, phase spectrum, combined magnitude and phase, and row derivative—and explains how each domain carries information differently. You will find a modular JavaScript code skeleton, plus practical notes on numerical stability, normalization, and engineering tips for building an interactive demo.
1. Background and Overall Approach
In image processing and computer vision education and research, there is a classic experiment: first transform an image into a certain “domain,” scribble a few strokes in that domain, then transform it back and observe the result. The value of this experiment lies not in the scribbling itself, but in how it intuitively reveals the way different transform domains carry information—some domains handle “what it looks like,” some handle “where it is,” and some handle “edges and textures.”
The original material came from an interactive web note generated by an AI coding tool. It contained five modes: scribbling and restoration in the inverse matrix domain, in the magnitude spectrum, in the phase spectrum, in both magnitude and phase simultaneously, and in the row derivative domain. This article builds on that foundation with a neutral rewrite, stripping away specific product attributes and keeping only the general technical core. It also fills in implementation details, numerical stability handling, and engineering suggestions that were missing from the original.
The overall technical pipeline can be broken into four steps:
- Read in the image and convert it to a grayscale floating-point matrix;
- Apply a forward transform to obtain the coefficient matrix in the target domain;
- Add scribbles in the target domain (zeroing out a region, setting it to a constant, or adding noise);
- Apply the inverse transform and normalize the result back to a displayable range.
2. How Information Is Carried in the Five Transform Domains
2.1 Inverse Matrix Domain
Inverting a square matrix A is essentially solving a system of linear equations. When an image is divided into blocks and treated as a matrix, scribbling amounts to destroying the linear correlation within that block. The image restored by the inverse transform shows contamination across the entire block, because the inverse matrix is globally coupled: changing any single element affects all outputs. This explains why scribbling in the inverse matrix domain has the strongest “spreading” effect.
2.2 Magnitude Spectrum
After a 2D discrete Fourier transform, the magnitude spectrum describes the strength of each frequency component. Low frequencies are concentrated at the center (if the spectrum has been shifted), corresponding to overall brightness and contours; high frequencies correspond to edges and details. Erasing low frequencies leaves only fragmented edges; erasing high frequencies makes the image blurry.
2.3 Phase Spectrum
The phase spectrum determines the relative spatial position of each sinusoidal component. Experimentally, setting the magnitude to one and keeping only the phase still yields a recognizable outline upon reconstruction, showing that phase carries structural information. Destroying the phase causes the image to degrade into noise-like texture.
2.4 Scribbling on Both Magnitude and Phase
When both are damaged at the same time, structural information and energy distribution are lost together, and the restoration result is the closest to pure noise—the most destructive combination among the five modes.
2.5 Row Derivative Domain
Taking a first-order difference along each row means scribbling introduces a step in that row. The inverse process performs cumulative summation to restore the image, and the error accumulates and propagates along the row, forming horizontal stripes. This mode best demonstrates “how local tampering gets amplified by integration.”
3. Runnable Code Skeleton
Below is modular sample code with framework bindings omitted, making it easy to deploy in any front-end environment.
// 1. Convert image to grayscale matrixfunction toGray(imgData, w, h) {const m = new Float32Array(w * h);for (let i = 0; i < w * h; i++) {const r = imgData[i * 4], g = imgData[i * 4 + 1], b = imgData[i * 4 + 2];m[i] = 0.299 * r + 0.587 * g + 0.114 * b;}return m;}// 2. 2D FFT (row-column separation, reusing the 1D implementation)function fft2(re, im, w, h, inverse) {for (let y = 0; y < h; y++) fft1(re, im, y * w, 1, w, inverse);for (let x = 0; x < w; x++) fft1(re, im, x, w, 1, h, inverse);}// 3. Scribble: zero out a rectangular region in the target domainfunction scribble(re, im, w, h, cx, cy, rw, rh, mode) {for (let y = Math.max(0, cy); y < Math.min(h, cy + rh); y++) {for (let x = Math.max(0, cx); x < Math.min(w, cx + rw); x++) {const idx = y * w + x;if (mode === 'amp') { const p = Math.hypot(re[idx], im[idx]); if (p === 0) continue; const k = 0 / p; re[idx] *= k; im[idx] *= k; }if (mode === 'phase') { const p = Math.hypot(re[idx], im[idx]) || 1; re[idx] = p * Math.cos(0); im[idx] = p * Math.sin(0); }if (mode === 'both') { re[idx] = 0; im[idx] = 0; }}}}// 4. Row derivative and restorationfunction rowDeriv(m, w, h) { const d = new Float32Array(w * h); for (let y = 0; y < h; y++) for (let x = 1; x < w; x++) d[y * w + x] = m[y * w + x] - m[y * w + x - 1]; return d; }function rowIntegrate(d, w, h) { const m = new Float32Array(w * h); for (let y = 0; y < h; y++) { m[y * w] = 0; for (let x = 1; x < w; x++) m[y * w + x] = m[y * w + x - 1] + d[y * w + x]; } return m; }
4. Numerical Stability and Engineering Notes
- Normalization: after the inverse transform, divide by the total number of pixels and apply min-max stretching; otherwise the display will be overall too dark or overexposed.
- Zero-value protection: when zeroing the magnitude and extracting the phase, guard against division by zero; adding a tiny positive fallback value is recommended.
- Size constraints: the naive 2D transform has a complexity of O(n²logn). For demo pages, limit the side length to within 256, or process in blocks.
- Interaction feedback: overlay the scribble area with a semi-transparent mask, and render restoration results with double buffering to avoid flicker.
- Precision choice: Float32 is sufficient for demos; for teaching derivations, switch to Float64 to observe differences in error.
5. Teaching and Extension Suggestions
These five modes can be combined into a progressive set of experiments: first observe the global spreading in the inverse matrix domain, then compare the division of labor between magnitude and phase, and finally use the row derivative to illustrate the integration amplification effect. For a more engineering-oriented implementation, extract the transform kernels into independent modules, and use a message queue or logging service to record the parameters of each scribble for reproducible experiments; static assets can be placed in object storage, and the front end can be deployed through a container platform. When using AI coding tools to generate skeleton code, always manually review numerical boundaries and normalization logic—this is the key to whether the demo restores correctly.
