JavaScript Image Frequency-Domain Doodling and Restoration: A Practical Guide
This article explores how to transform an image into a transform domain, add doodles such as noise, stripes, or strokes, and then transform it back to observe the restored result using browser-side JavaScript. It covers five modes—inverse matrix, magnitude spectrum, phase spectrum, combined magnitude and phase, and row derivative—and explains why magnitude mainly carries energy and texture while phase carries structural position and edge alignment. Readers will find implementation essentials, performance trade-offs, and common debugging pitfalls for building interactive image-processing demos without a server.
1. Background and Overall Approach
In digital image processing, the “transform–perturb–inverse transform” pipeline is a classic experimental workflow. Its value goes beyond producing striking doodle effects: it helps developers understand directly how image information is encoded, which components determine contour structure, and which components determine brightness and texture.
The scenario discussed here can be summarized as follows: first map the original image from the spatial domain to a transform domain, manually add doodles in that domain (random noise, stripes, color blocks, or arbitrary strokes), and then transform back to the spatial domain to observe what changes in the restored image. Around this main thread, five typical modes can be explored:
- Inverse matrix mode: centered on matrix inversion in linear algebra, verifying the invertibility and numerical stability of the transform matrix.
- Magnitude spectrum doodling: perturbing only the magnitude information in the frequency domain.
- Phase spectrum doodling: perturbing only the phase information in the frequency domain.
- Combined magnitude and phase doodling: observing the destructive effect when both types of information are perturbed together.
- Row derivative doodling: perturbing in the first-order difference domain and then integrating to restore.
All implementations below are based on browser-side JavaScript, with no server dependency, making them easy to run locally and use for teaching demonstrations.
2. Mathematical Foundations and Transform Domain Selection
2.1 Why a Transform Domain Is Needed
Pixels in the spatial domain are the final visual result, but much structural information has been “averaged out.” A linear transform decomposes an image into a weighted combination of basis functions, and the weight distribution itself is a form of information representation. Common options include the discrete Fourier transform, the discrete cosine transform, and wavelet transforms. To keep the implementation simple in a pure front-end environment, this article mainly adopts a separable two-dimensional discrete cosine transform approach and describes it uniformly in matrix form.
2.2 Division of Labor Between Magnitude and Phase Spectra
A two-dimensional transform result is usually complex and can be written as “magnitude × phase factor.” A widely accepted empirical conclusion in the field is that magnitude mainly reflects the image’s energy distribution and texture strength, while phase mainly reflects structural position and edge alignment. Therefore:
- Doodling only the magnitude usually leaves the general contour intact, but brightness and contrast are disrupted.
- Doodling only the phase noticeably scrambles the image structure, sometimes making it completely unrecognizable.
- Doodling both simultaneously usually makes the restored result close to noise.
This rule is the theoretical anchor for all experimental phenomena in this article.
3. Implementation Essentials of the Five Modes
3.1 Inverse Matrix Mode
The core idea is to apply a linear mapping to image blocks with an invertible matrix and multiply by the inverse matrix during restoration. Three points need attention in implementation: the matrix must be strictly invertible; the numerical scale must be controlled to avoid overflow; and the inversion algorithm should use a stable implementation (such as Gauss–Jordan elimination with partial pivoting).
function invertMatrix(m) {const n = m.length;const a = m.map((row, i) => [...row, ...Array.from({length: n}, (_, j) => i === j ? 1 : 0)]);for (let col = 0; col < n; col++) {let pivot = col;for (let r = col + 1; r < n; r++) if (Math.abs(a[r][col]) > Math.abs(a[pivot][col])) pivot = r;[a[col], a[pivot]] = [a[pivot], a[col]];const d = a[col][col] || 1e-12;for (let j = 0; j < 2 * n; j++) a[col][j] /= d;for (let r = 0; r < n; r++) {if (r === col) continue;const f = a[r][col];for (let j = 0; j < 2 * n; j++) a[r][j] -= f * a[col][j];}}return a.map(row => row.slice(n));}
When doodling, you can add an offset to the transformed coefficients, and after restoration you will see a “color-tinted” block effect.
3.2 Magnitude Spectrum Doodling and Restoration
First apply a two-dimensional transform to the image to obtain a complex matrix, then take the modulus to get the magnitude spectrum. Doodling modifies only the modulus while keeping the phase unchanged; then recombine the complex values and apply the inverse transform. The key points are: preserve the original phase after magnitude doodling; take the absolute value after doodling to avoid negative values; and perform normalization and truncation after the inverse transform.
function fft1D(re, im, inverse) {const n = re.length;for (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]]; }}for (let len = 2; len <= n; len <<= 1) {const ang = (inverse ? 2 : -2) * Math.PI / len;const wr = Math.cos(ang), wi = Math.sin(ang);for (let i = 0; i < n; i += len) {let cr = 1, ci = 0;for (let k = 0; k < len / 2; k++) {const ur = re[i + k], ui = im[i + k];const vr = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci;const vi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr;re[i + k] = ur + vr; im[i + k] = ui + vi;re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;const ncr = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = ncr;}}}if (inverse) for (let i = 0; i < n; i++) { re[i] /= n; im[i] /= n; }}
3.3 Phase Spectrum Doodling and Restoration
This mode is symmetric to the previous one: keep the modulus and modify only the phase. Doodling can be done by adding a constant to the phase, adding a linear ramp, or adding random perturbations. Since structural information is concentrated in the phase, even a slight perturbation can make the image unrecognizable, making this the most visually striking mode in this set of experiments.
3.4 Combined Magnitude and Phase Doodling
Superimpose the two doodling approaches above and observe the cumulative destructive effect. In engineering practice, it is advisable to make the doodling intensity an adjustable parameter to compare restoration quality at different intensities, thereby validating the concept of “information redundancy.”
3.5 Row Derivative Doodling and Restoration
First apply a first-order difference (discrete derivative) to each row, doodle in the difference domain, and then restore by cumulative summation (integration). Because differencing amplifies high-frequency noise, after integration the doodle is “spread out” into a horizontal trailing smear, a visual feature unique to this mode. Note that the initial value for integration must be preserved; otherwise the overall brightness will drift.
4. Engineering Implementation and Performance Trade-offs
The biggest constraint of a pure front-end implementation is computing power. The following strategies are recommended:
- Block processing: split large images into 8×8 or 16×16 blocks and transform block by block to reduce the computation per pass.
- Use separable transforms: perform row transforms first and then column transforms, reducing complexity from the O(n⁴) level to roughly O(n²logn).
- Use
requestAnimationFrameto execute work across frames and avoid interface freezing. - Read and write pixels directly with
ImageDatato reduce intermediate object allocation. - Turn doodling intensity and mode switching into a parameter panel for repeated experiments.
For larger images, you can also consider moving the computation into a Web Worker, or relying on cloud container platforms and object storage for offline batch processing, with the front end responsible only for interaction and result display.
5. Common Pitfalls and Debugging Tips
- Missing normalization: forgetting to divide by the length after the inverse transform causes an overall brightness shift.
- Missing truncation: writing floating-point results directly into 8-bit channels causes overflow, so values must be clamped to 0–255.
- Incorrect complex recombination: changing only the modulus or only the phase easily produces the opposite of the expected effect.
- Boundary effects: block transforms create seams at block boundaries, which can be mitigated with overlap or windowing.
- Numerical stability: always use pivoting for matrix inversion; otherwise small perturbations get amplified into noise.
6. Summary
These five modes essentially answer the same question: where is an image’s structural information hidden? Through five paths—inverse matrix, magnitude spectrum, phase spectrum, combined magnitude and phase, and row derivative—doodling and restoration can be presented intuitively with a unified front-end code framework, revealing the division of labor among different transform domains. For developers, mastering this approach not only enables interesting interactive demos but also lays a solid transform-domain foundation for later work in image compression, denoising, watermarking, and feature extraction.
