JavaScript Image Frequency-Domain Painting and Restoration

    This article explores how to paint directly in different transform domains of an image and then restore it back to the spatial domain using JavaScript. It covers the 2D discrete Fourier transform and a practical FFT implementation, followed by five interactive modes: inverse-matrix, magnitude spectrum, phase spectrum, combined magnitude and phase, and row-derivative domain. For each mode, it explains what information the domain carries, provides runnable code, and describes the visual effect of masking specific regions. The article also summarizes key interaction and performance practices, such as offscreen mask drawing, power-of-two sizing, worker-thread computation, logarithmic spectrum normalization, and double-precision accuracy.

    1. Why Paint in a Transform Domain

    Painting directly in the spatial domain changes the pixels themselves. Transforming an image into another mathematical space first changes the way its structure is described. A set of revealing experiments starts from five representations of an image: the inverse matrix, the magnitude spectrum, the phase spectrum, magnitude and phase together, and the row derivative. Each representation is locally masked or painted over, then transformed back to the spatial domain to observe the restoration result. The value of these experiments is that they turn the abstract question of “what an image is made of” into a visual, interactive phenomenon.

    From an engineering perspective, a demo page like this usually has to solve three problems: whether the transform itself can run in real time in the browser, how complex arithmetic and normalization are handled, and how the interaction layer maps a mouse trajectory onto coordinates in the transform domain. The sections below focus on these three points.

    2. Mathematical Basis: The 2D Discrete Fourier Transform

    The 2D discrete Fourier transform (DFT) maps an (M\times N) image to a complex matrix of the same size:

    1. F(u,v) = Σ_x Σ_y f(x,y) · exp(-j2π(ux/M + vy/N))

    Here (F(u,v)) is complex and can be written as a magnitude and a phase:

    1. F(u,v) = A(u,v) · exp(jφ(u,v))
    2. A(u,v) = |F(u,v)| // magnitude spectrum
    3. φ(u,v) = angle(F(u,v)) // phase spectrum

    In practice, a naive DFT is almost never implemented directly because its complexity is (O(M^2N^2)). The frontend typically uses a separable 1D fast Fourier transform (FFT), transforming rows first and then columns, which reduces the complexity to (O(MN\log MN)). The sketch code is shown below:

    1. // In-place 1D FFT (Cooley-Tukey), length is a power of 2
    2. function fft1d(re, im) {
    3. const n = re.length;
    4. for (let i = 1, j = 0; i < n; i++) {
    5. let bit = n >> 1;
    6. for (; j & bit; bit >>= 1) j ^= bit;
    7. j ^= bit;
    8. if (i < j) {
    9. [re[i], re[j]] = [re[j], re[i]];
    10. [im[i], im[j]] = [im[j], im[i]];
    11. }
    12. }
    13. for (let len = 2; len <= n; len <<= 1) {
    14. const ang = -2 * Math.PI / len;
    15. const wr = Math.cos(ang), wi = Math.sin(ang);
    16. for (let i = 0; i < n; i += len) {
    17. let cr = 1, ci = 0;
    18. for (let k = 0; k < len / 2; k++) {
    19. const ur = re[i + k], ui = im[i + k];
    20. const vr = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci;
    21. const vi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr;
    22. re[i + k] = ur + vr; im[i + k] = ui + vi;
    23. re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;
    24. const ncr = cr * wr - ci * wi;
    25. ci = cr * wi + ci * wr; cr = ncr;
    26. }
    27. }
    28. }
    29. }
    30. // Row transform + column transform
    31. function fft2d(re, im, width, height) {
    32. const rowR = new Array(height), rowI = new Array(height);
    33. for (let y = 0; y < height; y++) {
    34. for (let x = 0; x < width; x++) { rowR[x] = re[y * width + x]; rowI[x] = im[y * width + x]; }
    35. fft1d(rowR, rowI);
    36. for (let x = 0; x < width; x++) { re[y * width + x] = rowR[x]; im[y * width + x] = rowI[x]; }
    37. }
    38. const colR = new Array(width), colI = new Array(width);
    39. for (let x = 0; x < width; x++) {
    40. for (let y = 0; y < height; y++) { colR[y] = re[y * width + x]; colI[y] = im[y * width + x]; }
    41. fft1d(colR, colI);
    42. for (let y = 0; y < height; y++) { re[y * width + x] = colR[y]; im[y * width + y * 0 + x] = colI[y]; }
    43. }
    44. }

    The inverse transform only needs the sign of the twiddle factor reversed and a final division by the total number of pixels. After applying a spectrum shift (fftshift), low frequencies land in the center, making it easy for users to paint over the middle directly.

    3. Mode 1: Inverse-Matrix Painting and Restoration

    The “inverse matrix” mode can be understood in two ways. One is to treat an image block as a matrix and invert it to observe numerical stability. The other, closer to the intent of the demo, is to perturb the transform matrix itself and then invert it to restore. In implementation, a 2D transform is applied to the image to obtain a complex matrix, the elements corresponding to the painted region are zeroed or noised, and then the inverse transform is executed. Because the Fourier matrix is unitary, its inverse equals its conjugate transpose, so the restoration path is naturally stable and no numerical explosion occurs after painting.

    1. // Inverse transform: conjugate + reverse FFT + normalization
    2. function ifft2d(re, im, width, height) {
    3. for (let i = 0; i < re.length; i++) im[i] = -im[i];
    4. fft2d(re, im, width, height);
    5. const scale = 1 / (width * height);
    6. for (let i = 0; i < re.length; i++) { re[i] *= scale; im[i] *= -scale; }
    7. }

    4. Mode 2: Magnitude Spectrum Painting

    The magnitude spectrum determines the strength of each spatial frequency component in the image. Painting over the center of the magnitude spectrum (low frequencies) degrades the image into a “contour ghost” with only edges and noise left; painting over the periphery (high frequencies) makes the image blurry and strips away detail. This directly demonstrates that the magnitude spectrum carries the image’s “energy distribution.”

    1. function paintMagnitude(re, im, mask, width, height) {
    2. for (let i = 0; i < re.length; i++) {
    3. if (!mask[i]) continue;
    4. const a = Math.hypot(re[i], im[i]);
    5. if (a < 1e-12) continue;
    6. // Attenuate magnitude to 10%, keep phase unchanged
    7. const k = 0.1;
    8. re[i] *= k; im[i] *= k;
    9. }
    10. }

    5. Mode 3: Phase Spectrum Painting

    The phase spectrum determines the alignment position of each frequency component in the spatial domain. The experiment reveals an interesting phenomenon: keeping only the phase while setting the magnitude to one still leaves the image outline recognizable, whereas keeping only the magnitude while zeroing the phase makes the original image almost unrecognizable. Phase is therefore the main carrier of “structural information.” When painting over a phase region, the magnitude should stay unchanged and only the angle should be modified:

    1. function paintPhase(re, im, mask) {
    2. for (let i = 0; i < re.length; i++) {
    3. if (!mask[i]) continue;
    4. const a = Math.hypot(re[i], im[i]);
    5. const p = Math.atan2(im[i], re[i]) + Math.PI / 4; // phase shift
    6. re[i] = a * Math.cos(p);
    7. im[i] = a * Math.sin(p);
    8. }
    9. }

    6. Mode 4: Painting Magnitude and Phase Together

    Perturbing both at once is the most destructive, and after restoration usually only noise remains. This mode works well as a control experiment, helping readers build the intuition that “magnitude governs energy and phase governs structure.” In implementation, simply chain the two functions above, taking care that they share the same mask.

    7. Mode 5: Row-Derivative Domain Painting

    The row derivative is the first-order difference along the horizontal direction, (d(x,y)=f(x,y)-f(x-1,y)), which highlights horizontal edges. Painting in the derivative domain and then integrating back produces horizontal smearing and breaks. The implementation first applies a forward difference, then performs cumulative summation to restore after painting:

    1. function rowDerivativeForward(src, width, height) {
    2. const out = new Float32Array(src.length);
    3. for (let y = 0; y < height; y++)
    4. for (let x = 0; x < width; x++)
    5. out[y * width + x] = x === 0 ? 0 : src[y * width + x] - src[y * width + x - 1];
    6. return out;
    7. }
    8. function rowDerivativeInverse(diff, width, height) {
    9. const out = new Float32Array(diff.length);
    10. for (let y = 0; y < height; y++) {
    11. let acc = 0;
    12. for (let x = 0; x < width; x++) { acc += diff[y * width + x]; out[y * width + x] = acc; }
    13. }
    14. return out;
    15. }

    8. Interaction and Performance Notes

    1. Mask drawing: Use an offscreen canvas to record the mouse trajectory and read the pixel alpha as the mask, avoiding frequent readbacks on the main thread.
    2. Size constraints: The FFT requires lengths that are powers of 2. It is recommended to fix the internal size at 256×256 or 512×512 and scale only for display.
    3. Asynchronous computation: Put the forward and inverse transforms in a worker thread to avoid a frozen interface. If batch tasks are hosted on a cloud function-compute or container platform, they should also be designed as stateless single requests.
    4. Normalization and visualization: The spectrum needs logarithmic compression log(1+A) before normalization; otherwise the dynamic range is too large and the display turns all black.
    5. Precision: Use double-precision floating-point arrays to store the real and imaginary parts, avoiding accumulated error across repeated transforms.

    9. Summary

    The five modes together show that an image’s representation in different transform domains carries different kinds of information: the magnitude spectrum corresponds to energy, the phase spectrum to structure, and the derivative domain to local variation. Turning these abstract conclusions into a frontend page that can be painted on and restored is a lightweight entry point for understanding signal processing and linear algebra. To host larger-scale or concurrent experiments, you can use object storage to keep source material, a message queue to schedule tasks, and monitoring and alerting services to observe elapsed time, which is a common combination in general cloud architectures.