Browser-Based Image Transformation, Doodle Editing, and Reversible Reconstruction

    This article presents a browser-side experimental workflow for image transformation, frequency-domain doodling, and reversible reconstruction. It covers homogeneous affine transforms and inverse matrices, 2D DFT magnitude and phase editing, horizontal derivative inspection, Canvas interaction, numerical stability, and performance considerations, with JavaScript examples. Readers learn how forward and inverse operations connect, how local edits in transform space propagate to the final image, and which practical issues affect reconstruction quality.

    Browser-Based Image Transformation, Doodle Editing, and Reversible Reconstruction

    1. Project Overview

    Image processing generally follows two approaches. One modifies pixel positions or pixel values directly, which is spatial-domain processing. The other first maps the image into a mathematical representation space, performs editing in the transform domain, and then applies an inverse transform to return to image space.

    This article designs a browser-side experimental page where users can perform the following operations:

    1. Apply geometric transformations to an image and restore it using an inverse matrix.
    2. Compute the 2D discrete Fourier transform, edit the magnitude spectrum, and reconstruct the image.
    3. Edit the phase spectrum and reconstruct the image.
    4. Edit both magnitude and phase spectra.
    5. Compute the horizontal derivative of the image and observe how derivative information affects reconstruction.
    6. Doodle on a visualization canvas and directly observe how local modifications propagate to the final image.

    The entire process does not rely on server-side computation. Image data can be read, transformed, drawn, and exported inside the browser. This approach is suitable both for learning image transformation principles and for prototyping front-end image-processing components.


    2. Overall Processing Flow

    A complete image transformation and reconstruction flow can be abstracted as follows:

    1. Read image
    2. ↓
    3. Normalize size and color channels
    4. ↓
    5. Build a floating-point pixel matrix
    6. ↓
    7. Apply forward transform
    8. ↓
    9. Visualize or doodle on the transform result
    10. ↓
    11. Apply inverse transform
    12. ↓
    13. Normalize and clamp pixel values
    14. ↓
    15. Draw to Canvas

    To avoid data distortion from repeated conversions, it is recommended to store images internally as floating-point arrays. A common pixel representation is:

    1. const image = {
    2. width: 0,
    3. height: 0,
    4. channels: 1,
    5. data: new Float32Array()
    6. };

    For grayscale processing, each element in data corresponds to one pixel. For color images, the red, green, and blue channels can be processed separately. To reduce complexity, the experimental page can first convert the input image to grayscale:

    1. function toGray(r, g, b) {
    2. return 0.299 * r + 0.587 * g + 0.114 * b;
    3. }

    This weighting better matches human perception of brightness across different colors and is preferable to a simple average.


    3. Geometric Transformation and Inverse-Matrix Reconstruction

    3.1 Homogeneous Coordinates

    Translation, rotation, scaling, and shearing in a 2D image can all be represented using 3×3 homogeneous matrices:

    1. | x' | | a c e | | x |
    2. | y' | = | b d f | | y |
    3. | 1 | | 0 0 1 | | 1 |

    Here:

    • a, b, c, and d handle rotation, scaling, and shearing;
    • e and f handle translation;
    • (x, y) is the original coordinate;
    • (x', y') is the transformed coordinate.

    For example, when rotating around the image center, you cannot simply rotate around the coordinate origin, or the image will visibly shift. The correct approach is to move the image center to the origin, apply the rotation, and then move it back:

    1. T(cx, cy) · R(θ) · T(-cx, -cy)

    The order of matrix multiplication is important. Matrices are not ordinary scalars, and changing the multiplication order usually produces different results.

    3.2 Role of the Inverse Matrix

    If the forward transformation matrix is:

    1. M = | a c e |
    2. | b d f |
    3. | 0 0 1 |

    then restoring the original image requires M⁻¹. For the upper-left 2D matrix:

    1. A = | a c |
    2. | b d |

    its determinant is:

    1. det = a * d - b * c

    When det is close to zero, the matrix is either non-invertible or numerically unstable. Therefore, the implementation should include a check:

    1. function invertAffine(m) {
    2. const det = m.a * m.d - m.b * m.c;
    3. if (Math.abs(det) < 1e-8) {
    4. throw new Error("The current transformation matrix cannot be inverted reliably");
    5. }
    6. return {
    7. a: m.d / det,
    8. b: -m.b / det,
    9. c: -m.c / det,
    10. d: m.a / det,
    11. e: (m.c * m.f - m.d * m.e) / det,
    12. f: (m.b * m.e - m.a * m.f) / det
    13. };
    14. }

    3.3 Inverse Sampling Is Better Than Forward Projection

    For geometric image transformations, inverse sampling is recommended.

    Forward projection maps source-image pixels to the target image, but it easily creates holes because some target pixels may have no source. Inverse sampling traverses every pixel in the target image, computes its position in the source image using the inverse matrix, and then applies interpolation.

    1. for (let y = 0; y < targetHeight; y++) {
    2. for (let x = 0; x < targetWidth; x++) {
    3. const sx = inv.a * x + inv.c * y + inv.e;
    4. const sy = inv.b * x + inv.d * y + inv.f;
    5. target[y * targetWidth + x] = bilinearSample(
    6. source,
    7. sx,
    8. sy
    9. );
    10. }
    11. }

    Bilinear interpolation is smoother than nearest-neighbor interpolation. Its basic steps are:

    1. Find the four integer pixels surrounding the target coordinate.
    2. Compute horizontal interpolation based on the fractional part.
    3. Perform vertical interpolation.
    4. Handle out-of-bounds coordinates using boundary clamping, zero padding, or mirroring.

    4. Fundamentals of the 2D Fourier Transform

    4.1 Complex Representation

    The output of the 2D discrete Fourier transform is not an ordinary real number but a complex number:

    1. F(u, v) = R(u, v) + iI(u, v)

    Here:

    • R is the real part;
    • I is the imaginary part;
    • i is the imaginary unit.

    A complex number can be converted to magnitude and phase:

    1. Magnitude: A = sqrt(R² + I²)
    2. Phase: P = atan2(I, R)

    Conversely, the real and imaginary parts can be recovered from magnitude and phase:

    1. R = A * cos(P)
    2. I = A * sin(P)

    Therefore, magnitude and phase together form the complete frequency-domain information. Modifying only one part will still change the final image.

    4.2 Direct Implementation of the 2D Transform

    For clarity, the 2D discrete Fourier transform can be implemented directly. For an image of size W × H:

    1. F(u,v) =
    2. ΣΣ f(x,y) · exp[-i2π(ux/W + vy/H)]

    In JavaScript, complex numbers can be stored as objects:

    1. function addComplex(a, b) {
    2. return {
    3. re: a.re + b.re,
    4. im: a.im + b.im
    5. };
    6. }
    7. function mulComplex(a, b) {
    8. return {
    9. re: a.re * b.re - a.im * b.im,
    10. im: a.re * b.im + a.im * b.re
    11. };
    12. }

    In practice, the exponential term can be split into cosine and sine:

    1. const angle = -2 * Math.PI *
    2. (u * x / width + v * y / height);
    3. const re = Math.cos(angle);
    4. const im = Math.sin(angle);

    The direct 2D transform has high time complexity and is suitable for small experimental images. For larger images, separable computation should be used: first apply a 1D transform to each row, then apply a 1D transform to each column. Implementing a fast Fourier transform can further reduce computation significantly.


    5. Magnitude-Spectrum Doodling and Reconstruction

    5.1 Meaning of the Magnitude Spectrum

    The magnitude spectrum describes the energy strength of different spatial frequencies in the image:

    • Low frequencies usually correspond to overall brightness, contours, and large-scale changes.
    • High frequencies usually correspond to edges, textures, and details.
    • After spectrum shifting, the central region usually represents low-frequency components.

    For easier observation, the magnitude spectrum is usually logarithmically compressed:

    1. function displayMagnitude(value) {
    2. return Math.log(1 + value);
    3. }

    If raw magnitude values are used directly, a few strong low-frequency components will occupy most of the display range, leaving other regions almost black.

    5.2 Doodle Editing

    When the user draws a line on the spectrum canvas, the corresponding frequency position can be found from the canvas coordinates, and the magnitude can be modified:

    1. function paintMagnitude(magnitude, index, radius, factor) {
    2. for (let y = -radius; y <= radius; y++) {
    3. for (let x = -radius; x <= radius; x++) {
    4. if (x * x + y * y > radius * radius) continue;
    5. const p = index + y * factor + x;
    6. if (p >= 0 && p < magnitude.length) {
    7. magnitude[p] *= 0.2;
    8. }
    9. }
    10. }
    11. }

    Addition, multiplication, or overwrite modes can also be used:

    • Multiply by a small coefficient: attenuate a frequency region.
    • Multiply by a large coefficient: amplify a frequency region.
    • Set directly to zero: remove certain frequencies.
    • Add a fixed value: emphasize specific frequencies.

    After modifying the magnitude, keep the original phase, reconstruct the complex spectrum, and apply the inverse transform.

    5.3 Typical Effects

    Attenuating high frequencies usually blurs the image. Amplifying high frequencies may strengthen both edges and noise. Removing frequencies in certain directions produces directional textures or stripes. This shows that frequency-domain doodling does not affect only one point on the canvas; it affects the overall structure in the image that has the corresponding frequency characteristics.


    6. Phase-Spectrum Doodling and Reconstruction

    Phase describes the spatial arrangement relationships among different frequency components. In many cases, phase has a very significant impact on image structure and contours.

    The phase range is usually:

    1. [-π, π]

    For display, it can be mapped to a grayscale range:

    1. const gray = (phase + Math.PI) / (2 * Math.PI) * 255;

    After the user modifies phase, the magnitude must remain unchanged:

    1. const re = magnitude[i] * Math.cos(phase[i]);
    2. const im = magnitude[i] * Math.sin(phase[i]);

    The effects of phase doodling are often harder to predict intuitively than those of magnitude doodling. Local phase changes may cause edge-position changes, structural misalignment, or texture rearrangement. The reason is that phase is not a simple “brightness strength”; it determines how multiple frequency components superimpose in space.

    To avoid excessively strong jumps during doodling, gradual modification can be used:

    1. phase[i] += delta * weight;

    Here, weight decays according to the distance between the mouse and the doodle center. This reduces abrupt artifacts.


    7. Editing Magnitude and Phase Together

    When editing magnitude and phase simultaneously, the page should store two separate data sets:

    1. const spectrum = {
    2. magnitude: new Float32Array(size),
    3. phase: new Float32Array(size)
    4. };

    The drawing sequence can be:

    1. Convert mouse events to spectrum coordinates.
    2. Calculate the influence range based on brush radius.
    3. Adjust magnitude.
    4. Adjust phase.
    5. Recombine the modified data into complex numbers.
    6. Apply the inverse transform.
    7. Display the result.

    For experimentation, independent controls are recommended:

    • Magnitude modification strength;
    • Phase modification strength;
    • Brush radius;
    • Modification mode;
    • Whether to modify symmetrically;
    • Whether to reconstruct in real time.

    Spectrum Conjugate Symmetry

    For real-valued images, the Fourier spectrum satisfies conjugate symmetry:

    1. F(-u, -v) = conjugate(F(u, v))

    If only one position in the spectrum is modified without modifying the corresponding symmetric position, the inverse transform may produce a noticeable imaginary part. In the final display, usually only the real part is used, but this introduces error.

    A more rigorous approach is to update symmetric positions together:

    1. function symmetricIndex(x, y, width, height) {
    2. const sx = (width - x) % width;
    3. const sy = (height - y) % height;
    4. return sy * width + sx;
    5. }

    The center point and points lying on symmetry axes need special handling to avoid duplicate modifications.


    8. Image Horizontal Derivative and Edge Information

    The horizontal derivative describes how the image changes along the horizontal direction. The simplest discrete form is the forward difference:

    1. D(x,y) = I(x+1,y) - I(x,y)

    A central difference can also be used:

    1. D(x,y) = [I(x+1,y) - I(x-1,y)] / 2

    A JavaScript implementation is:

    1. function horizontalDerivative(src, width, height) {
    2. const dst = new Float32Array(src.length);
    3. for (let y = 0; y < height; y++) {
    4. for (let x = 1; x < width - 1; x++) {
    5. const left = src[y * width + x - 1];
    6. const right = src[y * width + x + 1];
    7. dst[y * width + x] = (right - left) * 0.5;
    8. }
    9. }
    10. return dst;
    11. }

    A derivative image usually contains positive and negative values and cannot be mapped directly to ordinary grayscale display. The following approach can be used:

    1. const value = Math.abs(derivative[i]);
    2. const display = Math.min(255, value * scale);

    The derivative highlights edges but also amplifies noise. Therefore, in practice, light smoothing is often applied before differentiation, or the gain is reduced during display.

    From the frequency-domain perspective, spatial differentiation corresponds to multiplication in the frequency domain:

    1. ∂f/∂x ↔ i2πu · F(u,v)

    This explains why high-frequency components are amplified, which is exactly why derivative images tend to emphasize edges and noise.


    9. Canvas Interaction Design

    The page can provide at least four types of canvases:

    1. Original image canvas;
    2. Transform result canvas;
    3. Doodle editing canvas;
    4. Reconstruction result canvas.

    Mouse coordinates must be converted from page coordinates to canvas coordinates:

    1. function getCanvasPoint(canvas, event) {
    2. const rect = canvas.getBoundingClientRect();
    3. return {
    4. x: (event.clientX - rect.left) *
    5. canvas.width / rect.width,
    6. y: (event.clientY - rect.top) *
    7. canvas.height / rect.height
    8. };
    9. }

    If the canvas uses CSS scaling without proportional conversion, the doodle position will be misaligned with the mouse.

    It is recommended to manage interaction state centrally:

    1. const state = {
    2. drawing: false,
    3. mode: "magnitude",
    4. radius: 8,
    5. strength: 0.5,
    6. lastPoint: null
    7. };

    When the mouse moves, do not modify only a single pixel. Adjacent points should be interpolated; otherwise, fast mouse movement will produce broken lines. Line-segment sampling can be performed between the start and end points:

    1. function sampleLine(a, b, step = 1) {
    2. const distance = Math.hypot(b.x - a.x, b.y - a.y);
    3. const count = Math.max(1, Math.ceil(distance / step));
    4. const points = [];
    5. for (let i = 0; i <= count; i++) {
    6. const t = i / count;
    7. points.push({
    8. x: a.x + (b.x - a.x) * t,
    9. y: a.y + (b.y - a.y) * t
    10. });
    11. }
    12. return points;
    13. }

    10. Numerical Stability and Performance Optimization

    10.1 Pixel Value Clamping

    The result after the inverse transform may exceed [0, 255], so it must be clamped:

    1. function clampByte(value) {
    2. return Math.max(0, Math.min(255, Math.round(value)));
    3. }

    If values are converted directly to unsigned byte types, negative numbers and large numbers may undergo unexpected modulo behavior. Therefore, manual clamping should be performed first.

    10.2 Normalization

    Different transformation modes can produce very different output ranges. Normalization can use the minimum and maximum values:

    1. function normalize(data) {
    2. let min = Infinity;
    3. let max = -Infinity;
    4. for (const v of data) {
    5. min = Math.min(min, v);
    6. max = Math.max(max, v);
    7. }
    8. const scale = max === min ? 1 : 255 / (max - min);
    9. return data.map(v => (v - min) * scale);
    10. }

    However, for tasks that must preserve absolute brightness relationships, global normalization should not be blindly applied to every result; otherwise, different results cannot be compared fairly.

    10.3 Avoid Blocking the Page

    Computing large 2D transforms directly will block the interface. The following strategies can be used:

    • Reduce the experimental image size;
    • Split computation into multiple stages;
    • Use background worker threads;
    • Provide progress feedback to the user;
    • Run full reconstruction only after the user stops dragging;
    • Show a low-resolution preview while dragging.

    10.4 Cache Trigonometric Functions

    In the discrete Fourier transform, a large amount of time is spent on sine and cosine calculations. For fixed-size images, angle tables can be precomputed to reduce repeated computation. Separable transforms also reduce the number of repeated operations.


    A complete experimental page can consist of the following areas:

    1. Input area
    2. ├── Select image
    3. ├── Select processing mode
    4. └── Set image size
    5. Visualization area
    6. ├── Original image
    7. ├── Transform result
    8. ├── Doodle layer
    9. └── Reconstruction result
    10. Parameter area
    11. ├── Brush radius
    12. ├── Modification strength
    13. ├── Interpolation method
    14. └── Real-time update toggle
    15. Control area
    16. ├── Run transform
    17. ├── Undo
    18. ├── Reset
    19. └── Export result

    The undo feature can store a limited number of snapshots. For large arrays, frequent deep copying of all data is not recommended. Instead, record only the doodle operation regions or use a differential storage strategy.


    12. Common Issues and Troubleshooting

    Obvious Black Borders After Reconstruction

    This usually means that target coordinates after geometric transformation fall outside the source image. The boundary strategy should be defined explicitly, such as transparent fill, constant fill, edge replication, or mirrored fill.

    Spectrum Display Is Almost Entirely Black

    This may be caused by excessive dynamic range. Use logarithmic compression and shift the spectrum center so that the low-frequency concentration is located in the middle of the canvas.

    Result Is Severely Distorted After Phase Modification

    This is usually not a program error; phase has a strong impact on structure. Reduce the modification strength and use a smooth brush.

    Inverse Transform Produces Color Artifacts or Abnormal Values

    If the source image is grayscale data but multiple color channels are incorrectly reused during reconstruction, or if spectrum conjugate symmetry is ignored, abnormalities may appear. Check channel handling, complex reconstruction logic, and spectrum index mapping.

    Mouse Doodle Position Is Inaccurate

    Check whether the CSS size matches the internal pixel size of the Canvas, and use getBoundingClientRect() to perform proportional conversion.


    13. Conclusion

    The core of this experiment is not merely to build an image doodling page, but to establish a complete understanding of “reversible transformation”:

    • Geometric transformations are described by matrices, and reconstruction relies on inverse matrices.
    • The Fourier transform maps an image from the spatial domain to the frequency domain.
    • Magnitude represents frequency energy; modifying it affects details and textures.
    • Phase determines spatial arrangement and plays an important role in structure and edges.
    • Derivatives highlight change regions while also amplifying noise.
    • An inverse transform does not necessarily mean lossless information recovery; numerical errors, sampling errors, and manual doodling all affect the final result.
    • Browser-side visualization can turn abstract mathematical processes into intuitive interactive experiments.

    On this basis, the work can be extended to 2D convolution, edge detection, frequency-domain filtering, image compression, noise suppression, and WebGL-based parallel computation. By combining mathematical models, pixel data, and interactive interfaces, a general image-processing platform can be built for teaching, algorithm validation, and rapid prototyping.