JavaScript Image Frequency-Domain Scribbling and Restoration: Five Transform Modes
This article presents a pure JavaScript approach to image scribbling and restoration across five representation domains: an invertible matrix domain, the magnitude spectrum, the phase spectrum, both magnitude and phase together, and the row-derivative domain. It explains the mathematical intuition behind each mode, a unified four-step pipeline, key engineering concerns such as invertibility, numerical precision, frequency-domain centering, normalization, and interactive performance, and includes runnable code skeletons. Readers will learn how to interpret the restoration results of each mode and how to apply the technique to teaching, robustness evaluation, and feature-importance analysis.
1. Background and Overall Approach
In image processing and computer vision teaching and research, a very intuitive and effective experiment is to first transform an image into some “representation domain,” manually add scribbles there (occlusion, zeroing, random perturbation), and then transform back to the pixel domain to observe the result. By comparing the differences “before damage” and “after restoration,” you can quantitatively or qualitatively judge how much a given representation component contributes to the image content.
The value of this kind of experiment shows up in three main areas:
- Teaching value: it turns abstract linear algebra and Fourier analysis into interactive visual phenomena.
- Analytical value: it assesses how much a model or algorithm depends on specific frequency bands or specific structural information, which supports interpretability and robustness analysis.
- Engineering value: it provides intuitive support for tasks such as image compression, denoising, watermarking, and feature selection.
The overall implementation follows a unified four-step pipeline:
- Load the image and convert it to a grayscale matrix (or process it channel by channel).
- Map the pixel domain to the target representation domain through some invertible transform.
- Perform the scribbling operation in the representation domain (interactive and parameterized).
- Apply the inverse transform to return to the pixel domain, then normalize and visualize for comparison.
Because every step runs in the browser with no server involvement, this is well suited to a single-page application or a teaching plugin. If you need to keep experiment records, you can write the result images and parameters to object storage in a generic way, or download them as local files.
2. Mathematical Intuition Behind the Five Modes
2.1 Invertible Matrix Transform Domain
Pick an invertible matrix A (for example, a discrete cosine transform matrix, a Hadamard matrix, or a randomly generated invertible square matrix) and apply linear combinations to the image row by row or column by column: Y = A·X. Scribbling means zeroing or perturbing selected elements of Y, and restoration gives X’ = A⁻¹·Y’. The key factor is the condition number of A: the larger the condition number, the more visibly the restoration error is amplified after scribbling, which by itself makes a good demonstration of numerical stability.
2.2 Magnitude Spectrum Domain
A 2D discrete Fourier transform of the image yields a complex spectrum F(u,v)=|F|·e^{jφ}. The magnitude spectrum |F| describes the strength distribution of each frequency component, with energy concentrated in low frequencies. To see the structure clearly, you need to center the magnitude spectrum (multiply by (-1)^{u+v}) and then apply logarithmic compression log(1+|F|) for visualization. Scribbling on certain regions of the magnitude spectrum mainly shows up after restoration as changes in overall brightness and contrast, plus blurred detail.
2.3 Phase Spectrum Domain
The phase φ(u,v) carries structural position information. Many experiments show that phase often affects recognizability more than magnitude. After scribbling the phase and restoring, the common result is misaligned object contours and broken structures, while some texture statistics are still preserved. In engineering terms, watch out for phase wrapping: reconstructing the complex values with cos/sin before the inverse transform is the safer route.
2.4 Scribbling Magnitude and Phase Simultaneously
Damaging both at once usually produces a restored image that is close to noise or severely degraded. This serves as a control baseline for “complete information loss” and can be used to calibrate the relative strength of the previous modes.
2.5 Row Derivative Domain
Apply a first-order difference to each row, d(i,j)=x(i,j)-x(i,j-1), scribble the difference sequence, and then restore it with a prefix sum. The difference emphasizes horizontal high frequencies and edges; after scribbling, horizontal texture is erased while vertical structure is relatively preserved, making this an intuitive case for understanding anisotropic information.
3. Key Engineering Implementation Points
Implementing the flow above in pure JavaScript in the browser calls for attention to a few points:
- Invertibility and numerical precision of the transform: store intermediate results in double-precision float arrays (Float64Array) to avoid accumulated error from repeated quantization.
- Frequency-domain centering: multiply by (-1)^(x+y) before and after Fourier-type transforms; otherwise low frequencies shift to the center, leading to wrong visualization and wrong judgment of the scribble region.
- Normalization: after the inverse transform, take the real part, apply min-max normalization to 0–255, and write it back to the canvas.
- Interactive performance: cache the transform result and recompute only the inverse transform while scribbling; for larger images, downsample first or use block processing to avoid blocking the main thread, and move work to a worker thread when necessary.
- Parameterization: the scribble radius, intensity, and target region (center low frequencies / outer high frequencies / random block) should all be adjustable to make comparison experiments easy.
Illustrative code skeleton (some utility functions omitted):
// Grayscale conversion and matrix utilitiesfunction toGray(imgData, w, h) {const g = new Float64Array(w * h);for (let i = 0; i < w * h; i++) {g[i] = 0.299*imgData[i*4] + 0.587*imgData[i*4+1] + 0.114*imgData[i*4+2];}return g;}// 2D DFT (naive implementation for teaching; a fast algorithm can be swapped in)function dft2(re, im, w, h) {const R = new Float64Array(w*h), I = new Float64Array(w*h);for (let u = 0; u < h; u++) {for (let v = 0; v < w; v++) {let sr = 0, si = 0;for (let y = 0; y < h; y++) {for (let x = 0; x < w; x++) {const a = -2*Math.PI*(u*x/w + v*y/h);const p = re[y*w+x];sr += p*Math.cos(a); si += p*Math.sin(a);}}R[u*w+v] = sr; I[u*w+v] = si;}}return {R, I};}// Scribble: zero out frequency-domain points inside a circle centered at (cx,cy) with radius rfunction scribble(R, I, w, h, cx, cy, r) {for (let y = 0; y < h; y++)for (let x = 0; x < w; x++)if ((x-cx)**2 + (y-cy)**2 <= r*r) { R[y*w+x]=0; I[y*w+x]=0; }return {R, I};}// Normalize after the inverse transform and draw back to the canvasfunction normalizeAndDraw(re, w, h, ctx) {let mn=Infinity, mx=-Infinity;for (let i=0;i<re.length;i++){ mn=Math.min(mn,re[i]); mx=Math.max(mx,re[i]); }const out = ctx.createImageData(w,h);for (let i=0;i<re.length;i++){const v = (re[i]-mn)/(mx-mn+1e-12)*255;out.data[i*4]=out.data[i*4+1]=out.data[i*4+2]=v; out.data[i*4+3]=255;}ctx.putImageData(out,0,0);}
The row derivative mode is even simpler:
function rowDiff(gray, w, h) {const d = new Float64Array(w*h);for (let y=0;y<h;y++){d[y*w] = gray[y*w];for (let x=1;x<w;x++) d[y*w+x] = gray[y*w+x]-gray[y*w+x-1];}return d;}function rowIntegrate(d, w, h) {const g = new Float64Array(w*h);for (let y=0;y<h;y++){g[y*w]=d[y*w];for (let x=1;x<w;x++) g[y*w+x]=g[y*w+x-1]+d[y*w+x];}return g;}
4. Interpreting Results and Best Practices
- Magnitude scribbling: destroying the low-frequency region degrades the image into blurry color blocks; destroying high frequencies removes detail and edges while the main subject stays recognizable.
- Phase scribbling: structural misalignment is the most obvious effect, showing that position information is mainly determined by phase.
- Invertible matrix scribbling: the degree of error amplification depends on the condition number, which makes it useful for demonstrating numerical instability.
- Row derivative scribbling: horizontal edges are erased while vertical structures remain, showing directional selectivity.
Practical advice: fix the random seed so experiments are reproducible; change only one variable at a time; save a three-panel comparison of the original image, the transform-domain image, and the restored image after scribbling; for color images, process channels independently and then recombine. For large-scale batch experiments, you can use container platforms and message queues to schedule tasks, and use logging services with monitoring and alerting to track success rates and elapsed time.
5. Summary
This article rebuilds the five modes of “image transform → scribble → restore” in a purely front-end way, covering the invertible matrix, magnitude spectrum, phase spectrum, the two combined, and the row derivative. It provides a unified four-step pipeline, key numerical handling, and a runnable code skeleton. Once you master this method, you can use it both as a visual teaching aid for Fourier analysis and linear algebra and as a starting point for practical tasks such as image robustness evaluation and feature-importance analysis.
