JavaScript Image Transform-Domain Doodling and Restoration
This article explores how to doodle on and restore images across five transform domains using browser-side JavaScript and Canvas. It covers the mathematical foundations, including the 2D discrete Fourier transform, magnitude and phase spectra, and the row-derivative domain, then walks through implementation details for inverse-matrix, magnitude-spectrum, phase-spectrum, combined magnitude-and-phase, and row-derivative modes. It also shares performance practices such as resolution control, offloading transforms to workers, caching forward results, log compression, and smooth brushes, along with conclusions on which perturbations are hardest to recover.
1. Background: Why Doodle in the Transform Domain
In image processing, masking or smearing pixels directly in the spatial domain destroys the most immediately visible information. If you first map an image into a transform domain, apply a local perturbation there, and then return to the spatial domain through an inverse transform, you get an interesting effect: the image looks altered, yet its structure remains recoverable. The value of this experiment is more than a visual toy. It reveals how image information is distributed across different representations: which components carry contours, which carry brightness, and which are more sensitive to local damage.
This article presents five interactive transform-domain doodling and restoration modes, all implemented in the browser with JavaScript and Canvas, with no server-side computation:
- Doodling and restoration on the image inverse matrix
- Doodling and restoration on the image magnitude spectrum
- Doodling and restoration on the image phase spectrum
- Simultaneous doodling and restoration on both magnitude and phase spectra
- Doodling and restoration on the image row derivative
2. Mathematical Foundations: From Spatial Domain to Transform Domain
2.1 The 2D Discrete Fourier Transform
For a grayscale image f(x,y) of size M×N, its 2D discrete Fourier transform 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))
Two points matter in an engineering implementation. First, apply the equivalent centering operation $(-1)^{x+y}$ so the low frequencies of the spectrum move to the center, making it easier for the human eye to inspect and for the mouse to target. Second, you must implement reusable complex-number arithmetic and a fast transform structure; otherwise a purely recursive implementation degrades to $O(M^2N^2)$ time complexity and freezes the browser main thread.
2.2 Magnitude and Phase Spectra
The complex result can be written in polar form:
F(u,v) = A(u,v) · exp(jφ(u,v))A(u,v) = |F(u,v)| magnitude spectrumφ(u,v) = atan2(Im, Re) phase spectrum
A widely accepted empirical conclusion in the field is that the phase spectrum carries more structural and positional information, while the magnitude spectrum mainly affects overall brightness and the energy distribution of texture. This point is repeatedly confirmed in the “restoration quality comparison” later in the article.
2.3 The Row-Derivative Domain
The row derivative is a lightweight linear transform in the spatial domain: take the adjacent difference along each row to obtain a set of one-dimensional sequences representing the vertical gradient.
d(x,y) = f(x,y+1) - f(x,y)
Its inverse process only requires prefix-sum accumulation to restore the original exactly, which makes it well suited for teaching demonstrations of “reversible doodling.”
3. Implementation of the Five Modes
3.1 Inverse-Matrix Mode
The “inverse matrix” in engineering usually means inverting a transform matrix and then applying it to a coefficient vector. In practice, the matrix may be singular or nearly singular, so you must add a regularization term or use pseudo-inverse handling; otherwise a single doodle can make the entire restoration diverge into pure noise. A recommended approach is to first check the order of magnitude of the determinant, then decide whether to use direct inversion or truncated singular values.
3.2 Magnitude-Spectrum Doodling
The flow is: forward transform → take the magnitude → smear on the magnitude map with the mouse → recombine using the original phase and the new magnitude → inverse transform. Since the phase is untouched, the contours are largely preserved, but brightness and contrast are noticeably rewritten. This is the most visually “gentle” of the five modes.
3.3 Phase-Spectrum Doodling
Only the phase is changed while the magnitude is preserved. The experimental phenomenon is striking: even a small smear causes the main structure to shift and edges to break, and after restoration, artifacts often remain even if the phase is restored. This shows that phase contributes far more to structural positioning than magnitude.
3.4 Simultaneous Magnitude and Phase Doodling
When both are perturbed at once, the damage is additive. In engineering, pay attention to the distance between the smear radius and the low-frequency region at the spectrum center: the closer to the center, the larger the share of energy destroyed per unit area, and the restoration difficulty rises nonlinearly.
3.5 Row-Derivative Doodling
Smearing in the difference domain is equivalent to artificially injecting a local integration-constant offset, which appears after restoration as horizontal stripe-like drift. Because the inverse process is accumulation, the error propagates along the row direction; therefore, the farther left the smear position, the wider the affected range.
4. Engineering Implementation and Performance Optimization
A browser-side implementation should follow this structure:
// Skeleton: a general pipeline for transform-domain doodlingfunction pipeline(img, domain, brush) {const coeff = forward(img, domain); // forward transformconst view = toVisual(coeff); // visualization (log compression)brush.stroke(view); // interactive doodlingconst dirty = fromVisual(view, coeff); // write coefficients backreturn inverse(dirty, domain); // inverse transform for restoration}
Practical performance recommendations:
- Resolution control. Spectrum computation is sensitive to size, so limit interactive previews to 256×256 or 512×512, and run once at full resolution after confirming the effect.
- Asynchronization. Put the transforms in a worker thread and let the main thread handle only drawing and event handling to avoid freezing the interface.
- Cache the forward transform result. The doodling phase only needs repeated inverse transforms, so caching coefficients can significantly reduce latency.
- Apply log compression to the magnitude display, i.e.,
log(1+A); otherwise the dynamic range is too large and the image is almost entirely black. - Change the brush to a smooth decay in the frequency domain rather than a hard overwrite, which noticeably reduces ringing artifacts after restoration.
5. Effect Comparison and Robustness Conclusions
Across the experimental behavior of the five modes, several stable conclusions emerge: phase perturbation causes the strongest structural damage, magnitude perturbation mainly affects brightness and contrast; simultaneous perturbation in both domains is the hardest to recover; perturbation in the difference domain has a directional error-propagation property; and the inverse-matrix mode with regularization is the most unstable when coefficients are ill-conditioned. Understanding these differences helps with model selection in scenarios such as image watermarking, reversible annotation, and teaching demonstrations.
6. Summary
Transform-domain doodling and restoration is a technically well-structured and highly interactive experiment. It turns abstract frequency-domain concepts into objects you can directly “touch” with the mouse, while also training a full set of front-end engineering skills: complex-number arithmetic, transform implementation, visualization mapping, and performance optimization. If you need to handle larger image data or reproduce the experiment across platforms, you can use object storage to save the original and restored results, and use logging services and monitoring alerts to track interaction performance metrics, turning a single classroom demonstration into a sustainable, iterable engineering asset.
