Scribbling and Restoration in the Transform Domain: A JavaScript Implementation
This article explores why applying scribbles in the transform domain rather than the pixel domain produces fundamentally different visual degradation, and how five progressive modes behave. It covers the mathematical basis of the 2D DFT, the amplitude-phase decomposition, and the reversibility conditions required for restoration, then walks through an invertible-matrix baseline, amplitude-spectrum scribbling, phase-spectrum scribbling, combined amplitude-and-phase scribbling, and row-derivative-domain scribbling with prefix-sum restoration, with JavaScript examples. It closes with engineering guidance on performance and precision trade-offs, showing that recoverability depends on which class of information is destroyed rather than how much area is affected.
1. Background: Why Scribble in the Transform Domain Instead of the Pixel Domain
Scribbling directly in the pixel domain destroys locally visible information. Scribbling in the transform domain destroys the image’s structural information. The visual consequences are completely different, which is exactly what makes transform-domain scribbling such an intuitive experiment for observing how information is distributed across an image.
The 2D discrete Fourier transform (DFT) maps a spatial pixel matrix into a complex matrix, where each frequency point carries both a magnitude and a phase. The widely accepted rule of thumb is that phase mostly determines where the structure is, while magnitude mostly determines overall brightness and texture statistics. Perturbing the magnitude spectrum and the phase spectrum separately, then transforming back to the spatial domain, therefore yields markedly different degradation.
The five modes discussed here form a sequence that progresses from shallow to deep:
- Inverse matrix mode: apply a reversible linear transform to the coefficient matrix, verifying that “reversible means lossless.”
- Magnitude spectrum scribbling: keep the phase, destroy the magnitude.
- Phase spectrum scribbling: keep the magnitude, destroy the phase.
- Simultaneous magnitude and phase scribbling: stack the damage and watch the information redundancy run out.
- Row derivative domain scribbling: take a first-order difference along each row, process in the derivative domain, then accumulate back.
2. Mathematical Basis and the Reversibility Prerequisite
Let the image be a grayscale matrix $f(x,y)$ of size $M\times N$. Its 2D DFT is:
F(u,v) = Σ_x Σ_y f(x,y) · exp(-j2π(ux/M + vy/N))
The inverse transform is:
f(x,y) = (1/(MN)) Σ_u Σ_v F(u,v) · exp(+j2π(ux/M + vy/N))
The polar decomposition is the core of every experiment:
F(u,v) = A(u,v) · exp(j·P(u,v))A = |F| // magnitude spectrumP = atan2(Im, Re) // phase spectrum
Reversibility holds only when three conditions are met: the transform matrix is non-singular, numerical precision is sufficient, and boundary handling is consistent. If any single step is irreversible, the so-called “restoration” is merely an approximate reconstruction.
3. Implementation Notes for the Five Modes
3.1 Inverse Matrix Mode: The Baseline Experiment for Reversible Transforms
Apply a non-singular linear operator to the coefficient matrix (for example, a combination of elementary row operations), record its inverse operator, and substitute it back. The value of this mode is to establish a control baseline for “information was not destroyed”: as long as the operator is reversible and numerically stable, the restored result should match the original image pixel for pixel (with error at floating-point magnitude).
// Reversibility baseline: apply elementary transforms to the matrix and log the inverse operationsfunction applyInvertible(M) {const A = clone(M);const log = [];for (let i = 0; i < A.length; i++) {const k = (i * 7 + 3) % A.length; // row swap[A[i], A[k]] = [A[k], A[i]];log.push(['swap', i, k]);}return { A, log };}function invert(A, log) {const B = clone(A);for (let t = log.length - 1; t >= 0; t--) {const [, i, k] = log[t];[B[i], B[k]] = [B[k], B[i]]; // roll back in reverse order}return B;}
3.2 Magnitude Spectrum Scribbling: Structure Survives, Appearance Collapses
Keep the phase $P$, replace the magnitude with a scribbled $A’$, then recombine $F’ = A’ e^{jP}$ and apply the inverse transform. The typical observation is that the direction of contours is still recognizable, but brightness and texture statistics are completely rewritten. One engineering caveat: the dynamic range of the magnitude spectrum is extremely large, so it is advisable to apply log compression before scribbling and take the exponential afterward to restore, avoiding numerical overflow.
const logA = A.map(r => r.map(v => Math.log1p(v)));scribble(logA); // scribble in the log domainconst A2 = logA.map(r => r.map(v => Math.expm1(v)));const restored = inverseTransform(recombine(A2, P));
3.3 Phase Spectrum Scribbling: Structure Collapses, Statistics Survive
Keep the magnitude and perturb the phase. Visually this usually appears as “a discernible brightness distribution with completely unrecognizable content,” which inversely confirms the dominant role of phase in locating structure. Phase is a periodic quantity, so after scribbling it must be normalized to $(-\pi,\pi]$; otherwise the inverse transform will produce phase-wrapping artifacts.
3.4 Simultaneous Magnitude and Phase Scribbling
When both are perturbed at once, the degradation stacks, redundancy is exhausted, and restoration becomes essentially infeasible. This mode works well as an “information upper bound” experiment: it gives an intuitive answer — when structural information and statistical information are destroyed at the same time, the remaining recoverable information approaches zero.
3.5 Row Derivative Domain Scribbling and Accumulation-Based Restoration
First take a first-order difference along each row, $d(x,y)=f(x,y)-f(x,y-1)$, scribble in the derivative domain, then restore with a prefix accumulation. Because the difference is a linear operator and the boundary term is preserved separately, the accumulation can roll back exactly. As a result, “restoration” is lossless in un-scribbled regions, while scribbled regions show smearing along the horizontal direction.
function rowDerivative(img) {return img.map(row => row.map((v, x) => x === 0 ? v : v - row[x - 1]));}function rowIntegrate(d) {return d.map(row => {const out = new Array(row.length);out[0] = row[0];for (let x = 1; x < row.length; x++) out[x] = out[x - 1] + row[x];return out;});}
4. Engineering Implementation and Performance Trade-offs
A pure JavaScript 2D DFT has complexity $O(M^2N^2)$ and will visibly stutter on the browser main thread. Practical recommendations:
- Size control: scale down to 128×128 or 256×256 for experiments first, and enlarge only after the logic is verified.
- Separate real and imaginary parts: store the real and imaginary parts in two
Float64Arrayinstances to avoid the GC pressure caused by object allocation. - Chunking and asynchrony: process in row-based chunks and yield the main thread with time slicing so the interaction does not freeze.
- Precision strategy: use double precision for intermediate computation, and apply
clamp + roundonly when writing back to the canvas. - Reproducibility: generate scribble trajectories with a seeded pseudo-random sequence, making results easy to reproduce and compare.
If the data volume grows further, the heavy computation can be offloaded to the cloud: object storage can hold the images, a message queue can decouple tasks, a container platform can scale compute horizontally, and log services plus monitoring alerts can track latency and failure rates. On Baidu AI Cloud, this kind of “heavy compute plus lightweight front-end interaction” split is a common and reliable architectural choice.
5. Conclusion
The five modes together demonstrate one thing: the recoverability of an image depends on which class of information is destroyed, not on how large the destroyed area is. The inverse matrix and row derivative modes support exact restoration because their operators are reversible. Magnitude and phase scribbling each strike at statistical information and structural information respectively, with restoration quality decaying in sequence, and scribbling both at once exhausts the information redundancy. With this layered understanding, you can design schemes with controllable damage and verifiable restoration for scenarios such as image watermarking, robustness evaluation, and visualization teaching.
