Image Frequency-Domain Doodling and Restoration in JavaScript

    This article explores five JavaScript techniques for applying controlled "doodles" to an image's intermediate representation and then restoring it back to the spatial domain. It covers the linear algebra behind reversible transforms, numerical stability concerns such as condition numbers, and practical browser-side implementation details. You will find working code for matrix inversion and 2D FFT, guidance on masking magnitude versus phase spectra, derivative-domain experiments, and engineering tips on memory layout, precision trade-offs, and common pitfalls.

    1. Background: Why Restoration After Doodling Matters

    A common and instructive problem in browser-based image processing is this: if you first transform an image into an intermediate representation (frequency domain, derivative domain, or inverse-matrix domain), manually erase part of the information there, and then transform it back to the spatial domain, what happens? Which regions lose information permanently, and which look almost unchanged to the human eye?

    The core value of these experiments is revealing how image information is distributed. They involve linear algebra, signal processing, and browser-side performance optimization, making them well suited as a front-end graphics exercise. This article uses a pure JavaScript implementation as the thread and walks through five technical routes.

    2. Mathematical Foundation: Linear Transforms and Invertibility

    Let an image be sampled as a matrix $A \in \mathbb{R}^{m \times n}$. Any linear transform can be written as $B = T(A)$. If $T$ is invertible, then $A = T^{-1}(B)$.

    • Invertible transforms: The image can be (approximately) restored after doodling; restoration quality depends on the proportion of total energy covered by the erased coefficients.
    • Non-invertible or ill-conditioned transforms: Tiny perturbations get amplified, so doodling causes severe distortion in the restored result.

    Numerical implementations must account for the condition number. For matrix inversion, the direct adjugate method accumulates error rapidly when $n$ is large; in practice you should use Gaussian elimination with pivoting or an orthogonal-decomposition approach. In JavaScript, use double-precision float arrays (Float64Array) to reduce error.

    1. // Example: Gauss-Jordan elimination with partial pivoting for inversion.
    2. // Input is a flattened n x n Float64Array.
    3. function invertMatrix(mat, n) {
    4. const a = new Float64Array(n * 2 * n);
    5. for (let i = 0; i < n; i++)
    6. for (let j = 0; j < n; j++) {
    7. a[i * 2 * n + j] = mat[i * n + j];
    8. a[i * 2 * n + n + j] = i === j ? 1 : 0;
    9. }
    10. for (let col = 0; col < n; col++) {
    11. let piv = col;
    12. for (let r = col + 1; r < n; r++)
    13. if (Math.abs(a[r * 2 * n + col]) > Math.abs(a[piv * 2 * n + col])) piv = r;
    14. if (Math.abs(a[piv * 2 * n + col]) < 1e-12) throw new Error('Singular matrix');
    15. [a.slice(col * 2 * n, col * 2 * n + 2 * n), a.slice(piv * 2 * n, piv * 2 * n + 2 * n)]
    16. .forEach((row, k) => a.set(row, (k === 0 ? piv : col) * 2 * n));
    17. const d = a[col * 2 * n + col];
    18. for (let j = 0; j < 2 * n; j++) a[col * 2 * n + j] /= d;
    19. for (let r = 0; r < n; r++) if (r !== col) {
    20. const f = a[r * 2 * n + col];
    21. for (let j = 0; j < 2 * n; j++) a[r * 2 * n + j] -= f * a[col * 2 * n + j];
    22. }
    23. }
    24. const out = new Float64Array(n * n);
    25. for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) out[i * n + j] = a[i * 2 * n + n + j];
    26. return out;
    27. }

    3. Route One: Doodling and Restoration in the Inverse-Matrix Domain

    The idea is to choose an invertible linear operator that matches the image dimensions (for example, a discrete-cosine-type transform matrix or a simple invertible convolution-kernel matrix), compute $A^{-1}$ or $T^{-1}(A)$, apply doodles to the transform coefficients, and then restore by left- or right-multiplication.

    Engineering notes:

    1. Process in blocks. Inverting the whole image costs $O(N^3)$, so use $8\times8$ or $16\times16$ blocks.
    2. Choose doodle locations carefully. Erasing high-frequency block coefficients introduces blocky artifacts; erasing low-frequency block coefficients causes an overall color shift.
    3. Evaluate restoration error. Use peak signal-to-noise ratio to measure restoration quality rather than subjective descriptions.

    4. Route Two: Magnitude-Spectrum Doodling and Restoration

    The 2D discrete Fourier transform gives $F(u,v)=|F|e^{j\phi}$. Keeping only the magnitude spectrum and zeroing the phase before the inverse transform yields a “textured” image; conversely, keeping only the phase still leaves the outline recognizable. This shows that structural information is mainly encoded in the phase.

    1. // Example: 2D FFT on a grayscale image (separable row/column 1D FFTs),
    2. // with support for magnitude-spectrum doodling.
    3. function fft2(re, im, width, height, inverse) {
    4. for (let y = 0; y < height; y++) fft1(re, im, y * width, 1, width, inverse);
    5. for (let x = 0; x < width; x++) fft1(re, im, x, width, height, inverse);
    6. }
    7. function fft1(re, im, offset, stride, n, inverse) {
    8. for (let i = 1, j = 0; i < n; i++) {
    9. let bit = n >> 1;
    10. for (; j & bit; bit >>= 1) j ^= bit;
    11. j ^= bit;
    12. if (i < j) {
    13. const a = offset + i * stride, b = offset + j * stride;
    14. [re[a], re[b]] = [re[b], re[a]];
    15. [im[a], im[b]] = [im[b], im[a]];
    16. }
    17. }
    18. for (let len = 2; len <= n; len <<= 1) {
    19. const ang = (inverse ? 2 : -2) * Math.PI / len;
    20. const wr = Math.cos(ang), wi = Math.sin(ang);
    21. for (let i = 0; i < n; i += len) {
    22. let cr = 1, ci = 0;
    23. for (let k = 0; k < len / 2; k++) {
    24. const p = offset + (i + k) * stride, q = offset + (i + k + len / 2) * stride;
    25. const tr = re[q] * cr - im[q] * ci, ti = re[q] * ci + im[q] * cr;
    26. re[q] = re[p] - tr; im[q] = im[p] - ti;
    27. re[p] += tr; im[p] += ti;
    28. const nr = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = nr;
    29. }
    30. }
    31. }
    32. if (inverse) for (let i = 0; i < n; i++) { re[offset + i * stride] /= n; im[offset + i * stride] /= n; }
    33. }

    Suggested masking strategy: use the spectrum center as the circle’s center and apply ring-shaped or fan-shaped occlusion to observe low-pass and band-stop effects separately. After erasing the magnitude spectrum and restoring, the image keeps its outline but loses tonal gradation.

    5. Route Three: Phase-Spectrum Doodling and Restoration

    The phase spectrum determines edges and positions. Randomizing the phase produces a noise-like image; locally erasing the phase causes geometric displacement and “tearing” in the corresponding spatial region. Implementation only requires modifying Math.atan2(im, re) before the inverse transform and then reconstructing the complex values.

    6. Route Four: Doodling Magnitude and Phase Simultaneously

    Attenuating both proportionally is equivalent to a multiplicative mask perturbation in the frequency domain. For experiment design, run a parameter sweep: vary the magnitude retention ratio $\alpha$ and the phase retention ratio $\beta$ from 0 to 1, and output a quality heat map that intuitively shows the differing contributions of the two types of information to recognizability.

    7. Route Five: Doodling and Restoration in the Row-Derivative Domain

    Apply a first-order difference to each row, $d(y,x)=I(y,x)-I(y,x-1)$, apply doodles in the derivative domain, and then accumulate to restore. Row derivatives are sensitive to abrupt changes along the horizontal direction, so doodling causes horizontal smearing; because differencing is a cumulative process, error is integrated and amplified along the row, so you need to introduce first-pixel anchoring and numerical clamping.

    8. Browser-Side Engineering Recommendations

    1. Rendering and data exchange: Use the canvas API to obtain ImageData, complete intermediate results in an offscreen canvas to avoid blocking the main thread, and move to a worker thread when the data volume is large.
    2. Memory layout: Prefer typed arrays and flat indexing to reduce object allocation; avoid per-pixel function calls and inline loops instead.
    3. Interaction design: Use sliders to control doodle radius and intensity with live preview; provide a dual view with “reset/compare”.
    4. Precision and performance trade-offs: Float32Array is sufficient for FFT; always use Float64Array for matrix inversion.
    5. Visualization aids: Spectrum plots need log compression and spectrum shifting (fftshift) before display.

    9. Common Pitfalls

    • Forgetting to divide by the length, causing brightness drift in the inverse transform;
    • Failing to apply center shifting to the spectrum, leading to misjudging the low-frequency location;
    • No overlap at block boundaries, producing seams;
    • Failing to clamp the numerical range after doodling, causing overflow when writing to the canvas.

    10. Summary

    Together, the five routes show that an invertible image transform redistributes information across different coefficient domains; doodling is essentially controllable information destruction, and restoration is information reconstruction under the inverse transform. Mastering the division of labor between magnitude and phase, numerical stability, and browser-side performance trade-offs lets you build an image-transform experiment platform in a pure front-end environment that is both intuitive and rigorous. If you need to support large-scale image experiments, you can combine object storage to save samples, a container platform to deploy compute services, and logging plus monitoring alerts to track task status, forming a complete engineering loop.