Image Transform-Domain Doodling and Restoration in the Browser
This article presents a pure front-end experiment in which users load an image, choose a transform domain (inverse matrix, magnitude spectrum, phase spectrum, combined magnitude-phase, or row derivatives), paint over the transformed coefficients, and let the system reconstruct the image from the corrupted data. It explains the underlying math—linear transforms, masking, regularized least squares—along with a browser FFT pipeline, Gerchberg-Saxton style iterative recovery, interaction and state design, numerical stability pitfalls, and performance optimization techniques, showing how linear algebra, Fourier analysis, and web engineering connect into one runnable workflow.
Image Transform-Domain Doodling and Restoration in the Browser
In a web page, an image is usually just a pixel buffer inside a Canvas. But once you treat it as a matrix, many “damage and restore” experiments gain a clear mathematical formulation. This article discusses a pure front-end experiment page: the user loads an image, picks a transform domain, paints over the transformed result with a brush, and the system attempts to recover the image from the corrupted coefficients. The value is not in replicating any particular tool, but in connecting linear algebra, Fourier analysis, regularized reconstruction, and browser engineering into a single runnable pipeline.
1. From Pixel Matrices to Invertible Transforms
A grayscale image can be written as a matrix X ∈ R^(m×n); a color image is split into R, G, and B channels processed separately. If there exist a linear transform T and its inverse T⁻¹, then Y = T(X), and ideally X = T⁻¹(Y). “Doodle and restore” essentially means applying a mask M to Y to get Y’ = M ⊙ Y, then solving for the X̂ that best satisfies the constraints of the original image. Direct inversion is often ill-posed—especially when doodling removes large amounts of low-frequency or phase information, the least-squares solution explodes with noise. In engineering, the objective is therefore typically written as:
min_X ‖M ⊙ (T(X) − Y’)‖² + λ‖D X‖²
Here D can be a row difference, column difference, or Laplacian operator, and λ controls the smoothing strength. The first term enforces data consistency; the second suppresses high-frequency artifacts.
2. A Unified Abstraction for Five Experiment Modes
The original page mentions five modes: inverse matrix, magnitude spectrum, phase spectrum, magnitude and phase together, and row derivatives. Viewed uniformly, they differ only in “which transform domain, which information is missing, and which prior constraints apply.”
The inverse matrix mode is ideal for demonstrating the ill-conditioning of linear systems: construct an invertible but badly conditioned matrix A, compute y = Ax, let the user erase some components of y, and recover with conjugate gradient. In magnitude spectrum mode, phase is preserved while magnitude is painted over, and reconstructions usually retain recognizable contours. In phase spectrum mode, magnitude is preserved while phase is destroyed, and image structure collapses rapidly—evidence that phase is far more critical to edge localization. Simultaneous magnitude and phase damage is closest to real compression artifacts and requires alternating projections: enforcing known magnitudes in the frequency domain, and non-negativity, range clamping, and smoothness constraints in the spatial domain. The row derivative mode changes the observation to differences between adjacent rows; doodling is equivalent to losing vertical variation, and recovery must restore low-frequency means while constraining inter-row continuity.
3. The Fourier Pipeline in the Browser
Frequency-domain doodling commonly uses the 2D discrete Fourier transform. A front-end implementation does not need a full low-level library: start with a radix-2 1D FFT, then apply it to rows and columns separately:
function fft1d(re, im, invert){ /* bit-reversal + butterfly iterations; invert controls scaling */ }function fft2d(ch){ // transform rows first, then columns; output centered magnitude and phase}
Magnitude is A = sqrt(re² + im²) and phase is P = atan2(im, re). For display, apply log(1 + A) to the magnitude and normalize, otherwise the low-frequency bright spot will overwhelm the whole image. The doodle layer should be stored as a Float32Array mask with the same dimensions as the spectrum: 0 means deleted, 1 means kept, and intermediate values act as soft attenuation. During reconstruction, if only the magnitude was painted, you can inverse-transform using the original phase combined with the damaged magnitude. If phase is unknown, introduce Gerchberg-Saxton style iteration: clamp pixels to [0, 255] in the spatial domain, substitute known magnitudes in the frequency domain, repeat for several rounds, and average the results to reduce ringing.
4. Interaction and State Design
The page is best split into four layers: source canvas, transform-domain canvas, doodle mask layer, and result canvas. The state machine holds six core fields: mode, lambda, brushSize, mask, iterations, and channel. When switching modes, you must clear the mask and rebuild the transform cache, otherwise stale spectrum dimensions will contaminate new results. The brush on the frequency canvas does not directly change colors—it modifies the mask, which then triggers a “local reconstruction.” For smooth interaction, run only a preview inverse transform while dragging, and perform the high-quality iteration on mouse release.
5. Numerical Stability and Boundary Details
First, keep DFT scaling consistent: a common convention is no division by N in the forward transform and division by N in the inverse, or dividing both by sqrt(N)—but the pair must match. Second, a centered spectrum makes it convenient to paint low frequencies, but you must undo the shift before the inverse transform. Third, for color images, it is advisable to convert to a luminance channel for the demo and map back to the original colors, avoiding color shifts caused by inconsistent phases across the three channels. Fourth, painting over the DC component causes overall brightness drift; protect the DC term separately or apply histogram matching after reconstruction. Fifth, row-derivative observations lose the starting point of each row, so boundary conditions are needed—for example, anchoring the first column of pixels or constraining the global mean.
6. Performance Optimization
Pure JavaScript handling a 512×512 image is already near the limit of interactivity. You can use OffscreenCanvas and Workers to move FFT and iterative reconstruction off the main thread; read and write ImageData in one shot instead of per-pixel getImageData calls; apply incremental reconstruction to the mask so only the frequency blocks covered by the brush are updated; and for large images, tune parameters on a downsampled pyramid level before refining at full resolution. If more compute is needed, a common industry approach is to run batch reconstruction jobs on a container platform, store intermediate results in object storage, and log parameters and failure causes with a logging service—but the front-end demo page itself should remain self-contained.
7. Directions for Extension
Beyond the demo, this pipeline extends naturally to teaching and quality assessment: turn spectrum doodling into an assignment to observe why phase destruction is more devastating than magnitude destruction; display PSNR and SSIM reconstruction errors as live charts; replace the mask with random missing samples, stripe occlusion, or motion blur kernels to simulate degradation models; and swap the smoothness prior for anisotropic diffusion to reduce edge blurring. It is important to stress that all restoration is estimation—the larger the doodled area, the wider the solution space. A reliable system should show confidence levels or a residual heatmap, not just a single “looks clean” result image.
Conclusion
The key to this kind of web page is grounding the playful painting interaction in computable objects: the transform must be invertible or approximately invertible, the missing information must be explicitly modeled, the priors must be interpretable, and the interaction should be split into preview and high-quality computation tiers. With these principles in hand, you can reliably reproduce the damage-and-restore process in the transform domain—whether with vanilla scripts in the browser or migrated to cloud-based batch processing.
