Browser-Based Image Transforms and Frequency-Domain Doodle Reconstruction
This article presents a browser-only image processing workspace for interactively editing intermediate image representations and reconstructing images through inverse transforms. It covers inverse-matrix transformations, Fourier magnitude and phase editing, joint frequency-domain editing, horizontal derivatives, Canvas-based interaction, numerical normalization, boundary conditions, and performance optimization. The examples show how pixel data can be converted into floating-point arrays, modified with a brush, and passed through inverse operations to produce new images.
Browser-Based Image Transforms and Frequency-Domain Doodle Reconstruction
1. Project Overview
Image editing usually takes place in the pixel domain: users directly modify a pixel’s color, brightness, or transparency, and the program displays the result. In digital image processing, however, an image can also be represented in other spaces, including the frequency domain, gradient domain, and geometric transformation space. In these representations, structural information appears in different forms. Users can modify intermediate data with a brush and then apply an inverse transform to reconstruct a new image.
This article describes a browser-only interactive image processing page with five experimental modes:
- Doodling on an inverse transformation matrix and reconstructing the image;
- Doodling on the image magnitude spectrum and reconstructing the image;
- Doodling on the image phase spectrum and reconstructing the image;
- Editing the magnitude and phase spectra together;
- Editing horizontal image derivatives and reconstructing the image.
Here, “doodling” does not mean drawing directly on the final image. Instead, it modifies a local region of an intermediate image representation. After editing, the program sends the modified data through the corresponding inverse process to generate a reconstructed image.
2. Overall Processing Pipeline
A complete processing pipeline can be summarized as follows:
Load the image↓Normalize dimensions and color channels↓Convert to grayscale or floating-point matrices↓Apply a forward transform↓Visualize the transformed data↓Receive mouse or touch input↓Modify the intermediate data↓Apply the inverse transform↓Normalize and render the reconstructed image
Images in the browser are commonly loaded through a file input control. Canvas can then be used to access pixel data. Canvas returns a continuous one-dimensional array, where each pixel usually contains four components:
R, G, B, A
Fourier transforms, matrix operations, and derivative calculations are more convenient with two-dimensional floating-point arrays. The first step is therefore usually to convert the image into a grayscale matrix:
function rgbaToGray(imageData) {const { data, width, height } = imageData;const gray = new Float32Array(width * height);for (let i = 0, p = 0; i < gray.length; i++, p += 4) {const r = data[p];const g = data[p + 1];const b = data[p + 2];// Use a common perceptual luminance weightinggray[i] = 0.299 * r + 0.587 * g + 0.114 * b;}return gray;}
If color information must be preserved, each color channel can be processed independently. For spectrum visualization and algorithm validation, however, grayscale images are easier to inspect and require significantly less computation.
3. Inverse-Matrix Transformation Mode
Geometric transformations can be expressed as matrix operations. Two-dimensional coordinates are commonly represented with homogeneous coordinates:
[x'][y'][1 ] = M · [x][y][1]
A matrix can represent translation, scaling, rotation, shearing, and other operations. A rotation matrix, for example, is:
[ cosθ -sinθ 0 ][ sinθ cosθ 0 ][ 0 0 1 ]
In image processing, writing pixels directly from source coordinates into target coordinates can create holes. A more common approach is inverse sampling: iterate over every pixel in the target image, use the inverse transformation matrix to locate its position in the source image, and then obtain its color with nearest-neighbor or bilinear interpolation.
function transformPoint(inv, x, y) {const tx = inv[0] * x + inv[1] * y + inv[2];const ty = inv[3] * x + inv[4] * y + inv[5];const tw = inv[6] * x + inv[7] * y + inv[8];return {x: tx / tw,y: ty / tw};}
“Doodling on the inverse matrix” can be understood as interactively changing the inverse transformation or its derived parameters. For example, when the user drags the pointer across a preview area, the program can adjust the rotation angle, scale, or shear coefficient based on the drag direction and then perform inverse sampling again.
This mode is intuitive and useful for demonstrating geometric transformations. Its limitation is that it does not directly modify image content; it changes the mapping between pixel coordinates. Image boundaries, interpolation methods, and sampling precision all have a direct impact on the result.
4. Magnitude-Spectrum Editing and Reconstruction
4.1 Basic Fourier Representation
For a two-dimensional image (f(x,y)), the discrete Fourier transform can be written as:
F(u,v) = ΣΣ f(x,y) · e^(-j2π(ux/W + vy/H))
The result is a complex value:
F(u,v) = R(u,v) + jI(u,v)
A complex value can be represented by magnitude and phase:
Magnitude A(u,v) = sqrt(R² + I²)Phase P(u,v) = atan2(I, R)
Magnitude describes the strength of different spatial-frequency components, while phase determines how those components are arranged spatially.
When visualizing a spectrum, logarithmic compression is usually required. Otherwise, low-frequency areas become excessively bright and high-frequency details become almost invisible:
function spectrumValue(real, imag) {const magnitude = Math.hypot(real, imag);return Math.log1p(magnitude);}
For easier inspection, low-frequency components can be moved to the center of the image. This is commonly called spectrum centering. It is usually implemented by swapping the four quadrants:
function shiftQuadrants(data, width, height) {const result = new Float32Array(data.length);const halfW = Math.floor(width / 2);const halfH = Math.floor(height / 2);for (let y = 0; y < height; y++) {for (let x = 0; x < width; x++) {const nx = (x + halfW) % width;const ny = (y + halfH) % height;result[ny * width + nx] = data[y * width + x];}}return result;}
4.2 Editing the Magnitude Spectrum
Magnitude-spectrum editing changes only (A(u,v)), while keeping the phase unchanged. A brush can increase or decrease the magnitude in a selected region, or erase particular frequency components.
During reconstruction, the complex spectrum must be rebuilt:
R'(u,v) = A'(u,v) · cos(P(u,v))I'(u,v) = A'(u,v) · sin(P(u,v))
An inverse Fourier transform can then be applied to obtain the image.
Magnitude primarily affects texture, edge strength, and overall detail. Modifying the central low-frequency region usually changes global brightness, contours, and slowly varying areas. Editing the outer high-frequency region is more likely to affect fine lines, noise, and sharp edges.
5. Phase-Spectrum Editing and Reconstruction
The phase spectrum generally falls within the following range:
-π ≤ P(u,v) ≤ π
Phase is periodic, so it cannot be treated as an ordinary grayscale value. For example, values close to (-π) and values close to (π) may be mathematically close, but mapping them directly to grayscale can create a visible discontinuity.
For display, phase can be mapped to the range from zero to one:
function phaseToGray(phase) {return (phase + Math.PI) / (2 * Math.PI);}
When the user doodles on the phase image, the program can increase or decrease phase according to the brush direction:
phase[index] += delta;phase[index] = Math.atan2(Math.sin(phase[index]), Math.cos(phase[index]));
This normalization keeps the phase within ([-π, π]).
Phase is highly sensitive to image structure. Even when the magnitude spectrum remains unchanged, significant phase modifications can cause contour shifts, texture rearrangement, or the complete loss of the original shape. This experiment demonstrates that image information is not stored only in frequency strength; spatial structure and phase relationships are equally important.
6. Joint Magnitude and Phase Editing
The joint-editing mode stores two editable representations at the same time:
const frequency = {real: new Float32Array(size),imag: new Float32Array(size),amplitude: new Float32Array(size),phase: new Float32Array(size)};
When the magnitude is modified, the real and imaginary components must be rebuilt. The same synchronization is required when the phase changes:
function rebuildComplex(amplitude, phase, real, imag) {for (let i = 0; i < amplitude.length; i++) {real[i] = amplitude[i] * Math.cos(phase[i]);imag[i] = amplitude[i] * Math.sin(phase[i]);}}
Joint editing can produce more complex effects, but it also makes numerical instability more likely. For example, repeatedly increasing the magnitude may cause inverse-transform values to exceed the normal display range. Dynamic normalization or clipping is therefore required before rendering:
function normalizeImage(values) {let min = Infinity;let max = -Infinity;for (const value of values) {min = Math.min(min, value);max = Math.max(max, value);}const scale = max === min ? 1 : 255 / (max - min);return values.map(value => (value - min) * scale);}
Normalization is useful for displaying experimental results. However, if the goal is quantitative analysis, each result should not be stretched independently, because doing so removes comparability between experiments.
7. Horizontal Derivatives and Integral Reconstruction
The row-derivative mode does not depend on a two-dimensional frequency domain. Instead, it computes differences along the horizontal direction of each row:
D(x,y) = I(x+1,y) - I(x,y)
A simple implementation is:
function horizontalDerivative(gray, width, height) {const derivative = new Float32Array(gray.length);for (let y = 0; y < height; y++) {const offset = y * width;for (let x = 0; x < width - 1; x++) {derivative[offset + x] =gray[offset + x + 1] - gray[offset + x];}derivative[offset + width - 1] = 0;}return derivative;}
A derivative emphasizes horizontal edges. When the derivative image is edited, the program is modifying pixel changes rather than brightness values directly. Reconstruction is performed by cumulative integration along each row:
function integrateDerivative(derivative, width, height, startValue = 0) {const restored = new Float32Array(derivative.length);for (let y = 0; y < height; y++) {const offset = y * width;restored[offset] = startValue;for (let x = 1; x < width; x++) {restored[offset + x] =restored[offset + x - 1] + derivative[offset + x - 1];}}return restored;}
An important issue is that a derivative does not determine the absolute baseline of each row. Even if every difference is correct, a different starting brightness will make the reconstructed row globally brighter or darker. The initial value of each row must therefore be preserved, or an additional boundary constraint must be used.
Integration also accumulates error. Small amounts of noise in the derivative can become significant brightness drift after repeated accumulation. Practical ways to reduce this effect include:
- Smoothing the derivative data;
- Applying mean correction to each reconstructed row;
- Constraining integration with known boundary values;
- Solving for a more stable reconstruction with least-squares methods.
8. Canvas Interaction Design
An interactive workspace commonly uses several Canvas elements:
Original image CanvasTransformed image CanvasIntermediate representation CanvasReconstructed image Canvas
When the user draws on the intermediate representation Canvas, pointer coordinates must be mapped to data coordinates. If the Canvas is scaled with CSS, offsetX and offsetY cannot be used directly as array indices:
function getCanvasPosition(event, canvas) {const rect = canvas.getBoundingClientRect();return {x: (event.clientX - rect.left) * canvas.width / rect.width,y: (event.clientY - rect.top) * canvas.height / rect.height};}
A brush can use a circular neighborhood:
function paint(data, width, height, cx, cy, radius, callback) {const minX = Math.max(0, Math.floor(cx - radius));const maxX = Math.min(width - 1, Math.ceil(cx + radius));const minY = Math.max(0, Math.floor(cy - radius));const maxY = Math.min(height - 1, Math.ceil(cy + radius));for (let y = minY; y <= maxY; y++) {for (let x = minX; x <= maxX; x++) {const dx = x - cx;const dy = y - cy;if (dx * dx + dy * dy <= radius * radius) {const index = y * width + x;callback(data, index, x, y);}}}}
A complete inverse Fourier transform should not be executed for every pointer event during a drag. A better strategy is to set a pending-render flag and update once during the next animation frame:
let pending = false;function requestRender() {if (pending) return;pending = true;requestAnimationFrame(() => {pending = false;renderRestoredImage();});}
This prevents a high frequency of pointer events from making the page unresponsive.
9. Performance and Engineering Practices
A direct two-dimensional discrete Fourier transform has a high computational cost. As image dimensions increase, the browser’s main thread can easily become occupied by trigonometric functions and complex-number operations. The following practices are important in a production-oriented implementation.
1. Control the Processing Size
The source image can be resized to a dimension suitable for interaction, such as by limiting its maximum width and height. Interactive previews should prioritize responsiveness, while final export can use a higher resolution for recomputation.
2. Use Typed Arrays
Float32Array is more suitable than ordinary object arrays for storing pixels and spectrum data. It reduces memory usage and improves traversal efficiency.
3. Cache Unchanged Data
If the user changes only the phase, the original magnitude does not need to be recalculated. If only geometric parameters change, the spectrum does not need to be regenerated. Separating original data, current data, and display caches helps avoid unnecessary computation.
4. Separate Computation from Display
Canvas should be responsible for display, while arrays should be responsible for computation. Avoid reading Canvas pixels inside high-frequency loops, because this introduces additional data-copy overhead.
5. Use Background Computation
For large images or complex algorithms, Fourier transforms and inverse transforms can be moved to a background thread. The main thread can then focus on interaction and rendering. This keeps the interface responsive, but requires careful handling of data transfer and task cancellation.
10. Boundary Conditions and Common Problems
1. The Spectrum Is Too Bright or Completely Black
This is usually caused by a large dynamic range. Use logarithmic magnitude display and perform min–max normalization before rendering.
2. The Reconstructed Image Is Too Dark or Too Bright
The values produced by the inverse transform may not have been scaled correctly, or the DC component may have been modified. Check the normalization strategy and the handling of low-frequency regions.
3. The Phase Image Contains Obvious Discontinuities
Phase is periodic and cannot be processed with ordinary linear interpolation. Display logic must account for wrapping, and edited values should be normalized back into the valid interval.
4. The Derivative Reconstruction Drifts Across Rows
This is caused by integration error and uncertain starting values. Preserve boundary values or apply constraints during row reconstruction.
5. Black Borders Appear After Geometric Transformation
Some target coordinates may map outside the source image. Possible strategies include transparent fill, edge replication, constant fill, and mirrored fill.
11. Possible Extensions
After completing the basic version, the following capabilities can be added:
- Independent spectrum editing for color channels;
- Undo, redo, and historical snapshots;
- Adjustable brush strength, radius, and editing mode;
- Frequency coordinates, magnitude values, and phase values;
- Rectangular, circular, gradient, and other regional editing modes;
- Gaussian, low-pass, and high-pass filters;
- Export of intermediate data as structured files;
- Background-thread processing for large images;
- Error metrics such as mean squared error and peak signal-to-noise ratio;
- Side-by-side comparison of different transformation modes.
12. Conclusion
The core of this project is not simply building a conventional image doodling tool. It is building a complete workflow of image representation, interactive modification, inverse transformation, and reconstruction. Geometric transformations emphasize coordinate mapping. The magnitude spectrum represents the distribution of frequency energy. The phase spectrum reveals spatial structure. Joint editing demonstrates the coupling between the real and imaginary components of a complex spectrum. Horizontal derivatives show how local changes can be recombined through integration to form an image.
With Canvas, typed arrays, event handling, and numerical processing in the browser, it is possible to build an image-processing experiment platform without a complex deployment environment. The most important engineering concerns are data representation, numerical ranges, boundary conditions, spectrum visualization, and interaction performance. Once these components are separated properly, the same framework can be extended to support additional image transformations and inverse-reconstruction experiments.
