Image Transform-Domain Doodling and Restoration in JavaScript

    This article presents a unified JavaScript framework for five image transform-domain experiments: inverse-matrix transforms, magnitude-spectrum doodling, phase-spectrum doodling, combined magnitude-and-phase doodling, and row-derivative doodling. It explains the shared mathematical view behind these modes, provides a common forward/perturb/inverse pipeline with code samples, and covers the engineering practices needed to keep restoration numerically faithful, along with interaction and performance strategies for the browser.

    1. Problem Definition: Why “Transform, Doodle, Restore” Is Worth Doing

    The source material lays out a set of parallel experiment directions: image transformation based on an inverse matrix, doodling on the magnitude spectrum, doodling on the phase spectrum, doodling on magnitude and phase simultaneously, and doodling based on row derivatives. All of them converge on a single set of code for “five modes.” Together they describe one unified engineering paradigm: map an image from the spatial domain into some invertible representation domain, apply a controlled perturbation in that domain, then map it back to the spatial domain to observe the result.

    The value of this paradigm is not “making a mess of the image.” It is that an interactive interface turns abstract linear algebra and signal processing concepts into phenomena you can see and undo. For developers, it trains three things at once: the engineering of matrix operations, the numerical guarantees behind transform invertibility, and the layered design of browser-side interactive performance.

    It is worth stressing that all computation can run locally with no external service involved. That is a privacy advantage, but it also means every precision and performance problem falls on the implementer.

    2. Mathematical Groundwork: A Unified View of Three Representation Domains

    2.1 Inverse Matrix Transform: Put Invertibility First

    Let the image be flattened into a column vector x, and pick an invertible matrix A. The forward transform is y = A x and the inverse is x = A⁻¹ y. “Doodling in the transform domain” means adding a perturbation δ to y, giving y’ = y + δ, so that restoration yields x’ = A⁻¹ y’ = x + A⁻¹ δ.

    One easily overlooked conclusion follows: the shape of the perturbation in the spatial domain is determined entirely by A⁻¹. If A is orthogonal, then A⁻¹ = Aᵀ and the perturbation energy is preserved exactly. If A is close to singular, some directions of A⁻¹ are amplified enormously, and the doodle shows up as severe local artifacts. Engineering practice therefore requires two things. First, compute the inverse with column-pivoted Gaussian elimination or LU decomposition rather than plugging into a textbook formula. Second, stay alert to the condition number and, when necessary, regularize by using (AᵀA + λI)⁻¹Aᵀ instead of the bare inverse.

    2.2 Magnitude and Phase Spectra: Decomposing a 2D Orthogonal Transform

    Apply a separable orthogonal transform to the 2D image (a discrete cosine family transform or a fast Fourier family transform both work) to obtain a coefficient matrix F. The polar decomposition F = R ⊙ e^{jΦ} splits the coefficients into magnitude R and phase Φ. Practice has repeatedly confirmed the same thing: the human eye is far more sensitive to phase than to magnitude. Flatten the magnitude spectrum and keep only the phase, and contours remain recognizable; scramble the phase and keep the magnitude, and the image degrades into structureless texture.

    So “magnitude doodling” is suited to demonstrating changes in energy distribution, “phase doodling” is suited to demonstrating the destruction of structural information, and “doodling both at once” shows the composite effect of the two coupled together. These three make an excellent controlled experiment.

    2.3 Row Derivative: The Cheapest Difference Representation

    Take a first-order difference along the row direction, d[i][j] = x[i][j] − x[i][j−1]. Its inverse is simply prefix-sum accumulation. Both the forward and inverse passes are O(N) linear scans, making this the lowest-cost of the three representations and a good fit as a teaching entry point and a performance baseline.

    3. A Unified Implementation Skeleton for the Five Modes

    Abstract the five modes into the same set of operators and the code structure becomes clear immediately:

    1. // Unified operator interface: forward / perturb / inverse
    2. const modes = {
    3. inverseMatrix: { forward, perturb, inverse },
    4. magnitude: { forward, perturb, inverse },
    5. phase: { forward, perturb, inverse },
    6. both: { forward, perturb, inverse },
    7. rowDerivative: { forward, perturb, inverse }
    8. };
    9. function runPipeline(mode, pixels, w, h, strength) {
    10. const F = mode.forward(pixels, w, h); // spatial domain -> transform domain
    11. mode.perturb(F, strength); // doodle in the transform domain
    12. return mode.inverse(F, w, h); // transform domain -> spatial domain
    13. }

    The key to the inverse-matrix mode is matrix construction and inversion:

    1. function invertMatrix(M) {
    2. const n = M.length, A = M.map((r, i) => [...r, ...Array.from({length:n}, (_, j) => i === j ? 1 : 0)]);
    3. for (let c = 0; c < n; c++) {
    4. let p = c;
    5. for (let r = c + 1; r < n; r++) if (Math.abs(A[r][c]) > Math.abs(A[p][c])) p = r;
    6. [A[c], A[p]] = [A[p], A[c]];
    7. const d = A[c][c] || 1e-12;
    8. for (let k = 0; k < 2 * n; k++) A[c][k] /= d;
    9. for (let r = 0; r < n; r++) if (r !== c) {
    10. const f = A[r][c];
    11. for (let k = 0; k < 2 * n; k++) A[r][k] -= f * A[c][k];
    12. }
    13. }
    14. return A.map(r => r.slice(n));
    15. }

    The magnitude and phase modes share the same forward and inverse transforms and diverge only at the perturbation step:

    1. function toPolar(F) { /* return {R, Phi}, per-point hypot and atan2 */ }
    2. function fromPolar(R, Phi) { /* recombine per point with R*cos(Phi), R*sin(Phi) */ }
    3. function perturbMagnitude(F, s) { const {R, Phi} = toPolar(F); return fromPolar(R.map(v => v * (1 + s * noise())), Phi); }
    4. function perturbPhase(F, s) { const {R, Phi} = toPolar(F); return fromPolar(R, Phi.map(v => v + s * noise())); }

    The row-derivative mode is a minimal pair of scans in both directions:

    1. function rowForward(x, w, h) { const d = new Array(x.length).fill(0);
    2. for (let i = 0; i < h; i++) for (let j = 1; j < w; j++) d[i*w+j] = x[i*w+j] - x[i*w+j-1]; return d; }
    3. function rowInverse(d, w, h) { const x = new Array(d.length).fill(0);
    4. for (let i = 0; i < h; i++) { x[i*w] = 0; for (let j = 1; j < w; j++) x[i*w+j] = x[i*w+j-1] + d[i*w+j]; } return x; }

    4. Engineering Safeguards for Invertibility

    Invertible does not mean numerically equivalent. To make “restoration” actually look restored, four sources of error need handling:

    • Floating-point accumulation error: error grows linearly after repeated additions and subtractions, so apply a single clamp and rounding pass after the inverse transform to avoid color-level jumps caused by values like 0.9999 versus 1.0001.
    • Inconsistent boundary assumptions: if the row derivative defines the first-column difference as 0, the inverse must accumulate starting from 0; periodic and mirrored boundaries for transform-based methods must not be mixed.
    • Quantization loss: writing intermediate results into an 8-bit buffer and reading them back forces quantization, so keep intermediate state in floating point.
    • Perturbation strength semantics: normalize strength to [0,1], then map it internally to the appropriate magnitude for each mode, so the feel does not vary too much between modes.

    5. Layered Interaction and Performance

    For per-pixel work in the browser, the bottleneck is usually data movement rather than the algorithm. A three-layer strategy works: use plain arrays in the prototype stage for readability; use typed arrays and in-place operations in the interactive stage to reduce allocations; once the scale grows, hand the whole matrix to a parallel computation interface or a graphics buffer for batch processing, leaving the main thread to handle events and compositing only. The doodle brush should be throttled and recomputed incrementally, rerunning the pipeline only inside dirty rectangles instead of recomputing the full image on every mouse move.

    6. Parameters, Observability, and Common Pitfalls

    Make “mode, strength, brush radius, boundary strategy, whether to regularize” an explicit configuration object, and display the current configuration in the interface so experiments are reproducible. Common pitfalls include: directly inverting a near-singular matrix and triggering numerical explosion; a polar decomposition whose phase is meaningless near the origin yet still participates in doodling; the difference mode introducing a constant offset in the first column; and writing intermediate floating-point results into a low-precision buffer too early. Check these points one by one and the restoration quality of all five modes will stabilize noticeably.

    7. Extensions

    This skeleton can be extended further: generalize the 1D difference to a 2D gradient and study anisotropic doodling; replace the single transform with a multi-scale transform to observe robustness differences across frequency bands; and add quantitative metrics for each mode (such as mean squared error and structural similarity after restoration) to turn “looks right” into “measurable.” If you need to keep experiment samples, object storage in a general-purpose category can archive the inputs, parameters, and outputs for later review and teaching reuse.