Image Frequency-Domain Doodling and Restoration in JavaScript
This article explores how to doodle on images in the transform domain and restore them using JavaScript. It covers four representations—inverse matrix, magnitude spectrum, phase spectrum, and row-derivative—along with their inverse operations, and explains why magnitude and phase differ sharply in robustness. You will also find the front-end architecture, weighted least-squares solving details, performance optimizations, and common engineering pitfalls. Readers will learn how to build an interactive browser-based tool that links linear algebra, Fourier analysis, and regularized solving.
1. Background: Why Doodle in the Transform Domain
In image processing, masking pixels directly in the spatial domain usually means irreversible information loss. Once a pixel is painted black, the original gray value cannot be recovered. But if you first map the image to another mathematical representation and then perturb it in the “coefficient domain,” the situation is completely different: some representations are highly redundant, and after a few coefficients are destroyed, the remaining coefficients still carry enough information to reconstruct the original image by solving an inverse problem.
This kind of experiment has high teaching value. It turns abstract concepts such as linear algebra, Fourier analysis, and numerical stability into an interactive process you can drag with a mouse and see results from instantly. This article focuses on four typical representations: the inverse matrix representation, the magnitude spectrum, the phase spectrum, and the row-derivative representation. It also discusses the case where magnitude and phase are doodled on at the same time.
It is worth emphasizing that this kind of “restoration” is not lossless compression or encryption, but an approximate solution to an ill-posed inverse problem. Restoration quality depends on representation redundancy, the doodling ratio, and the regularization strategy.
2. Mathematical Foundations: Four Representations and Their Inverses
Let the original image be a grayscale matrix $X \in \mathbb{R}^{N\times N}$. All transforms are required to be “invertible” or “approximately invertible.”
- Inverse matrix representation. Take an invertible matrix $A$ with a controllable condition number and let $Y = A X$. Doodling means setting some elements of $Y$ to zero or randomizing them to get $\tilde{Y}$. For restoration, solve $\min |X|_F^2 + \lambda|A X - \tilde{Y}|_F^2$, which is a standard Tikhonov-regularized least squares problem with the closed-form solution $X = (A^\top A + \lambda I)^{-1} A^\top \tilde{Y}$.
- Magnitude and phase spectra. The 2D discrete Fourier transform gives $F = \mathcal{F}(X)$. In polar form, $F = M \cdot e^{j\Phi}$, where $M$ is the magnitude spectrum and $\Phi$ is the phase spectrum. Doodling on the magnitude spectrum is equivalent to modifying $|F|$ while keeping $\Phi$; doodling on the phase spectrum is the opposite. Restoration is done by forming $F’ = M’ e^{j\Phi’}$ and applying the inverse transform $\mathcal{F}^{-1}$.
- Row-derivative representation. Let $D$ be the difference operator, so $Y = D X$ is the first-order difference along the row direction. Because the difference operator has a null space (constant rows), direct inversion is not unique and requires additional boundary conditions or a minimum-norm constraint.
The common feature of these four representations is that the forward transform is cheap, while the inverse transform requires solving a linear system or performing an inverse transform. Doodling destroys part of the equations, degrading the problem from “direct computation” to “constrained estimation.”
3. Why Magnitude and Phase Spectra Have Completely Different Robustness
This is the most insightful part of the whole experiment. The magnitude spectrum describes the energy distribution of each frequency component, with a smooth overall contour and weak local correlation. The phase spectrum encodes structural position information and appears visually as sharp edge textures.
- Doodling on the magnitude spectrum: Because the energy distribution has many approximate symmetries and smooth priors, occluded low and mid frequencies can be estimated by interpolation from neighboring frequency points. The restored image usually keeps recognizable structures, but contrast and detail levels decrease.
- Doodling on the phase spectrum: Phase determines “where the structure is.” Once key phases are destroyed, the inverse transform produces misplaced pseudo-structures, and the restored image is often severely distorted even at a very low doodling ratio.
- Doodling on both: Complementary information is weakened at the same time, making restoration the hardest and requiring stronger priors, such as total variation regularization.
The engineering takeaway is this: if you want a more fault-tolerant representation, prefer transforms with high redundancy and strong local correlation. If the representation itself is nearly orthogonal and has no redundancy, any masking brings irreversible loss.
4. Web Implementation Architecture
A pure front-end implementation can be done entirely in the browser, with no server required:
- Canvas layer: Use two canvases to display the original and restored images, plus an overlay canvas to capture mouse doodling trajectories.
- Data layer: Read pixels from the canvas, convert them to a grayscale Float64Array, and build an $N\times N$ matrix.
- Compute layer: Implement the 2D FFT (reusing two 1D FFTs over rows and columns), polar decomposition, inverse transform, and a least-squares solver.
- Interaction layer: Real-time control of mode switching, brush size, doodling ratio, and the regularization coefficient $\lambda$.
The sample code below shows the core data flow:
// Grayscale conversion and matrix constructionfunction toGray(imageData, n) {const X = new Float64Array(n * n);for (let i = 0; i < n * n; i++) {const r = imageData.data[i * 4];const g = imageData.data[i * 4 + 1];const b = imageData.data[i * 4 + 2];X[i] = 0.299 * r + 0.587 * g + 0.114 * b;}return X;}// Polar decomposition: magnitude and phase spectrafunction toPolar(re, im) {const n = re.length;const mag = new Float64Array(n);const pha = new Float64Array(n);for (let i = 0; i < n; i++) {mag[i] = Math.hypot(re[i], im[i]);pha[i] = Math.atan2(im[i], re[i]);}return { mag, pha };}// Rebuild the complex spectrum from magnitude and phase, then inverse transformfunction fromPolar(mag, pha) {const n = mag.length;const re = new Float64Array(n);const im = new Float64Array(n);for (let i = 0; i < n; i++) {re[i] = mag[i] * Math.cos(pha[i]);im[i] = mag[i] * Math.sin(pha[i]);}return { re, im };}
5. Solving Details for Doodling and Restoration
Both the inverse matrix mode and the row-derivative mode reduce to solving a sparse linear system. Since doodling affects only some observations, you can treat the undoodled positions as hard constraints and the doodled positions as soft constraints, forming a weighted least squares problem:
// Weighted least squares: W is the confidence weight, set to 0 at doodled positionsfunction solveWeighted(A, Y, W, lambda, n) {// Build the normal equations (A^T W A + lambda I) x = A^T W y// For large sizes, use conjugate gradient iteration to avoid explicit inversionreturn conjugateGradient(A, Y, W, lambda, n);}
In practice, it is recommended to keep the matrix size between 64 and 128 to ensure smooth interaction; scan $\lambda$ from small to large and observe the restored image transition from “over-smoothing” to “amplified pseudo-texture”; for phase-spectrum doodling, try doodling only in low-magnitude regions to verify the assumption that “structural information is concentrated in a few strong phase points.”
6. Performance and Experience Optimization
- Split the FFT into row and column transforms and reuse the 1D kernel, reducing complexity from $O(N^4)$ to $O(N^2\log N)$.
- Use a Web Worker to handle computation and avoid blocking the main thread; pass doodling coordinates incrementally.
- Set an iteration cap and residual threshold for conjugate gradient, trading a little accuracy for predictable response time.
- Cache intermediate results with an offscreen canvas, and only recompute the affected steps when switching modes.
7. Common Pitfalls and Engineering Advice
First, do not interpret “restorable” as “compressible.” Redundant representations are indeed fault-tolerant, but they cost more to store. Second, the relationship between doodling ratio and restoration quality is not linear; there is an obvious phase-transition point beyond which quality drops sharply. Third, the fragility of the phase spectrum shows that any representation relying on structural position needs extra position priors for protection. Fourth, if you want to deploy similar capabilities in production, you can use object storage to keep intermediate images, a message queue to smooth out compute-task peaks, a container platform to scale Worker compute horizontally, and logging and monitoring/alerting services to observe restoration time and failure rates.
8. Summary
The value of the transform-domain doodling experiment lies in using an interactive small tool to link linear algebra, Fourier analysis, and regularized solving into one complete chain. The four representations each have their own character: the inverse matrix depends on the condition number, the magnitude spectrum is the most fault-tolerant, the phase spectrum is the most fragile, and the row derivative needs boundary constraints. Understanding these differences helps you make more reasonable representation choices and robustness designs in real systems.
