Frequency-Domain Scribbling and Restoration: JavaScript Implementation Essentials

    This article covers five modes of editing images in transform domains and restoring them with JavaScript: DCT coefficients, magnitude spectrum, phase spectrum, combined magnitude and phase, and row derivatives. It explains the mathematical meaning of each mode, the conditions required by every inverse transform, common implementation pitfalls, and provides working code for FFT, fftshift, coordinate mapping, pixel normalization, and row-wise integration.

    Introduction

    This article is for front-end developers who want to do image processing with JavaScript. After reading, you will be able to distinguish the mathematical meaning of five transform-domain scribbling modes, understand the conditions each inverse transform must satisfy, and avoid several common implementation mistakes. The examples work on grayscale images whose side length is assumed to be a power of two, such as 256 or 512.

    Mode Transform Domain Scribble Target Key Inverse Step Main Effect Main Risk
    DCT coefficients Cosine transform Per-block coefficients Inverse DCT Texture changes within a block Blocking artifacts
    Magnitude spectrum Fourier frequency domain Magnitude Undo logarithm, IFFT Brightness and contrast Normalization affects the result
    Phase spectrum Fourier frequency domain Phase Combine with magnitude, IFFT Structural position shifts Phase wrapping
    Magnitude + phase Fourier frequency domain Both Combine, IFFT Both effects superimposed Pixel value overflow
    Row derivative Spatial gradient Horizontal difference Row-wise integration or Poisson solver Edge reconstruction Non-integrable gradient field

    1. Fundamentals

    Spatial domain vs. frequency domain. A grayscale image is an H×W matrix where each element is a pixel’s intensity. The 2D discrete Fourier transform (DFT) expresses it as a set of complex numbers F(u,v). The modulus |F| is the magnitude spectrum, and the argument is the phase spectrum. The DC component F(0,0) equals the sum of all pixels, so it determines the average brightness. The magnitude spectrum describes the strength of each frequency component, while the phase spectrum stores the positional relationships among the sinusoidal components.

    Derivatives and integration. The horizontal difference dx(i,j)=I(i,j+1)−I(i,j) captures how intensity changes along the horizontal direction. Vertical edges produce the strongest response in the horizontal derivative. Recovering an image from derivatives requires integration, and integration requires a starting value. Only when the derivative field is everywhere consistent (curl-free) does the integrated result exactly match the original image.

    2. Five Scribble-and-Restore Modes

    1. Scribbling on DCT Coefficients

    The DCT (discrete cosine transform) is orthogonal, so its inverse equals its transpose. A unique inverse exists for any data; matrix invertibility is not a concern.

    In practice, the image is split into 8×8 blocks and each block is transformed into 64 coefficients. The top-left corner holds low frequencies and the bottom-right holds high frequencies. Painting a block’s coefficients black is equivalent to zeroing the corresponding cosine components, so after the inverse transform that block’s texture is weakened. Because blocks are processed independently, visible square seams may appear at block boundaries—this is the blocking artifact.

    If you need global processing of the whole image, you can use SVD instead: A = UΣVᵀ. Modifying the singular values and reconstructing changes the image’s dominant structural components. Note that a matrix inverse exists only for full-rank square matrices. An image matrix is generally non-square, so it should not be described as “inverting the image matrix.”

    2. Scribbling on the Magnitude Spectrum

    Processing has three steps.

    First, run an FFT on the grayscale matrix, then apply fftshift to move the zero-frequency component to the center. Second, compute L = log(1 + |F|) for display. The raw magnitude spans several orders of magnitude and would display as nearly black. Third, the user scribbles on L. For example, drawing a black circle at the center reduces the low-frequency magnitudes near the center.

    Since L = log(1 + |F|), setting L to 0 corresponds exactly to |F| = 0, i.e., completely removing that frequency.

    Restoration reverses the steps. First undo the logarithm with |F| = expm1(L), combine with the original phase, apply ifftshift, run the IFFT, and finally take the real part of the result.

    Two conditions affect the outcome. The first is the DC component: zeroing F(0,0) sets the average brightness to zero. Display normalization then re-stretches the overall intensity, which looks like a contrast change rather than simple darkening. The second is pixel mapping: IFFT output may fall outside 0–255. Direct clipping produces a different result than linear min-max normalization. Fix one mapping method for experiments and document it.

    Scribbled magnitudes usually break conjugate symmetry, so the IFFT result carries an imaginary part. Taking only the real part discards some energy; this is an approximation, not an exact recovery.

    Under these conditions, removing central low frequencies weakens large smooth intensity transitions, while removing outer high frequencies softens edges.

    3. Scribbling on the Phase Spectrum

    Phase is obtained via atan2(Im F, Re F) and ranges over (−π, π]. Phase wrapping is a concern: −π and π represent the same direction. When smoothing or interpolating, differences must be computed on the circle; plain subtraction produces jumps.

    Three common ways to scribble on phase: zeroing, adding random values, and replacing a local region with phase from another location.

    Zeroing aligns all sinusoidal components, causing structure to cluster at certain positions. Randomization scrambles relative positions and the image tends toward noise. Random phase should follow a uniform distribution over (−π, π], e.g., (Math.random() * 2 - 1) * Math.PI; re-wrap values that fall outside the range.

    When magnitude is fixed and only phase changes, structural displacement and distortion are typically more pronounced than from magnitude-only edits, in common experiments on natural images. This conclusion depends on image content; run a controlled comparison on the same 512×512 grayscale image and record the differences for each operation.

    4. Scribbling on Magnitude and Phase Together

    Modify the magnitude array first, then the phase array, then combine and apply the IFFT. The two edits are independent; the final merged result does not depend on edit order—order only affects UI feedback.

    The superimposed effect is hard to judge by eye. Export three images separately: magnitude-only, phase-only, and both, and compare their difference images.

    5. Scribbling on Row Derivatives

    Compute the horizontal derivative of each row with forward differences, j from 0 to W−2. The user’s scribbles modify this derivative array.

    There are two restoration methods.

    The first is row-wise accumulation: column 0 of each row takes the original image value, and subsequent columns accumulate dx. It is simple, but errors accumulate along each row, rows do not constrain each other, and striping artifacts are common.

    The second is least squares: find an image I whose horizontal and vertical gradients best match the given gradient field. This is equivalent to solving the Poisson equation ∇²I = div G, which can be solved iteratively with Jacobi, Gauss-Seidel, or conjugate gradient methods, and requires boundary conditions such as Dirichlet boundaries (boundary pixels fixed to the original image values).

    When only horizontal derivatives are modified, the gradient field is generally non-integrable—no real image corresponds to it. The least-squares result is then only an approximate solution. The scribbled region shows intensity transitions, but the boundary with the surroundings may be discontinuous. With suitable boundary conditions, local edits can blend naturally—this is the basic idea behind Poisson blending.

    3. JavaScript Implementation Essentials

    1. Grayscale Conversion and Data Preparation

    1. const ctx = canvas.getContext('2d', { willReadFrequently: true });
    2. const imageData = ctx.getImageData(0, 0, W, H);
    3. const gray = new Float64Array(W * H);
    4. for (let i = 0; i < W * H; i++) {
    5. const p = i * 4;
    6. gray[i] = 0.299 * imageData.data[p] + 0.587 * imageData.data[p + 1] + 0.114 * imageData.data[p + 2];
    7. }

    W and H should be powers of two. Radix-2 FFT requires this; otherwise you need zero-padding or resampling. Zero-padding introduces artifacts at image edges, which should be documented.

    2. Choosing an FFT

    A pure-JavaScript 2D FFT has complexity O(N² log N). On a mid-range phone, 512×512 may take from a few hundred milliseconds to several seconds; measure on your target devices.

    You can use libraries such as fft.js from npm, applying a 1D FFT along rows and then columns to achieve a 2D transform. Lock the version in package.json and read its documentation on data layout. For real-time interaction, consider WebGL or WebGPU.

    This article assumes fft2D(gray, N) returns { re, im }, both row-major arrays of length N×N, without shifting.

    1. function toMagPhase(re, im) {
    2. const n = re.length;
    3. const mag = new Float64Array(n);
    4. const phase = new Float64Array(n);
    5. for (let i = 0; i < n; i++) {
    6. mag[i] = Math.hypot(re[i], im[i]);
    7. phase[i] = Math.atan2(im[i], re[i]);
    8. }
    9. return { mag, phase };
    10. }

    3. Shifting and Spectrum Display

    1. function fftshift(data, N) {
    2. const out = new Float64Array(N * N);
    3. const h = N / 2;
    4. for (let y = 0; y < N; y++) {
    5. for (let x = 0; x < N; x++) {
    6. out[((y + h) % N) * N + ((x + h) % N)] = data[y * N + x];
    7. }
    8. }
    9. return out;
    10. }

    For even side lengths, applying fftshift twice is the identity, so ifftshift is identical to fftshift.

    To prepare display data, compute the log magnitude first, then shift:

    1. const { mag, phase } = toMagPhase(re, im);
    2. const logMag = fftshift(mag.map((m) => Math.log1p(m)), N);
    3. const shiftedPhase = fftshift(phase, N);

    4. Coordinate Mapping

    The canvas CSS size may differ from the spectrum size N, so pointer positions must be converted to matrix indices. Using clientX is safer than offsetX, because the latter misbehaves when the event target is a child element.

    1. function pointerToIndex(e, canvas, N) {
    2. const rect = canvas.getBoundingClientRect();
    3. const x = Math.floor((e.clientX - rect.left) * N / rect.width);
    4. const y = Math.floor((e.clientY - rect.top) * N / rect.height);
    5. return {
    6. x: Math.min(N - 1, Math.max(0, x)),
    7. y: Math.min(N - 1, Math.max(0, y)),
    8. };
    9. }

    When scribbling, write values into the array within a circular region:

    1. function paintCircle(arr, N, cx, cy, radius, value) {
    2. const r2 = radius * radius;
    3. for (let dy = -radius; dy <= radius; dy++) {
    4. for (let dx = -radius; dx <= radius; dx++) {
    5. if (dx * dx + dy * dy > r2) continue;
    6. const x = cx + dx;
    7. const y = cy + dy;
    8. if (x < 0 || y < 0 || x >= N || y >= N) continue;
    9. arr[y * N + x] = value;
    10. }
    11. }
    12. }

    Note that arr holds log-domain values. To completely remove a frequency, write 0.

    5. Magnitude Restoration

    1. function restoreMagnitude(logMag, phase, N, ifft2D) {
    2. const n = N * N;
    3. const re = new Float64Array(n);
    4. const im = new Float64Array(n);
    5. for (let i = 0; i < n; i++) {
    6. const m = Math.expm1(logMag[i]);
    7. re[i] = m * Math.cos(phase[i]);
    8. im[i] = m * Math.sin(phase[i]);
    9. }
    10. // Undo the shift; for even side lengths ifftshift equals fftshift
    11. const out = ifft2D(fftshift(re, N), fftshift(im, N), N);
    12. return out.re; // Take only the real part; the imaginary part comes from the asymmetry introduced by scribbling
    13. }

    6. Pixel Mapping and Write-Back

    1. function toImageData(real, N) {
    2. let min = Infinity;
    3. let max = -Infinity;
    4. for (const v of real) {
    5. if (v < min) min = v;
    6. if (v > max) max = v;
    7. }
    8. const span = max - min || 1;
    9. const pixels = new Uint8ClampedArray(N * N * 4);
    10. for (let i = 0; i < N * N; i++) {
    11. const g = Math.round((real[i] - min) / span * 255);
    12. pixels[i * 4] = g;
    13. pixels[i * 4 + 1] = g;
    14. pixels[i * 4 + 2] = g;
    15. pixels[i * 4 + 3] = 255;
    16. }
    17. return new ImageData(pixels, N, N);
    18. }

    This uses linear normalization. Switching to direct clipping to 0–255 yields different brightness and contrast. Both approaches are valid, but stay consistent and state your choice in the UI.

    7. Integrating Row Derivatives

    1. function integrateRows(dx, firstCol, W, H) {
    2. // dx has length H*(W-1); firstCol holds each row's column-0 value
    3. const out = new Float64Array(W * H);
    4. for (let y = 0; y < H; y++) {
    5. out[y * W] = firstCol[y];
    6. for (let x = 0; x < W - 1; x++) {
    7. out[y * W + x + 1] = out[y * W + x] + dx[y * (W - 1) + x];
    8. }
    9. }
    10. return out;
    11. }

    This code only performs row-wise accumulation, and errors propagate along each row. For better results, use least squares or a Poisson solver instead.

    4. Performance and Compatibility Risks

    Memory usage grows quadratically with size. At 512×512, each Float64Array is about 2.1 MB. An implementation typically holds re, im, magnitude, phase, and shifted copies simultaneously, totaling roughly 20 MB. At 1024×1024, the same arrays total about 84 MB. Mobile browsers may slow down or crash as a result.

    For real-time interaction, consider first…