Image Transformation, Doodling, and Restoration in JavaScript: A Practical Guide

    This article explores how to apply mathematical transformations to images in the browser, add doodles or masks in the transformed domain, and restore the original image through inverse transformations using JavaScript and Canvas. It covers five modes—inverse matrix, magnitude spectrum, phase spectrum, combined magnitude and phase, and row derivative—along with implementation details such as pixel-to-number mapping, performance, mask design, and visualization. The key takeaway is that reversibility depends on information completeness, and the location of corruption determines the severity of loss.

    1. Background and Core Approach

    In image processing and front-end visualization, a common and challenging task is to apply a mathematical transformation to an image, add doodles (occlusion, noise, or smearing) in the transformed domain, and then attempt to recover the image through an inverse transformation. This process essentially explores how information is distributed across different representation spaces and which parts, when damaged, cause irreversible loss.

    The value of this experiment lies not only in its visual appeal but also in how it reveals the differences in how information is carried in the frequency domain, gradient domain, and matrix domain. In a browser environment, the pixel read/write capabilities of Canvas combined with numerical computation in JavaScript are sufficient to complete the entire workflow without a server.

    The overall technical pipeline consists of four steps:

    1. Read the source image pixels and convert them into a numerical matrix;
    2. Apply a forward transformation to map the image into the target domain;
    3. Overlay a doodle mask in the target domain;
    4. Apply the inverse transformation, observe the restoration result, and analyze the sources of loss.

    2. Principles and Implementation of Five Transformation Modes

    2.1 Inverse Matrix Transformation and Restoration

    Treat the image as a 2D matrix, construct an invertible linear transformation matrix, and multiply the image from the left or right. The doodle is applied to the elements of the transformed matrix; during restoration, multiplying by the inverse matrix recovers the image.

    1. // Example: matrix transformation and inverse transformation
    2. function matMul(A, B) {
    3. const n = A.length, m = B[0].length, k = B.length;
    4. const C = Array.from({length: n}, () => new Array(m).fill(0));
    5. for (let i = 0; i < n; i++)
    6. for (let j = 0; j < m; j++)
    7. for (let t = 0; t < k; t++) C[i][j] += A[i][t] * B[t][j];
    8. return C;
    9. }
    10. // Restoration: recovered = inv(T) * doodled

    The key point is that the transformation matrix must be numerically stable. A large condition number amplifies errors in the inverse matrix computation, causing visible distortion even in pixels outside the doodled area.

    2.2 Magnitude Spectrum Doodling and Restoration

    After applying a 2D discrete Fourier transform to the image, the complex spectrum can be split into a magnitude spectrum and a phase spectrum. Smearing only a local region of the magnitude spectrum and then applying the inverse transform preserves the overall outline, but textures and details become significantly blurred. This shows that the magnitude carries the energy distribution, while structural information relies more on the phase.

    2.3 Phase Spectrum Doodling and Restoration

    In contrast to the magnitude spectrum, damaging the phase spectrum severely scrambles the image structure, making it unrecognizable even when the magnitude is intact. This comparison is one of the most classic conclusions in frequency-domain analysis and is very intuitive to reproduce in code.

    1. // Example: spectrum splitting and recombination
    2. const spectrum = fft2(imageData);
    3. const mag = spectrum.map(c => Math.hypot(c.re, c.im));
    4. const phase = spectrum.map(c => Math.atan2(c.im, c.re));
    5. // Apply a mask to phase and recombine
    6. const restored = ifft2(combine(mag, doodledPhase));

    2.4 Simultaneous Doodling of Magnitude and Phase

    When both are corrupted at the same time, the restoration result is almost unusable. This inversely confirms that reversible transformations depend on complete information. In engineering, this can be used to demonstrate the concept of “information redundancy”.

    2.5 Row Derivative Doodling and Restoration

    Apply a first-order difference (discrete derivative) to each row, then restore by cumulative summation after doodling. Because the derivative loses the DC component (the starting constant) of each row, the restored image exhibits an overall brightness drift. Accurately reconstructing the image requires saving the first row or first pixel as a boundary condition.

    1. // Forward and inverse row derivative transformation
    2. const deriv = row.map((v, i) => i === 0 ? v : v - row[i - 1]);
    3. const restored = [];
    4. deriv.forEach((v, i) => restored.push(i === 0 ? v : v + restored[i - 1]));

    3. Key Engineering Details

    • Pixel-to-number mapping: Map 0–255 integers into a floating-point computation space, then apply truncation and rounding after the inverse transformation to avoid overflow.
    • Performance: A pure JavaScript 2D Fourier transform has high complexity. You can first perform separable 1D row and column transforms to reduce computation, or downsample before demonstrating.
    • Mask design: Parameterize the doodle mask (position, radius, intensity) to make it easy to compare restoration quality under different degrees of corruption.
    • Side-by-side visualization: Displaying the original image, transformed domain, doodled version, and restored image in a four-panel view is the most effective way to understand the process.

    4. Scaling Up and Deployment Suggestions

    For larger images or higher performance requirements, move the computation-intensive parts to the cloud using a combination of general-purpose capabilities: use object storage to save original and result images, use a container platform to run batch computation tasks, use a message queue to decouple task scheduling, and use logging, monitoring, and alerting services to track task status. Baidu AI Cloud offers mature solutions in these general categories, and you can choose based on your needs.

    5. Conclusion

    The five modes together demonstrate one core conclusion: the reversibility of a transformation depends on information completeness, and the location of corruption determines the severity of the loss. The contrast between magnitude and phase, and the boundary-condition issue in the derivative domain, are excellent entry points for understanding signal representation theory. With these principles in hand, developers can make more reasonable design trade-offs in scenarios such as image compression, watermarking, and fault-tolerant transmission.