Transform-Domain Scribbling and Restoration in JavaScript: From Magnitude Spectrum to Row Derivatives
This article presents an interactive JavaScript experiment that transforms grayscale images into different representation domains, allows users to scribble on those domains, and reconstructs the spatial image. It covers five modes: inverse-matrix representation, magnitude spectrum, phase spectrum, combined magnitude and phase spectrum, and row derivatives. The article explains the 2D DFT, spectrum centering, row-difference reversibility, FFT implementation, canvas-based painting interaction, observed visual effects, and performance practices such as power-of-two sizing, TypedArray storage, frame-throttled reconstruction, and isolated source data.
Transform-Domain Scribbling and Restoration in JavaScript: From Magnitude Spectrum to Row Derivatives
1. Background and Problem Definition
In digital image processing, direct pixel-space manipulation is the most intuitive approach, but many powerful capabilities are hidden in transform domains. The Fourier transform maps an image from the spatial domain to the frequency domain and decomposes it into magnitude and phase components. Difference operations reveal edges and texture information. A useful and instructive experiment is to transform an image into a representation domain, scribble freely on this “unfamiliar view,” and then apply the inverse transform to observe how the scribbles spread into the original image.
This experiment visually demonstrates the different roles that magnitude and phase play in image structure. It also helps developers understand why small changes in a transform domain can produce significant effects in the spatial domain. This article covers five modes:
- Scribbling and restoration on the inverse-matrix representation of the image
- Scribbling and restoration on the magnitude spectrum
- Scribbling and restoration on the phase spectrum
- Scribbling and restoration on both magnitude and phase spectra
- Scribbling and restoration on row derivatives (inter-row differences)
2. Core Technical Principles
2.1 2D Fourier Transform and Spectrum Decomposition
For an M×N grayscale image f(x, y), the 2D discrete Fourier transform (DFT) is:
F(u, v) = Σ Σ f(x, y) · exp(-j2π(ux/M + vy/N))
The result F(u, v) is a complex matrix that can be decomposed into:
- Magnitude spectrum: |F(u, v)|, which describes the strength distribution of each frequency component.
- Phase spectrum: ∠F(u, v), which describes the spatial location information of each frequency component.
A classic conclusion is that the phase spectrum carries key information about “where structure is” in the image. An image reconstructed using only the phase spectrum and discarding the magnitude spectrum can still reveal the original outline, while an image reconstructed using only the magnitude spectrum is almost unrecognizable. The scribbling experiment provides an interactive verification of this conclusion.
2.2 Spectrum Centering
By default, the low-frequency components of the DFT are distributed in the four corners. To make observation and scribbling easier, the original image is usually multiplied by (-1)^(x+y), or the spectrum is circularly shifted so that low frequencies are concentrated in the center. The centered low-frequency region corresponds to large smooth structures in the image, while the high-frequency region corresponds to edges and details. Scribbling on a centered spectrum makes the spatial distribution of the effect easier to predict and explain.
2.3 Row Derivative Representation
Applying a first-order horizontal difference (f(x, y) - f(x, y-1)) to an image produces a row derivative map. It highlights vertical edges and suppresses slow horizontal changes. The row derivative is an invertible linear transform: given the first column of pixels and the difference result, the image can be fully restored by accumulation (integration). When scribbles are applied and the image is restored, the scribbles are “accumulated and amplified” along the row direction, producing a typical streak-spreading effect.
3. Engineering Implementation
3.1 Overall Pipeline
The processing pipeline of the web application is:
Load image → Grayscale conversion → Forward transform → Render transform-domain view↓User scribbles on canvas↓Assemble modified transform data → Inverse transform → Render restored image
3.2 FFT Implementation
For images with power-of-two dimensions, the transform can be performed by row-wise and column-wise 1D FFTs, with an overall complexity of O(MN log N). The core butterfly operation is shown below:
function fft1d(re, im, inverse) {const n = re.length;// Bit-reversal permutationfor (let i = 1, j = 0; i < n; i++) {let bit = n >> 1;for (; j & bit; bit >>= 1) j ^= bit;j |= bit;if (i < j) {[re[i], re[j]] = [re[j], re[i]];[im[i], im[j]] = [im[j], im[i]];}}// Butterfly operationsfor (let len = 2; len <= n; len <<= 1) {const ang = 2 * Math.PI / len * (inverse ? 1 : -1);for (let i = 0; i < n; i += len) {for (let k = 0; k < len / 2; k++) {const a = ang * k;const wr = Math.cos(a), wi = Math.sin(a);const ur = re[i + k], ui = im[i + k];const vr = re[i + k + len / 2] * wr - im[i + k + len / 2] * wi;const vi = re[i + k + len / 2] * wi + im[i + k + len / 2] * wr;re[i + k] = ur + vr; im[i + k] = ui + vi;re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;}}}if (inverse) {for (let i = 0; i < n; i++) { re[i] /= n; im[i] /= n; }}}
The 2D transform is implemented by calling the 1D FFT on each row and each column.
3.3 Transform-Domain Canvas and Scribbling Interaction
Spectrum values have an extremely large dynamic range, so direct display appears almost black. A common approach is logarithmic mapping: display = log(1 + |F|), followed by normalization to 0–255. Scribbling occurs on the display canvas, but the actual complex data is modified. In magnitude-spectrum mode, for each pixel touched by the brush, the real and imaginary parts are reconstructed from the new magnitude value while the phase is preserved:
function paintOnMagnitude(x, y, brushValue) {const idx = y * width + x;const phase = Math.atan2(im[idx], re[idx]);const newMag = Math.pow(10, brushValue / 25 - 1); // Inverse log mappingre[idx] = newMag * Math.cos(phase);im[idx] = newMag * Math.sin(phase);}
Phase-spectrum mode does the opposite: magnitude is preserved and only the phase angle is modified. In the mode where magnitude and phase are scribbled simultaneously, the user-specified combination of real and imaginary parts is written directly.
3.4 Row Derivative Mode Implementation
Row derivative mode is relatively simple:
// Forward transform: first-order row differencefor (let y = 0; y < h; y++)for (let x = w - 1; x > 0; x--)diff[y][x] = gray[y][x] - gray[y][x - 1];// Inverse transform: cumulative restorationfor (let y = 0; y < h; y++)for (let x = 1; x < w; x++)restored[y][x] = restored[y][x - 1] + diff[y][x];
When one pixel is altered on the difference map, the overall grayscale of that row from the edited point onward shifts after the inverse transform, creating a typical “smearing” phenomenon. This directly illustrates the noise amplification effect of the difference operator.
4. Experimental Observations and Analysis of the Five Modes
- Magnitude spectrum scribbling: Modifying the low-frequency center causes drastic changes in overall image contrast and brightness. Modifying the high-frequency corner regions produces regular patterns or ringing effects.
- Phase spectrum scribbling: Even small phase perturbations severely disrupt image structure, producing ghosting and geometric distortion. This verifies the dominant role of phase in structure.
- Simultaneous scribbling: The effect is a superposition of magnitude and phase perturbations, usually appearing as energy redistribution accompanied by structural disruption.
- Inverse-matrix mode: The image is treated as a matrix. Scribbles are applied to its inverse representation and then restored. The scribbles are amplified by the linear mapping of the matrix inverse, and the effect depends on the eigenvalue structure at the edited position.
- Row derivative scribbling: As described above, this appears as an overall grayscale shift along the row and streak spreading.
5. Performance Optimization and Practical Recommendations
- Dimension constraints: Scale the input image to power-of-two dimensions (e.g., 256×256) so that a standard FFT can be used, avoiding the complexity of mixed-radix implementations.
- TypedArray: Use
Float64Arrayto store real and imaginary parts and avoid the boxing overhead of ordinary JavaScript arrays. - Scribbling debouncing: Brush events fire at high frequency, so inverse-transform computation should be frame-throttled (for example, with
requestAnimationFrame). Two 256×256 FFTs can finish in tens of milliseconds in modern browsers, which is sufficient for smooth interaction. - Data isolation: Always keep an original spectrum copy and rebuild restoration from “original data + scribble delta” to avoid error accumulation.
- Deployment form: A pure front-end application like this only requires static asset hosting. Object storage and content delivery can support low-cost deployment without server-side computation.
6. Conclusion
The transform-domain scribbling experiment turns abstract spectrum theory into an interactive and observable experience. By implementing the DFT, spectrum decomposition, difference transform, and their inverse processes in JavaScript, developers can deepen their understanding of image frequency-domain properties and learn a general engineering pattern of “transform—edit—restore.” This pattern also applies to a range of more complex image-processing tasks such as filtering, watermarking, and compression, making it a highly extensible starting point at the intersection of front-end development and image processing.
