Image Transform, Doodle, and Restore: A Web Implementation
This article explains how to build a browser-based tool that transforms an image into a transform domain, lets users add doodle-style perturbations there, and then maps the result back to the spatial domain through an inverse transform. It covers the problem definition, four mathematical tools (2D DFT, magnitude and phase spectra, row derivatives, and inverse matrices), a pure front-end architecture, core JavaScript code for FFT and perturbation injection, implementation notes for five interactive modes, and practical guidance on performance, precision, and deployment. Readers will learn how a reversible linear transform turns abstract concepts such as invertibility, condition number, and integration constants into visible, interactive phenomena.
1. Problem Definition: What Is “Transform–Doodle–Restore”
“Transform, doodle, then restore” means you do not modify pixels directly. Instead, you first map the image into some transform domain (frequency domain, derivative domain, or a matrix-solving domain), artificially add perturbations there (the “doodle”), and then pull the result back to the spatial domain through an inverse transform. Because the transform is global, a local doodle produces global, controllable “afterimages” or structural changes in the spatial domain. This is exactly what makes it more interesting than directly smearing pixels, and better at revealing how image information is distributed.
The whole process can be abstracted into three steps:
- Forward transform:
F = T(I), mapping the spatial-domain imageIinto the transform domainF; - Domain perturbation:
F' = F + D, whereDis the perturbation generated by the user’s doodle; - Inverse transform:
I' = T⁻¹(F'), producing the restored (or “re-synthesized”) image.
The key prerequisite is that the transform is invertible or approximately invertible. As long as T is linear and invertible, the three-step composition forms a stable closed loop. If it is not invertible (for example, due to truncation or quantization), the restored result carries irreversible loss—which itself makes excellent teaching material.
2. Four Mathematical Tools
2.1 2D Discrete Fourier Transform
For an M×N image, the 2D DFT is defined as:
F(u,v) = Σ_x Σ_y I(x,y) · exp(-j2π(ux/M + vy/N))
In practice, no one computes the O(M²N²) double sum directly. Instead, separability is used: first run a 1D FFT along the rows, then a 1D FFT along the columns, reducing complexity to O(MN·log(MN)). The complex result is usually split into a magnitude spectrum |F| and a phase spectrum arg(F), which are handled separately.
2.2 Magnitude and Phase Spectra
The magnitude spectrum describes the strength of each frequency component and determines the image’s “energy distribution” and overall tonal range. The phase spectrum describes the relative position of each frequency component and determines the alignment of edges, textures, and structures. The classic result is that heavily perturbing the phase completely destroys recognizable structure, while perturbing only the magnitude mainly affects contrast and color tone. This contrast is precisely the teaching value of the five modes.
2.3 Row Derivative
The row derivative (a finite difference along the y direction) is a high-pass operator that highlights abrupt changes in the horizontal direction. Its inverse problem is an “integration plus boundary conditions” problem: given the derivative image, restoring the original requires determining the integration constant for each row, so uncertainty is inherent, and the doodle’s influence appears as a whole-row drift.
2.4 Inverse Matrix
Stack the image rows into a vector x, and write the linear transform as b = Ax. Given A and the observation b, solving for x means solving a linear system. When A is not invertible or there are fewer equations than unknowns, use the least-squares normal equations AᵀAx = Aᵀb to find an approximate solution. The doodle is equivalent to adding a perturbation to b, and the change in the solution is amplified or suppressed by the condition number of A.
3. Overall Architecture
A pure front-end single-page implementation is recommended, with no backend involved in the computation:
- View layer: two stacked canvases, the upper one showing the transform domain (spectrum/derivative image) and the lower one showing the spatial-domain result;
- Compute layer: a standalone numerical kernel module that exposes only the
forward/inverseinterfaces; - Scheduling layer: use a worker thread to handle the FFT and matrix solving, while the main thread only handles events and drawing to avoid UI stalls;
- State layer: store the original image, the current transform-domain data, and the doodle mask; when switching modes, only recompute the affected parts.
Use Float32Array to store real parts and Float64Array to store phase and accumulators, avoiding accumulated error over long iterations.
4. Core Code Skeleton
1D FFT (iterative, in-place):
function fft1(re, im, inverse) {const n = re.length;for (let i = 1, j = 0; i < n; i++) {let bit = n >> 1;for (; j & bit; bit >>= 1) j ^= bit;j ^= bit;if (i < j) {[re[i], re[j]] = [re[j], re[i]];[im[i], im[j]] = [im[j], im[i]];}}for (let len = 2; len <= n; len <<= 1) {const ang = (inverse ? 2 : -2) * Math.PI / len;const wr = Math.cos(ang), wi = Math.sin(ang);for (let i = 0; i < n; i += len) {let cr = 1, ci = 0;for (let k = 0; k < len / 2; k++) {const ur = re[i + k], ui = im[i + k];const vr = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci;const vi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr;re[i + k] = ur + vr; im[i + k] = ui + vi;re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;const ncr = cr * wr - ci * wi;ci = cr * wi + ci * wr; cr = ncr;}}}if (inverse) for (let i = 0; i < n; i++) { re[i] /= n; im[i] /= n; }}
2D transform and spectrum centering:
function fft2(re, im, w, h, inverse) {const rowR = new Float32Array(w), rowI = new Float32Array(w);for (let y = 0; y < h; y++) {rowR.set(re.subarray(y * w, y * w + w));rowI.set(im.subarray(y * w, y * w + w));fft1(rowR, rowI, inverse);re.set(rowR, y * w); im.set(rowI, y * w);}const colR = new Float32Array(h), colI = new Float32Array(h);for (let x = 0; x < w; x++) {for (let y = 0; y < h; y++) { colR[y] = re[y * w + x]; colI[y] = im[y * w + x]; }fft1(colR, colI, inverse);for (let y = 0; y < h; y++) { re[y * w + x] = colR[y]; im[y * w + x] = colI[y]; }}}
Doodle mask and perturbation injection (frequency domain as an example):
function splat(re, im, w, h, cx, cy, radius, gain) {for (let y = Math.max(0, cy - radius); y < Math.min(h, cy + radius); y++) {for (let x = Math.max(0, cx - radius); x < Math.min(w, cx + radius); x++) {const d = Math.hypot(x - cx, y - cy) / radius;if (d > 1) continue;const k = 1 + gain * (1 - d) * (1 - d); // smooth falloff to avoid hard-edge ringingconst i = y * w + x;re[i] *= k; im[i] *= k;}}}
5. Implementation Notes for the Five Modes
- Inverse matrix mode: build a sparse
A(such as a local difference operator), let the doodle modifyb, and use the conjugate gradient method to iteratively solve the least-squares problem; the more iterations, the more fully the doodle’s influence appears. - Magnitude-only doodle: scale only
|F|while keeping the phase unchanged; the result is a regional change in brightness and contrast, with structure largely preserved. - Phase-only doodle: rotate only
arg(F)while keeping the magnitude unchanged; the result is misaligned structure and broken edges, best demonstrating the dominant role of phase. - Simultaneous magnitude and phase doodle: combine the two with different gains to get a continuous transition between “recognizable” and “fully abstract,” suitable for slider interaction.
- Row-derivative doodle: after smearing on the derivative image, restore by row-wise cumulative summation; the doodle appears as a whole-row brightness drift, intuitively showing the uncertainty of the integration constant.
6. Performance and Precision
- Downscale the resolution to a 256 or 512 edge length for interactive preview, then recompute once at full resolution after the pointer is released;
- Put the FFT and iterative solving in a worker thread so the main thread keeps drawing at 60fps;
- Cache the forward-transform result, recompute only the affected frequency points when doodling, and trigger the inverse transform on demand;
- Store phase in
Float64Arrayso long iteration chains do not drift; - After restoration, apply a histogram stretch or slight clamping to suppress overflow that causes dead white/dead black.
7. Engineering and Deployment
Static assets can be hosted on object storage and accelerated with a content delivery network; compute-heavy versions can be containerized and deployed with stateless services for horizontal scaling; write doodle operations and timing metrics into a logging service, and combine them with monitoring alerts to locate slow requests. If you need to save users’ works, minimize data collection, clearly state the purpose, and provide one-click deletion.
8. Summary
The value of this approach lies not in the “doodle” itself, but in using an interactive closed loop to turn abstract concepts—linear transforms, invertibility, condition number, integration constants—into visible phenomena. Master these four things: the separable implementation of the 2D FFT, smooth mask injection, worker-thread scheduling, and least-squares solving, and you can extend any linear invertible transform into a new doodle mode.
