Interactive Frequency-Domain Editing with Doodles: Understanding Image Transforms Through Experiments

    An in-browser JavaScript tool lets you paint directly on magnitude, phase, and other frequency-domain views, then observe the resulting changes in the spatial domain. This article explains the 2D FFT pipeline, implementation details, five editing modes, parameter tuning, validation methods, and common pitfalls. It is designed for learning and experimentation rather than general-purpose image restoration.

    Frequency-Domain Fundamentals: Why Paint in the Frequency Domain

    In the spatial domain, an image is represented as an arrangement of pixel intensities. After applying a two-dimensional discrete Fourier transform (2D DFT), the same image is represented by a matrix of complex coefficients. Each coefficient contains two components: magnitude and phase. Magnitude indicates the strength of a frequency component, while phase determines how those components align and combine in the spatial domain.

    By modifying frequency-domain coefficients and applying the inverse transform, you can observe the effect of changing specific frequency components. Reducing low-frequency magnitudes makes large-scale tones and broad structures less pronounced. Reducing high-frequency magnitudes softens edges and fine details.

    The system described here is implemented in JavaScript and runs entirely in the browser without a backend. Its purpose is to make transform concepts easier to understand through interaction. It is not a replacement for general-purpose image restoration, and the edited output is not guaranteed to be sharper or better than the original image.

    System Workflow and Shared Assumptions

    The system runs through six steps:

    1. Load a local image and draw it to a canvas.
    2. Extract the pixel data. Color images are converted to a luminance channel for frequency-domain editing. If color output is required, the same process is applied independently to the R, G, and B channels using one shared paint mask.
    3. Apply a two-dimensional transform to obtain a complex matrix.
    4. Let the user paint on the magnitude spectrum, phase spectrum, or another view to modify the corresponding coefficients.
    5. Apply the inverse transform, keep the real part, round the values, and clamp them to the range 0–255.
    6. Render the result. A copy of the original complex matrix is retained for one-click reset.

    The following assumptions must remain consistent across all modes. Otherwise, results from different modes cannot be compared reliably.

    • Dimensions: Pad the width and height to powers of two, such as 512×512. Crop the padded region after the inverse transform.
    • Magnitude display: Compute log(1 + |F|), then divide by the maximum value and map the result to 0–255. This keeps both low and high frequencies visible.
    • Centered spectrum: Shift the zero-frequency component to the center for display. Use the original indexing convention for calculations.
    • Phase range: Compute phase with atan2, producing values in [-π, π). Any modified phase outside this interval must be wrapped back into the range.
    • Brush strength: Let the strength s range from 0 to 1. Multiplying the magnitude by (1 - s) represents attenuation. Adding an offset to the phase represents phase perturbation.
    • Imaginary component: The spectrum of a real image has conjugate symmetry, so the inverse transform should theoretically have a zero imaginary part. In practice, only floating-point error remains. Modifying a single frequency bin breaks this symmetry, so the imaginary component is no longer zero. When the real part is taken, the corresponding modification in the imaginary component is discarded.

    Runtime Environment and Performance Methodology

    • Browsers: Chrome 90, Firefox 90, or Safari 15 and later. The implementation requires ES2020 syntax, Float64Array, and Canvas 2D.
    • Dependencies: No third-party libraries are required. The source can be placed in a single HTML file and opened directly.
    • Image size: Images should generally be no larger than 2048 pixels in either dimension. A 1024×1024 single-channel image requires two Float64Array buffers, or approximately 16 MB. Retaining a reset copy roughly doubles this memory requirement.
    • Performance methodology: Wrap the fft2d call with performance.now(), run one warm-up iteration, and use the median of 10 subsequent measurements. When reporting results, include the image dimensions, browser version, and device model.

    A Complete 2D FFT Implementation

    A two-dimensional DFT can be decomposed into two one-dimensional transforms: first apply a 1D FFT to every row, then apply a 1D FFT to every column. The fft1d function below uses an iterative radix-2 algorithm. fft2d follows an in-place convention: after the call, re and im contain the result.

    1. // Iterative radix-2 FFT, computed in place. The length must be a power of two.
    2. function fft1d(re, im, inverse = false) {
    3. const n = re.length;
    4. // Bit-reversal permutation
    5. for (let i = 1, j = 0; i < n; i++) {
    6. let bit = n >> 1;
    7. for (; j & bit; bit >>= 1) j ^= bit;
    8. j ^= bit;
    9. if (i < j) {
    10. [re[i], re[j]] = [re[j], re[i]];
    11. [im[i], im[j]] = [im[j], im[i]];
    12. }
    13. }
    14. // Butterfly operations
    15. for (let len = 2; len <= n; len <<= 1) {
    16. const half = len >> 1;
    17. const ang = (inverse ? 2 : -2) * Math.PI / len;
    18. for (let i = 0; i < n; i += len) {
    19. for (let k = 0; k < half; k++) {
    20. const wr = Math.cos(ang * k);
    21. const wi = Math.sin(ang * k);
    22. const a = i + k;
    23. const b = a + half;
    24. const tr = re[b] * wr - im[b] * wi;
    25. const ti = re[b] * wi + im[b] * wr;
    26. re[b] = re[a] - tr;
    27. im[b] = im[a] - ti;
    28. re[a] += tr;
    29. im[a] += ti;
    30. }
    31. }
    32. }
    33. }
    34. // re and im are row-major Float64Array buffers of length w * h.
    35. // The function operates in place. When inverse is true, the result is in
    36. // the spatial domain.
    37. function fft2d(re, im, w, h, inverse = false) {
    38. const rowRe = new Float64Array(w);
    39. const rowIm = new Float64Array(w);
    40. for (let y = 0; y < h; y++) {
    41. for (let x = 0; x < w; x++) {
    42. rowRe[x] = re[y * w + x];
    43. rowIm[x] = im[y * w + x];
    44. }
    45. fft1d(rowRe, rowIm, inverse);
    46. for (let x = 0; x < w; x++) {
    47. re[y * w + x] = rowRe[x];
    48. im[y * w + x] = rowIm[x];
    49. }
    50. }
    51. const colRe = new Float64Array(h);
    52. const colIm = new Float64Array(h);
    53. for (let x = 0; x < w; x++) {
    54. for (let y = 0; y < h; y++) {
    55. colRe[y] = re[y * w + x];
    56. colIm[y] = im[y * w + x];
    57. }
    58. fft1d(colRe, colIm, inverse);
    59. for (let y = 0; y < h; y++) {
    60. re[y * w + x] = colRe[y];
    61. im[y * w + x] = colIm[y];
    62. }
    63. }
    64. if (inverse) {
    65. const scale = 1 / (w * h);
    66. for (let i = 0; i < w * h; i++) {
    67. re[i] *= scale;
    68. im[i] *= scale;
    69. }
    70. }
    71. }

    The following example performs a round trip on a grayscale image and checks the numerical error. gray is a Uint8Array with N × N elements, which can be obtained from canvas pixel data.

    1. const N = 512;
    2. const re = new Float64Array(N * N);
    3. const im = new Float64Array(N * N);
    4. for (let i = 0; i < N * N; i++) re[i] = gray[i];
    5. const origRe = re.slice();
    6. fft2d(re, im, N, N);
    7. fft2d(re, im, N, N, true);
    8. let maxErr = 0;
    9. for (let i = 0; i < N * N; i++) {
    10. maxErr = Math.max(maxErr, Math.abs(re[i] - origRe[i]));
    11. }
    12. console.log("Maximum error:", maxErr); // Should be far below 1e-6

    If the inverse transform omits the 1 / (w × h) scaling factor, the result becomes N × N times brighter than the original. After clamping to 255, the image will be almost entirely white.

    Displaying the Magnitude Spectrum

    1. function magnitudeToImage(re, im, w, h) {
    2. const out = new Uint8ClampedArray(w * h);
    3. const mag = new Float64Array(w * h);
    4. let max = 0;
    5. for (let i = 0; i < w * h; i++) {
    6. mag[i] = Math.log(1 + Math.hypot(re[i], im[i]));
    7. if (mag[i] > max) max = mag[i];
    8. }
    9. for (let i = 0; i < w * h; i++) {
    10. out[i] = max > 0 ? (mag[i] / max) * 255 : 0;
    11. }
    12. return out;
    13. }

    Five Editing Modes

    All five modes use the same paint mask. Each mode determines which part of the complex coefficient is modified. The examples below operate on frequency-bin index i, where s is the brush strength.

    Magnitude Spectrum

    Magnitude mode changes only |F| while preserving the phase. The new magnitude is |F|(1 - s).

    1. function wrapPhase(p) {
    2. return p - 2 * Math.PI * Math.floor((p + Math.PI) / (2 * Math.PI));
    3. }
    4. // mode: 'amp' for magnitude, 'phase' for phase, or 'both' for both
    5. function editBin(re, im, i, s, mode, rng) {
    6. const a = Math.hypot(re[i], im[i]);
    7. let phi = Math.atan2(im[i], re[i]);
    8. let amp = a;
    9. if (mode === "amp" || mode === "both") {
    10. amp = a * (1 - s);
    11. }
    12. if (mode === "phase" || mode === "both") {
    13. phi = wrapPhase(phi + s * (rng() * 2 - 1) * Math.PI);
    14. }
    15. re[i] = amp * Math.cos(phi);
    16. im[i] = amp * Math.sin(phi);
    17. }

    rng should be a seedable pseudorandom function so that identical parameters produce reproducible results. If Math.random() is used directly, the output will differ between runs.

    Phase Spectrum

    Phase mode changes only the phase while preserving the magnitude. After adding the phase offset, the result must be wrapped back into [-π, π).

    Phase often has a greater influence on image structure than magnitude because it determines the spatial relationships among frequency components. Even a small phase perturbation can shift edges or reorganize textures.

    Combined Editing

    Combined mode changes both magnitude and phase. It corresponds to the 'both' branch in editBin. The effects are combined, creating more parameter combinations. It is most useful after comparing the two single-component modes.

    Inverse Filtering

    In this article, inverse mode means applying inverse filtering to the painted region. The painted region is treated as a known degradation function H, and the original spectrum is divided by that degradation. A regularization term eps is required to avoid division by values close to zero.

    1. // F' = F · conj(H) / (|H|² + eps)
    2. function inverseFilterBin(re, im, i, hRe, hIm, eps) {
    3. const den = hRe * hRe + hIm * hIm + eps;
    4. const nr = re[i] * hRe + im[i] * hIm;
    5. const ni = im[i] * hRe - re[i] * hIm;
    6. re[i] = nr / den;
    7. im[i] = ni / den;
    8. }

    Inverse filtering amplifies noise. When H approaches zero at certain frequencies, those components can be amplified significantly even with regularization. Speckles and ringing in the output usually originate from this behavior.

    Row Derivative

    The row-derivative mode multiplies each frequency bin by i·2πu/w, where u is the signed horizontal frequency. In the spatial domain, this corresponds to taking the horizontal derivative of each row. As a result, edges become more prominent and the brightness of flat regions is reduced.

    1. // Row derivative:
    2. // (re + i·im) · (i·k) = -k·im + i·k·re
    3. // k = 2πu / w
    4. function rowDerivative(re, im, w, x, y, s) {
    5. const i = y * w + x;
    6. const u = x < w / 2 ? x : x - w;
    7. const k = (2 * Math.PI * u) / w;
    8. const dr = -k * im[i];
    9. const di = k * re[i];
    10. re[i] = (1 - s) * re[i] + s * dr;
    11. im[i] = (1 - s) * im[i] + s * di;
    12. }

    If the two members of a conjugate pair are modified asymmetrically during painting, a residual imaginary component will remain. To preserve conjugate symmetry, apply the same modification to (u, v) and (-u, -v).

    Comparing the Five Modes

    Mode Modified component Observable effect Useful for Notes
    Magnitude Magnitude Attenuating low frequencies reduces broad tones; attenuating high frequencies softens details Understanding the relationship between frequency components and image detail Results are sensitive to the painted region
    Phase Phase Structural shifts and texture reorganization Understanding how phase carries spatial structure Large values of s can make the image difficult to recognize
    Combined Magnitude and phase Superimposes both effects Comparing the combined impact of the two modifications Many parameter combinations require careful recording
    Inverse filtering Division based on H Sharper edges, more noise, and ringing Understanding inverse filtering and its instability Too-small eps produces visible speckles
    Row derivative Multiplication by i·k for horizontal frequencies Vertical edges become more prominent and flat areas become darker Understanding the frequency-domain form of differentiation Conjugate symmetry must be preserved

    Parameter Tuning, Validation, and Mode Selection

    Suggested Parameters

    • Brush strength s: Start with 0.1–0.3 when exploring. Use 0.3–0.6 for a clearly visible change. Values above 0.8 nearly remove the painted components and are useful for observing extreme behavior.
    • Phase mode: Start with s ≤ 0.2. Phase perturbations are usually much more disruptive than magnitude attenuation.
    • Brush radius: Use 2–5 pixels in the frequency domain. A larger radius changes many frequency components at once, making the result harder to interpret.
    • Regularization eps: Start at 1e-3 times the maximum energy of H, then gradually increase it toward 1e-1 times that value. Larger eps reduces noise but makes the output closer to the original.

    Validation Procedure

    1. Round-trip test: With s = 0, the inverse-transform result should match the original image point by point, with a maximum error far below 1e-6.
    2. Imaginary-part check: Record the maximum absolute value of the imaginary part after the inverse transform. Before editing, it should be close to zero. If it grows significantly after editing, the paint operation has broken conjugate symmetry.
    3. Reproducibility test: Fix the random seed and paint mask, run the process twice, and compare the output hashes. The results should be identical.
    4. Reset test: After clicking reset, the output should match the original image point by point.
    5. Performance test: Measure fft2d according to the methodology described earlier and report the image size, browser, and device.

    Choosing a Mode

    • To understand the meaning of frequency components, start with magnitude mode.
    • To study the role of phase in image structure, use phase mode and keep s below 0.2.
    • To compare the combined effect of both types of modification, use combined mode and record the results from the individual modes separately.
    • To observe the instability of inverse filtering, use inverse mode and compare outputs produced with different eps values.
    • To study the frequency-domain interpretation of differentiation, use row-derivative mode and check for residual imaginary values.

    Common Mistakes

    • Forgetting to crop the padded region after zero-padding, which produces an incorrectly sized output.
    • Failing to wrap phase values after modification, which causes invalid phase discontinuities.
    • Omitting magnitude normalization when displaying the spectrum, resulting in an image that is entirely black or white.
    • Omitting the 1 / (w × h) scaling factor in the inverse transform, causing abnormal brightness.
    • Displaying the spectrum without centering it, leaving low-frequency components in the four corners and making them difficult to paint.

    Conclusion

    The main value of this tool is that it lets users directly modify frequency-domain coefficients and immediately observe the corresponding changes in the spatial domain. It demonstrates the separate roles of magnitude and phase while also exposing the instability of inverse filtering.

    The result depends on the source image and the selected parameters, so the tool cannot guarantee restoration quality. When choosing a mode, first identify the phenomenon you want to observe, then evaluate the output step by step using the suggested parameters and validation procedures.