Browser-Based Image Frequency Editing and Reconstruction with JavaScript

    Learn how to build a browser-based workflow for painting on image amplitude and phase spectra, then reconstructing the result with an inverse FFT. This article covers grayscale conversion, zero-padding, 2D FFT implementation, spectrum visualization, Canvas editing, quantization limits, and reconstruction artifacts. It also explains the boundaries of matrix inversion and a separate spatial-domain row-difference mode.

    1. From Pixels to Frequencies

    A grayscale image can be represented as a two-dimensional matrix. The discrete Fourier transform (DFT) maps that matrix into the frequency domain, producing a complex value, F(u, v), at each frequency coordinate.

    The magnitude of each complex value forms the amplitude spectrum, which describes the strength of that frequency component. Its angle forms the phase spectrum, which describes the component’s spatial alignment.

    Phase carries structural information such as edges and contours, so changing phase often affects an image’s appearance more noticeably than changing amplitude. The exact effect depends on the image: both amplitude and phase contribute to reconstruction.

    For the workflow below, color images are first converted to grayscale using the common luminance formula:

    1. Y = 0.299R + 0.587G + 0.114B

    This conversion discards chromatic information. The reconstructed output is therefore grayscale, not a restoration of the original color image.

    2. Five Editing Modes and Their Limits

    Mode Preserved information Editing target Main limitation
    Matrix inversion None The matrix itself A non-square or singular matrix cannot be inverted
    Amplitude spectrum Original phase Amplitude spectrum Discarding the original phase can destroy recognizable structure
    Phase spectrum Original amplitude Phase spectrum Changes can substantially alter structure and brightness distribution
    Combined amplitude and phase editing None Two independent canvases The two sets of edits interact, making their effects difficult to separate
    Row differences First pixel of each row Difference image This is a spatial-domain method, not a frequency-domain method

    Matrix inversion

    Matrix inversion applies only to square, full-rank matrices. Images are usually rectangular, so this mode is best limited to educational demonstrations with small square matrices, such as 3 × 3 examples.

    For a non-square or singular matrix, a pseudoinverse or a regularized formulation can provide an approximate solution, but neither should be described as the matrix inverse.

    Amplitude-spectrum editing

    This mode preserves the original phase and changes only amplitude.

    If a preview instead replaces the original phase with a constant, the reconstructed image may lose recognizable structure and appear as scattered patterns or texture fragments.

    Phase-spectrum editing

    This mode preserves the original amplitude and changes only phase. Phase edits affect the spatial arrangement of image features and can change both contours and brightness distribution; preserving amplitude does not guarantee that the original contours remain intact.

    Combined editing

    Editing amplitude and phase together requires two independent canvases. After editing, the two arrays are combined to rebuild the complex spectrum.

    Row-difference editing

    This mode computes differences between neighboring pixels in each row. It does not use an FFT and does not require power-of-two image dimensions. Section 8 covers it separately.

    3. Grayscale Conversion and Zero-Padding

    First, read the pixels from Canvas and calculate a grayscale matrix.

    The following implementation ignores alpha. Transparent pixels therefore require separate handling if their hidden RGB values should not contribute to the result.

    1. function getGrayMatrix(imageData) {
    2. const { data, width, height } = imageData;
    3. const gray = new Float64Array(width * height);
    4. for (let i = 0; i < width * height; i++) {
    5. const p = i * 4;
    6. gray[i] = 0.299 * data[p] + 0.587 * data[p + 1] + 0.114 * data[p + 2];
    7. }
    8. return { gray, width, height };
    9. }
    10. function nextPow2(n) {
    11. let p = 1;
    12. while (p < n) p <<= 1;
    13. return p;
    14. }
    15. // Add zeros on the right and bottom to reach power-of-two dimensions.
    16. function padToPow2({ gray, width, height }) {
    17. const W = nextPow2(width);
    18. const H = nextPow2(height);
    19. const re = new Float64Array(W * H); // Initialized to zero.
    20. const im = new Float64Array(W * H);
    21. for (let y = 0; y < height; y++) {
    22. for (let x = 0; x < width; x++) {
    23. re[y * W + x] = gray[y * width + x];
    24. }
    25. }
    26. return { re, im, W, H };
    27. }

    Zero-padding can introduce abrupt transitions at image boundaries. These discontinuities spread energy into higher frequencies and can produce bright, cross-shaped lines in the spectrum—an example of spectral leakage.

    A Hann window can reduce leakage, but it also multiplies the image by the window function. Exact recovery would require dividing by that function, which is impossible at boundaries where it equals zero.

    This implementation does not apply a window and accepts the associated boundary artifacts. After the inverse transform, the result must be cropped to the original dimensions; otherwise, the padded area remains in the output.

    4. Implementing the 2D FFT

    A two-dimensional FFT can be computed by applying a one-dimensional FFT to every row, then to every column.

    The implementation below requires power-of-two lengths.

    1. function fft1d(re, im, invert) {
    2. const n = re.length;
    3. for (let i = 1, j = 0; i < n; i++) {
    4. let bit = n >> 1;
    5. for (; j & bit; bit >>= 1) j ^= bit;
    6. j ^= bit;
    7. if (i < j) {
    8. [re[i], re[j]] = [re[j], re[i]];
    9. [im[i], im[j]] = [im[j], im[i]];
    10. }
    11. }
    12. for (let len = 2; len <= n; len <<= 1) {
    13. const half = len >> 1;
    14. const ang = (invert ? 2 : -2) * Math.PI / len;
    15. for (let i = 0; i < n; i += len) {
    16. for (let k = 0; k < half; k++) {
    17. const wr = Math.cos(ang * k), wi = Math.sin(ang * k);
    18. const a = i + k, b = a + half;
    19. const xr = re[b] * wr - im[b] * wi;
    20. const xi = re[b] * wi + im[b] * wr;
    21. re[b] = re[a] - xr; im[b] = im[a] - xi;
    22. re[a] += xr; im[a] += xi;
    23. }
    24. }
    25. }
    26. }
    27. function fft2d(re, im, W, H, invert) {
    28. const rr = new Float64Array(W), ri = new Float64Array(W);
    29. for (let y = 0; y < H; y++) {
    30. const off = y * W;
    31. rr.set(re.subarray(off, off + W));
    32. ri.set(im.subarray(off, off + W));
    33. fft1d(rr, ri, invert);
    34. re.set(rr, off);
    35. im.set(ri, off);
    36. }
    37. const cr = new Float64Array(H), ci = new Float64Array(H);
    38. for (let x = 0; x < W; x++) {
    39. for (let y = 0; y < H; y++) {
    40. cr[y] = re[y * W + x];
    41. ci[y] = im[y * W + x];
    42. }
    43. fft1d(cr, ci, invert);
    44. for (let y = 0; y < H; y++) {
    45. re[y * W + x] = cr[y];
    46. im[y * W + x] = ci[y];
    47. }
    48. }
    49. }
    50. function forwardFFT(gray) {
    51. const spec = padToPow2(gray);
    52. fft2d(spec.re, spec.im, spec.W, spec.H, false);
    53. return spec;
    54. }

    The forward transform does not normalize its output. After the inverse transform, every value must be divided by W * H; otherwise, the reconstructed values will be too large by that factor.

    Repeated calls to Math.cos and Math.sin add computational overhead. For larger images, twiddle factors can be precomputed. That optimization is omitted here to keep the implementation compact.

    5. Mapping the Amplitude Spectrum to Grayscale

    Amplitude spectra have a large dynamic range. The DC component—displayed at the low-frequency center after shifting—can be several orders of magnitude stronger than other components.

    A linear display may therefore show little more than a bright central point. Logarithmic compression makes weaker components visible.

    Let the maximum amplitude be A_max, and define:

    1. S = ln(1 + A_max)

    The mappings between amplitude a and display intensity V are:

    • Display: V = 255 × ln(1 + a) / S, clamped to [0, 255]
    • Read back: a = exp(V / 255 × S) − 1

    For an all-black image, A_max is zero. Set S = 1 in that case to avoid division by zero.

    1. function splitAmpPhase(spec) {
    2. const n = spec.re.length;
    3. const amp = new Float64Array(n);
    4. const pha = new Float64Array(n);
    5. let maxA = 0;
    6. for (let i = 0; i < n; i++) {
    7. amp[i] = Math.hypot(spec.re[i], spec.im[i]);
    8. pha[i] = Math.atan2(spec.im[i], spec.re[i]);
    9. if (amp[i] > maxA) maxA = amp[i];
    10. }
    11. const logScale = maxA > 0 ? Math.log1p(maxA) : 1;
    12. return { amp, pha, logScale };
    13. }
    14. function ampToGray(a, logScale) {
    15. return Math.min(255, Math.round(255 * Math.log1p(a) / logScale));
    16. }
    17. function grayToAmp(v, logScale) {
    18. return Math.expm1(v / 255 * logScale);
    19. }
    20. // Map display coordinates to spectrum indices, equivalent to fftshift.
    21. // For even dimensions, this mapping is also its own inverse.
    22. function shiftIndex(x, y, W, H) {
    23. const sx = (x + (W >> 1)) % W;
    24. const sy = (y + (H >> 1)) % H;
    25. return sy * W + sx;
    26. }
    27. function renderAmp(amp, W, H, logScale) {
    28. const img = new ImageData(W, H);
    29. for (let y = 0; y < H; y++) {
    30. for (let x = 0; x < W; x++) {
    31. const v = ampToGray(amp[shiftIndex(x, y, W, H)], logScale);
    32. const p = (y * W + x) * 4;
    33. img.data[p] = img.data[p + 1] = img.data[p + 2] = v;
    34. img.data[p + 3] = 255;
    35. }
    36. }
    37. return img;
    38. }

    The 8-bit Canvas representation used here provides only 256 grayscale levels.

    For a maximum amplitude of one million, S is approximately 13.8. Each grayscale step corresponds to a relative change in 1 + a of approximately:

    1. exp(13.8 / 255) − 1 ≈ 5.6%

    By comparison, the linear mapping:

    1. V = 255 × a / A_max

    has an amplitude step size of:

    1. A_max / 255 ≈ 3,922

    Such a large step can erase weak frequency components entirely. Logarithmic mapping is therefore better suited to displaying these spectra.

    6. Mapping the Phase Spectrum to Grayscale

    Phase angles span approximately −π to π. Map them linearly to grayscale:

    • Display: V = round((φ + π) / (2π) × 255)
    • Read back: φ = V / 255 × 2π − π
    1. function phaseToGray(p) {
    2. return Math.min(255, Math.max(0, Math.round((p + Math.PI) / (2 * Math.PI) * 255)));
    3. }
    4. function grayToPhase(v) {
    5. return v / 255 * 2 * Math.PI - Math.PI;
    6. }

    Phase wraps around: black (0) and white (255) represent the equivalent angular endpoints −π and π. This can create an apparent seam in the displayed phase spectrum.

    A stroke crossing that seam may produce a numerical jump of about 2π. Reconstruction uses sine and cosine, so the wrap itself does not introduce an error. However, the visual discontinuity still matters when interpreting brush edits.

    7. Painting, Inverse Transformation, and Cropping

    Set the editing Canvas dimensions to W × H, then use CSS to scale its on-screen size as needed.

    Pointer coordinates must be converted from display coordinates to Canvas coordinates. Without this conversion, brush strokes will not align with the underlying pixels.

    1. function toCanvasPoint(canvas, e) {
    2. const r = canvas.getBoundingClientRect();
    3. return {
    4. x: (e.clientX - r.left) * (canvas.width / r.width),
    5. y: (e.clientY - r.top) * (canvas.height / r.height),
    6. };
    7. }
    8. // Read back edits. Replace only changed pixels and preserve the original
    9. // numerical values elsewhere to avoid unnecessary quantization error.
    10. function readBack(ctx, shown, base, W, H, toValue) {
    11. const data = ctx.getImageData(0, 0, W, H).data;
    12. const out = Float64Array.from(base);
    13. for (let y = 0; y < H; y++) {
    14. for (let x = 0; x < W; x++) {
    15. const p = (y * W + x) * 4;
    16. if (data[p] !== shown[p]) {
    17. out[shiftIndex(x, y, W, H)] = toValue(data[p]);
    18. }
    19. }
    20. }
    21. return out;
    22. }
    23. function ampPhaseToSpectrum(amp, pha, W, H) {
    24. const n = amp.length;
    25. const re = new Float64Array(n), im = new Float64Array(n);
    26. for (let i = 0; i < n; i++) {
    27. re[i] = amp[i] * Math.cos(pha[i]);
    28. im[i] = amp[i] * Math.sin(pha[i]);
    29. }
    30. return { re, im, W, H };
    31. }
    32. function inverseCrop(spec, origW, origH) {
    33. const { re, im, W, H } = spec;
    34. fft2d(re, im, W, H, true);
    35. const n = W * H;
    36. const out = new Uint8ClampedArray(origW * origH * 4);
    37. for (let y = 0; y < origH; y++) {
    38. for (let x = 0; x < origW; x++) {
    39. // Edits can break conjugate symmetry; discard the imaginary part.
    40. const v = re[y * W + x] / n;
    41. const p = (y * origW + x) * 4;
    42. out[p] = out[p + 1] = out[p + 2] = v;
    43. out[p + 3] = 255;
    44. }
    45. }
    46. return out;
    47. }

    The complete amplitude-editing workflow is:

    1. const gray = getGrayMatrix(imageData);
    2. const spec = forwardFFT(gray);
    3. const { amp, pha, logScale } = splitAmpPhase(spec);
    4. const img = renderAmp(amp, spec.W, spec.H, logScale);
    5. const shown = new Uint8ClampedArray(img.data);
    6. ctx.putImageData(img, 0, 0);
    7. // After the user paints on the spectrum:
    8. const newAmp = readBack(ctx, shown, amp, spec.W, spec.H, v => grayToAmp(v, logScale));
    9. const rebuilt = ampPhaseToSpectrum(newAmp, pha, spec.W, spec.H);
    10. const pixels = inverseCrop(rebuilt, gray.width, gray.height);
    11. outCtx.putImageData(new ImageData(pixels, gray.width, gray.height), 0, 0);

    For phase editing, display the phase spectrum using phaseToGray, retain a copy of its displayed pixel data, and read the edited phase values with:

    1. readBack(ctx, shown, pha, W, H, grayToPhase)

    Then combine the original amplitude with the edited phase rather than combining an edited amplitude with the original phase.

    For the unmodified spectrum of a real-valued image, the inverse transform’s imaginary component is theoretically zero, apart from numerical error. Painting can break the spectrum’s conjugate symmetry, producing a nonzero imaginary component.

    This implementation discards that component. Doing so is one source of information loss between the edited spectrum and the displayed image.

    8. Row-Difference Editing: A Spatial-Domain Mode

    Row-difference editing is not a frequency-domain operation. It calculates differences between adjacent pixels in each row while separately preserving the row’s first pixel.

    For each row:

    1. d[x] = g[x] − g[x − 1], for x ≥ 1

    The first value, g[0], is stored separately.

    1. function rowDiff({ gray, width, height }) {
    2. const diff = new Float64Array(width * height); // Column 0 is unused.
    3. const first = new Float64Array(height); // First pixel of each row.
    4. for (let y = 0; y < height; y++) {
    5. first[y] = gray[y * width];
    6. for (let x = 1; x < width; x++) {
    7. diff[y * width + x] = gray[y * width + x] - gray[y * width + x - 1];
    8. }
    9. }
    10. return { diff, first, width, height };
    11. }
    12. // Reconstruct each row using its first pixel and cumulative differences.
    13. function rowRebuild({ diff, first, width, height }) {
    14. const out = new Uint8ClampedArray(width * height);
    15. for (let y = 0; y < height; y++) {
    16. let acc = first[y];
    17. out[y * width] = acc;
    18. for (let x = 1; x < width; x++) {
    19. acc += diff[y * width + x];
    20. out[y * width + x] = acc;
    21. }
    22. }
    23. return out;
    24. }

    Differences range from −255 to 255. Use the following mappings for display and readback:

    1. Display: V = clamp(128 + d / 2)
    2. Read back: d = 2 × (V − 128)

    Here, clamp limits the displayed value to [0, 255].

    Encoding differences in 8-bit grayscale quantizes odd-valued differences. These small errors accumulate during reconstruction and can cause drift toward the end of a row.

    As with spectrum editing, replace only the differences corresponding to edited pixels. Preserve the original numerical values for unedited pixels to avoid introducing quantization error across the entire row.