Frequency-Domain Doodle Restoration in JavaScript: A Browser-Based DFT Experiment

    This article describes a browser-only experiment that applies a two-dimensional discrete Fourier transform (DFT) to an image, lets users paint on the spectrum, and reconstructs the image with the inverse transform. It shows how the magnitude and phase spectra each affect image structure, and it covers the implementation details that matter: storing data in linear form, log scaling for display only, keeping brush edits conjugate-symmetric, and running the inverse transform in a Web Worker.

    1. Why Build This Experiment

    A classic exercise in image processing courses is to transform an image from the spatial domain to the frequency domain, edit it there, and transform it back to see what changed. The exercise shows directly what the magnitude spectrum and the phase spectrum each contribute in the Fourier transform.

    This article implements the experiment with plain front-end technologies: HTML, JavaScript, and Canvas. After a user uploads an image, the page computes a two-dimensional DFT in the browser, displays the spectrum, lets the user paint on it, and then applies the inverse transform to recover an image. A web page needs no installation and runs as soon as it is opened, which makes it suitable for classroom demonstrations.

    On privacy: images are processed only in the local browser through Canvas and are never sent to a server. If upload or save features are added later, the destination of the data will need to be explained separately.

    2. The 2D DFT and Spectrum Separation

    2.1 Forward and Inverse Transforms

    Let the image have width W and height H, and let the grayscale value of each pixel be f(x, y). The two-dimensional DFT is defined as:

    1. F(u, v) = Σx=0..W-1 Σy=0..H-1 f(x, y) · exp(-j·2π(ux/W + vy/H))

    The inverse transform changes the sign of the exponent to positive and multiplies by the normalization factor 1/(W·H):

    1. f(x, y) = (1/(W·H)) · Σu Σv F(u, v) · exp(+j·2π(ux/W + vy/H))

    Computing the definition directly has a complexity of O((W·H)²). For a 256×256 image, that is roughly 4.3 billion complex multiply-add operations, which makes the browser visibly slow. There are two common ways to speed this up. The first uses separability: compute a one-dimensional transform on each row, then on each column. This reduces the complexity to O(W·H·(W+H)). The second is the fast Fourier transform (FFT), which has a complexity of O(W·H·log(W·H)). For a teaching demo, limiting the image to 128 to 256 pixels makes the separable one-dimensional DFT fast enough.

    2.2 Magnitude and Phase Spectra

    Each complex value F(u, v) at a frequency point can be split into two parts:

    • Magnitude: A(u, v) = sqrt(Re² + Im²)
    • Phase: φ(u, v) = atan2(Im, Re)

    The two parts can be recombined into a complex value: Re = A·cos φ and Im = A·sin φ.

    The magnitude describes how much energy each frequency component carries. The phase describes how those components are arranged in space. Edges and outlines of an image are mainly preserved by the phase. To verify this, keep the phase of the original image, set every magnitude to 1, and apply the inverse transform. The outlines of the image remain clear. In the opposite test, keep the magnitude of the original image and randomize the phase. The image structure weakens noticeably and only a noise-like texture remains.

    Therefore, when only the magnitude spectrum is painted, the image structure stays relatively stable, and the main changes are contrast and texture strength. When only the phase spectrum is painted, the structure is more easily destroyed. This matches the conclusion that the phase mainly determines image structure.

    2.3 Why the Magnitude Spectrum Is Log-Scaled

    Low-frequency energy in the spectrum is much larger than high-frequency energy. If the linear magnitude is mapped directly to grayscale, the image is almost entirely black, with only the center point bright. For this reason, the display usually shows log(1 + A) multiplied by a scale factor, and shifts the low frequencies to the center of the image (fftshift).

    Two things need to be kept separate here. log(1 + A) is used only for display. Brush edits should modify the linear magnitude A. Do not feed the canvas gray values directly into the inverse transform as A’. Otherwise, the values used in the inverse transform would not match the brightness the user sees, and the log compression would distort the brush effect. The correct approach is to store a linear array internally and treat the canvas as a view of that array. The brush first converts display coordinates to frequency indices, then modifies the linear array, and finally re-renders the canvas.

    2.4 Meaning of the Row Derivative Transform

    The row derivative mode runs a one-dimensional DFT on each row and operates only on the horizontal frequency u. In the frequency domain, a horizontal derivative corresponds to multiplying by j·2π·k/W, where k is the signed horizontal frequency, ranging from -W/2 to W/2.

    Note that this multiplier is the exact derivative for a periodic signal. The spatial first-order difference x[n] - x[n-1] corresponds to the multiplier 1 - exp(-j·2πk/W). The two are close only at low frequencies and differ more at high frequencies. Readers who want to compare the results should understand this difference and should not treat the two operators as fully equivalent.

    3. Five Modes and Data Mapping

    In the implementation, use a mode enumeration to decide which array the brush writes to, then reuse the same inverse transform pipeline. The table below shows the mapping.

    Mode Name Data Written by the Brush Reconstruction Before Restoration
    1 Direct complex spectrum painting re, im None. Apply the inverse transform directly.
    2 Magnitude-only painting A Rebuild re and im from the modified A’ and the original phase.
    3 Phase-only painting φ Rebuild re and im from the original magnitude and the modified φ’.
    4 Magnitude and phase painting A and φ Rebuild re and im from A’ and φ’.
    5 Row derivative transform painting re and im after multiplication by the derivative multiplier None. The inverse transform produces the derivative image.

    The name of Mode 1 was originally “image inverse matrix,” which could be misleading. It is now uniformly called direct complex spectrum painting. Mode 1 modifies the complex values directly without splitting them into magnitude and phase, so an edit can change both the magnitude and the phase at once.

    The inverse transform in Mode 5 produces a derivative image, and its values can be negative. Before display, add an offset of 128 and clip the result to the range 0 to 255, so that a zero value maps to neutral gray.

    4. Implementation Notes

    4.1 Data Structures and Memory Estimates

    Use three canvases: one for the original image, one for the spectrum painting area, and one for the restored result. Store the core data in Float64Array arrays for re and im, and derive A and φ when needed. Each array element takes 8 bytes per pixel. If re, im, A, and φ are all stored, a 256×256 image uses about 2 MB. A 4096×4096 image uses about 512 MB, which will strain phones and ordinary laptops. For this reason, downsample the image to a suitable size before running the demo.

    4.2 Spectrum Display and Coordinate Mapping

    fftshift moves the zero frequency to the center of the display. A conversion function is needed between canvas display coordinates and frequency indices. The code below assumes that the width and height are even numbers.

    1. // Frequency index for display coordinates (du, dv). fftshift moves the zero frequency to the center.
    2. function displayToIndex(du, dv, W, H) {
    3. const u = (du + W / 2) % W;
    4. const v = (dv + H / 2) % H;
    5. return v * W + u;
    6. }
    7. // Conjugate-symmetric position (-u, -v) for frequency index i
    8. function mirrorIndex(i, W, H) {
    9. const u = i % W;
    10. const v = Math.floor(i / W);
    11. return ((H - v) % H) * W + ((W - u) % W);
    12. }
    13. // Render the linear magnitude as a grayscale image. Display uses log(1 + A), which affects only the canvas, not the data.
    14. function renderSpectrum(amp, ctx, W, H, scale) {
    15. const img = ctx.createImageData(W, H);
    16. for (let dv = 0; dv < H; dv++) {
    17. for (let du = 0; du < W; du++) {
    18. const src = displayToIndex(du, dv, W, H);
    19. const g = Math.min(255, Math.log(1 + amp[src]) * scale);
    20. const p = (dv * W + du) * 4;
    21. img.data[p] = img.data[p + 1] = img.data[p + 2] = g;
    22. img.data[p + 3] = 255;
    23. }
    24. }
    25. ctx.putImageData(img, 0, 0);
    26. }

    4.3 Brushes and Conjugate Symmetry

    The DFT of a real image satisfies conjugate symmetry: F(-u, -v) = conj(F(u, v)). This means the magnitude satisfies A(-u, -v) = A(u, v), and the phase satisfies φ(-u, -v) = -φ(u, v).

    If a brush modifies a frequency point without modifying its mirror point, the inverse transform will contain an imaginary residue. Discarding the imaginary part directly makes the restored result differ from what the user expects. For this reason, the magnitude brush should also write to the mirror point, and the phase brush should write the negated phase value to the mirror point.

    1. // Apply a circular brush with falloff to the linear magnitude array, and write to the mirror position at the same time
    2. function applyAmpBrush(amp, W, H, du, dv, radius, strength) {
    3. const r2 = radius * radius;
    4. for (let dy = -radius; dy <= radius; dy++) {
    5. for (let dx = -radius; dx <= radius; dx++) {
    6. if (dx * dx + dy * dy > r2) continue;
    7. const x = du + dx, y = dv + dy;
    8. if (x < 0 || x >= W || y < 0 || y >= H) continue;
    9. const i = displayToIndex(x, y, W, H);
    10. amp[i] *= (1 - strength);
    11. amp[mirrorIndex(i, W, H)] *= (1 - strength);
    12. }
    13. }
    14. }
    15. // Rebuild the complex spectrum from magnitude and phase
    16. function rebuildFromAmpPhase(amp, phase, re, im) {
    17. for (let i = 0; i < amp.length; i++) {
    18. re[i] = amp[i] * Math.cos(phase[i]);
    19. im[i] = amp[i] * Math.sin(phase[i]);
    20. }
    21. }

    The phase brush works the same way as the magnitude brush, except that the mirror position receives the negated phase value.

    4.4 Inverse Transform and Restoration

    The code below is a minimal separable implementation. It applies a one-dimensional inverse transform to each row, then to each column. The two normalization steps together divide by W·H. The function returns the real part of the complex result, because after painting, a result that should theoretically be real may contain small imaginary errors.

    1. // One-dimensional inverse DFT of length n. The result is divided by n.
    2. function idft1d(inR, inI, n, outR, outI) {
    3. for (let k = 0; k < n; k++) {
    4. let sr = 0, si = 0;
    5. for (let t = 0; t < n; t++) {
    6. const ang = 2 * Math.PI * k * t / n;
    7. const c = Math.cos(ang), s = Math.sin(ang);
    8. sr += inR[t] * c - inI[t] * s;
    9. si += inR[t] * s + inI[t] * c;
    10. }
    11. outR[k] = sr / n;
    12. outI[k] = si / n;
    13. }
    14. }
    15. // Two-dimensional inverse DFT: rows first, then columns. Returns the real part.
    16. function idft2(re, im, W, H) {
    17. const tR = new Float64Array(W * H), tI = new Float64Array(W * H);
    18. const rowR = new Float64Array(W), rowI = new Float64Array(W);
    19. const oR = new Float64Array(W), oI = new Float64Array(W);
    20. for (let v = 0; v < H; v++) {
    21. for (let u = 0; u < W; u++) {
    22. rowR[u] = re[v * W + u];
    23. rowI[u] = im[v * W + u];
    24. }
    25. idft1d(rowR, rowI, W, oR, oI);
    26. for (let u = 0; u < W; u++) {
    27. tR[v * W + u] = oR[u];
    28. tI[v * W + u] = oI[u];
    29. }
    30. }
    31. const colR = new Float64Array(H), colI = new Float64Array(H);
    32. const cR = new Float64Array(H), cI = new Float64Array(H);
    33. const outR = new Float64Array(W * H);
    34. for (let u = 0; u < W; u++) {
    35. for (let v = 0; v < H; v++) {
    36. colR[v] = tR[v * W + u];
    37. colI[v] = tI[v * W + u];
    38. }
    39. idft1d(colR, colI, H, cR, cI);
    40. for (let v = 0; v < H; v++) outR[v * W + u] = cR[v];
    41. }
    42. return outR;
    43. }
    44. // Convert the real part to 8-bit grayscale. Uint8ClampedArray clamps values to 0 to 255 and rounds them.
    45. function toGray(realOut) {
    46. return Uint8ClampedArray.from(realOut);
    47. }

    For restoration in row derivative mode, add an offset of 128 before calling toGray. The offset affects only the display and does not change the data itself.

    4.5 Performance and Interaction

    • Run the computation in a Web Worker. The inverse transform is computationally heavy, so it should run in a Worker, while the main thread handles rendering. Pass Float64Array data between the Worker and the main thread with postMessage. Using transferable objects is recommended to avoid copying.
    • Update only the spectrum while painting, and restore after the mouse is released. Running a full inverse transform on every pointermove is too expensive. A better approach is to update the linear arrays and redraw the spectrum canvas during painting. After the mouse is released, send the computation to the Worker to perform the restoration asynchronously.
    • Keep incremental redraws in sync with data updates. Redrawing only the rectangle affected by the brush reduces drawing cost, but this affects only the display. The brush must still update the corresponding spectrum arrays through the mask. Otherwise, the restored result will not reflect the user’s painting.
    • Use one mode enumeration for the whole pipeline. All five modes share the same brush, reconstruction, and inverse transform flow. They differ only in which array the brush writes to and whether reconstruction is needed before restoration.

    5. Frequently Asked Questions

    5.1 What is the difference between the magnitude spectrum and the phase spectrum?

    The magnitude spectrum records how strong each frequency component is. The phase spectrum records the relative positions of the components. The outlines and edges of a spatial image are mainly preserved by the phase. The overall brightness contrast and texture strength depend more on the magnitude.

    5.2 How is the inverse transform applied after painting in the frequency domain?

    First, organize the painted linear arrays into a complex spectrum. For magnitude or phase painting, rebuild re and im from A and φ before continuing. Next, apply the two-dimensional inverse DFT, divide by W·H, take the real part, and clip the result to 0 to 255. When painting, keep conjugate symmetry so that the imaginary part of the result stays close to zero.

    5.3 Why is the magnitude spectrum log-scaled?

    The dynamic range of the raw magnitude is very large, with low frequencies far above high frequencies. Taking the logarithm compresses this range, so the mid-frequency and high-frequency components become visible on screen. The logarithm is used only for display. Calculations still use the linear magnitude.

    6. Summary

    This experiment uses only front-end code to present the complete loop of moving from the spatial domain to the frequency domain, editing there, and restoring the image with the inverse transform. It shows how the magnitude and phase spectra divide their roles, and it practices common techniques such as Canvas pixel operations, complex arithmetic, and asynchronous computation with Web Workers.

    Readers can build on this experiment and extend it from here.