Browser-Based Image Transforms, Spectrum Doodling, and Lossless Restoration

    This article walks through building a browser-based experiment page for image processing. It covers loading images into grayscale matrices, applying transforms such as matrix inversion, 2D Fourier magnitude/phase spectra, and horizontal derivatives, letting users doodle on the transformed data, and restoring the image through inverse transforms. Readers will learn the mathematical foundations, interaction design, rendering strategies, and numerical stability practices needed to make these transformations observable and interactive.

    1. Project Overview

    Image processing is more than directly modifying pixel colors. A 2D image can be analyzed from the spatial domain, the frequency domain, and the derivative domain. Each representation preserves different information: the spatial domain is intuitive, the frequency domain reveals texture and structure, and the derivative domain is well suited for edges and change trends.

    This article designs a browser-based experiment page with the following core workflow:

    1. The user loads an image.
    2. The page converts the image into a grayscale matrix suitable for computation.
    3. A transform is executed based on the current mode.
    4. The user doodles on the transformed result.
    5. The system restores the image using saved original data or an inverse transform.
    6. The page displays the original image, the transformed result, the doodled result, and the restored result side by side.

    “Doodling” is not just a visual effect. It helps us see directly which information is affected when data is modified, and why certain transforms can be restored while others produce errors.

    2. Overall Architecture

    The page can be divided into four layers.

    2.1 Image Input Layer

    This layer reads a local image and draws it onto a canvas. After loading, it obtains RGBA data through the pixel API and converts it to a grayscale matrix.

    Grayscale conversion can use the common weighted method:

    1. function toGray(data, width, height) {
    2. const gray = new Float64Array(width * height);
    3. for (let i = 0, p = 0; i < gray.length; i++, p += 4) {
    4. const r = data[p];
    5. const g = data[p + 1];
    6. const b = data[p + 2];
    7. gray[i] = 0.299 * r + 0.587 * g + 0.114 * b;
    8. }
    9. return gray;
    10. }

    Storing intermediate results in floating-point arrays is critical. Converting to 8-bit integers too early loses negative values, out-of-range values, and fractional parts, which eventually causes visible distortion in the restored result.

    2.2 Transform Layer

    The transform layer converts spatial-domain data into the chosen representation. Supported modes include:

    • Image matrix inversion
    • Image magnitude spectrum
    • Image phase spectrum
    • Magnitude and phase spectra processed together
    • Horizontal derivative of the image

    Each mode should provide functions in both directions:

    1. const mode = {
    2. forward(matrix) {
    3. // Spatial domain -> current representation
    4. },
    5. inverse(data) {
    6. // Current representation -> spatial domain
    7. }
    8. };

    This keeps drawing logic separate from mathematical logic and makes it easy to add new transforms later.

    2.3 Interaction Layer

    The interaction layer handles mouse or touch events and maps the user’s strokes onto the target canvas. Doodling can use semi-transparent colors, a fixed brush width, or a pressure-independent circular brush.

    Note that the display canvas size does not necessarily equal the original image size, so coordinate conversion is required:

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

    If the scale ratio is ignored, the stroke position the user sees will not match the actual data position, especially with high-resolution images or responsive layouts.

    2.4 Rendering Layer

    The rendering layer converts matrices into displayable pixels. Different data types require different normalization strategies.

    An ordinary grayscale image can be clamped directly to [0, 255]:

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

    Spectra usually have a very large dynamic range, so logarithmic compression is recommended:

    1. function normalizeSpectrum(value, maxValue) {
    2. const compressed = Math.log1p(Math.abs(value));
    3. const maxCompressed = Math.log1p(maxValue);
    4. return maxCompressed === 0
    5. ? 0
    6. : 255 * compressed / maxCompressed;
    7. }

    3. Image Matrix Inversion Mode

    Let the grayscale matrix be (A). When it is square and invertible, its inverse (A^{-1}) can be computed. In practice, however, images are usually not square, and image matrices are often rank-deficient, ill-conditioned, or non-invertible, so plain matrix inversion cannot be applied to arbitrary images.

    To make this mode practically usable, consider the following strategies:

    1. Crop or scale the image into a smaller square matrix.
    2. Use a regularized pseudo-inverse.
    3. Process the matrix in blocks.
    4. Position the inversion mode as a mathematical demonstration rather than a high-performance restoration solution.

    For matrix inversion, augmented-matrix elimination is an intuitive implementation. The basic idea is to concatenate matrix (A) with the identity matrix (I):

    [
    [A|I]
    ]

    Through elementary row operations, the left side is reduced to the identity matrix, and the right side becomes the inverse.

    Core pseudocode:

    1. function inverseMatrix(input, n, epsilon = 1e-10) {
    2. const aug = Array.from({ length: n }, (_, row) => {
    3. const line = new Float64Array(n * 2);
    4. for (let col = 0; col < n; col++) {
    5. line[col] = input[row * n + col];
    6. }
    7. line[n + row] = 1;
    8. return line;
    9. });
    10. for (let col = 0; col < n; col++) {
    11. let pivot = col;
    12. for (let row = col + 1; row < n; row++) {
    13. if (Math.abs(aug[row][col]) > Math.abs(aug[pivot][col])) {
    14. pivot = row;
    15. }
    16. }
    17. if (Math.abs(aug[pivot][col]) < epsilon) {
    18. throw new Error("Matrix is not invertible");
    19. }
    20. [aug[col], aug[pivot]] = [aug[pivot], aug[col]];
    21. const divisor = aug[col][col];
    22. for (let k = 0; k < 2 * n; k++) {
    23. aug[col][k] /= divisor;
    24. }
    25. for (let row = 0; row < n; row++) {
    26. if (row === col) continue;
    27. const factor = aug[row][col];
    28. for (let k = 0; k < 2 * n; k++) {
    29. aug[row][k] -= factor * aug[col][k];
    30. }
    31. }
    32. }
    33. const result = new Float64Array(n * n);
    34. for (let row = 0; row < n; row++) {
    35. for (let col = 0; col < n; col++) {
    36. result[row * n + col] = aug[row][n + col];
    37. }
    38. }
    39. return result;
    40. }

    In a real web page, inverting a large image as a whole is not recommended: the time complexity is high, memory consumption is large, and numerical stability is poor. A more reasonable approach is to scale the image down to a small size to demonstrate the characteristics of matrix operations.

    4. 2D Fourier Transform and Spectrum Processing

    The 2D Fourier transform converts an image from the spatial domain to the frequency domain. The result is complex:

    [
    F(u,v)=R(u,v)+iI(u,v)
    ]

    It can be further expressed as magnitude and phase:

    [
    M(u,v)=\sqrt{R^2+I^2}
    ]

    [
    P(u,v)=\operatorname{atan2}(I,R)
    ]

    Magnitude reflects the strength of each frequency component, while phase records structural positional relationships. In many cases, contours, edges, and object layouts are highly sensitive to phase. If only the magnitude is kept and the phase is lost, the restored image usually loses its clear structure.

    4.1 Direct 2D Transform Implementation

    For clarity, the 2D transform can be implemented directly from the discrete definition:

    1. function dft2D(input, width, height) {
    2. const real = new Float64Array(width * height);
    3. const imag = new Float64Array(width * height);
    4. for (let v = 0; v < height; v++) {
    5. for (let u = 0; u < width; u++) {
    6. let sumR = 0;
    7. let sumI = 0;
    8. for (let y = 0; y < height; y++) {
    9. for (let x = 0; x < width; x++) {
    10. const angle = 2 * Math.PI *
    11. (u * x / width + v * y / height);
    12. const value = input[y * width + x];
    13. sumR += value * Math.cos(angle);
    14. sumI -= value * Math.sin(angle);
    15. }
    16. }
    17. const index = v * width + u;
    18. real[index] = sumR;
    19. imag[index] = sumI;
    20. }
    21. }
    22. return { real, imag };
    23. }

    This implementation is structurally clear but has high time complexity, making it suitable for small images or teaching demonstrations. For larger images, the fast Fourier transform approach should be used, splitting the 2D transform into row-wise and column-wise transforms.

    4.2 Spectrum Centering

    In a discrete spectrum, the low-frequency components sit at the corners by default. For easier observation, the spectrum is usually centered:

    1. function shiftSpectrum(data, width, height) {
    2. const result = new Float64Array(data.length);
    3. const halfW = Math.floor(width / 2);
    4. const halfH = Math.floor(height / 2);
    5. for (let y = 0; y < height; y++) {
    6. for (let x = 0; x < width; x++) {
    7. const nx = (x + halfW) % width;
    8. const ny = (y + halfH) % height;
    9. result[ny * width + nx] = data[y * width + x];
    10. }
    11. }
    12. return result;
    13. }

    When displaying a spectrum, centering and logarithmic scaling are typically used together; otherwise the low-frequency region is overly bright and high-frequency details are nearly invisible.

    5. Magnitude Spectrum, Phase Spectrum, and Doodling Effects

    5.1 Modifying Only the Magnitude Spectrum

    Doodling on the magnitude spectrum can be understood as changing the energy of different frequency components. Drawing lines on the spectrum may enhance or weaken certain textures, edges, or periodic structures.

    During restoration, the original phase is preserved, and the doodled magnitude is recombined with the original phase:

    1. function composeComplex(magnitude, phase) {
    2. const real = new Float64Array(magnitude.length);
    3. const imag = new Float64Array(magnitude.length);
    4. for (let i = 0; i < magnitude.length; i++) {
    5. real[i] = magnitude[i] * Math.cos(phase[i]);
    6. imag[i] = magnitude[i] * Math.sin(phase[i]);
    7. }
    8. return { real, imag };
    9. }

    This mode usually preserves much of the spatial structure because the phase is intact, but texture, sharpness, and local contrast may change noticeably.

    5.2 Modifying Only the Phase Spectrum

    Phase doodling directly affects structural positioning. Even if the magnitude stays unchanged, significant phase modifications can alter edges and object contours in the image.

    Phase is an angular value with periodicity. For example:

    [
    -\pi \equiv \pi
    ]

    Therefore, when drawing on the phase, results should be constrained to a valid range:

    1. function wrapPhase(value) {
    2. while (value > Math.PI) value -= 2 * Math.PI;
    3. while (value < -Math.PI) value += 2 * Math.PI;
    4. return value;
    5. }

    In actual interaction, the brush influence can be converted into a small angular increment rather than setting the phase to a fixed value directly. This reduces abrupt changes and prevents large-scale artifacts in the restored result.

    5.3 Modifying Magnitude and Phase Together

    Doodling on both is a more destructive mode. Magnitude determines frequency energy and phase determines structural position; changing both at once can cause texture changes, contour shifts, local artifacts, and overall contrast changes in the restored image.

    To support comparison, the page should retain four copies of data:

    • The original spatial-domain matrix
    • The original complex spectrum
    • The doodled magnitude and phase
    • The final inverse-transformed matrix

    Do not overwrite the original data with doodled results; otherwise the user cannot return to the initial state when undoing, switching modes, or re-restoring.

    6. Horizontal Derivative of the Image

    The horizontal derivative describes how the image changes along the horizontal direction. The simplest first-order difference is:

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

    The corresponding implementation:

    1. function horizontalDerivative(input, width, height) {
    2. const output = new Float64Array(input.length);
    3. for (let y = 0; y < height; y++) {
    4. for (let x = 0; x < width - 1; x++) {
    5. const current = input[y * width + x];
    6. const next = input[y * width + x + 1];
    7. output[y * width + x] = next - current;
    8. }
    9. output[y * width + width - 1] = 0;
    10. }
    11. return output;
    12. }

    Derivative results contain both positive and negative values and cannot be displayed directly as an ordinary grayscale image. For display, the zero point can be mapped to mid-gray:

    1. function derivativeToGray(value, scale = 1) {
    2. return clampByte(128 + value * scale);
    3. }

    The inverse of the derivative mode is essentially accumulation. Given the initial value of a row, the image can be restored recursively:

    [
    I(x+1,y)=I(x,y)+D(x,y)
    ]

    However, since the initial value is unknown and doodling introduces errors, the restored result may suffer from overall brightness drift. Therefore, a baseline value for each row or for the whole image should be saved, with range correction applied after restoration.

    7. Engineering Details of Doodle Interaction

    7.1 Use an Independent Overlay Layer

    Two canvases are recommended:

    • Bottom canvas: displays the transformed data
    • Top canvas: displays the user’s strokes

    This avoids recomputing the entire image on every mouse move. When the user finishes drawing, the overlay strokes are converted into data modifications.

    7.2 Support Continuous Strokes

    Mouse events may arrive at intervals, so drawing discrete dots produces broken lines. Record the previous point and connect with line segments:

    1. function drawStroke(ctx, from, to, radius, color) {
    2. ctx.strokeStyle = color;
    3. ctx.lineWidth = radius * 2;
    4. ctx.lineCap = "round";
    5. ctx.beginPath();
    6. ctx.moveTo(from.x, from.y);
    7. ctx.lineTo(to.x, to.y);
    8. ctx.stroke();
    9. }

    7.3 Control the Brush Influence Range

    For spectrum or derivative data, the brush should not overwrite values with fixed numbers. A more stable approach uses Gaussian weights, so the center is affected most and the influence decays toward the edges:

    [
    w(d)=e^{-d^2/(2\sigma^2)}
    ]

    The modification can be written as:

    [
    V’(x,y)=V(x,y)+\alpha w(d)
    ]

    This reduces ringing and discontinuities caused by hard edges.

    8. Numerical Stability and Performance Optimization

    Image transforms involve heavy floating-point computation. Keep the following points in mind:

    1. Use floating-point arrays for intermediate steps.
    2. Perform normalization and integer conversion only at the display stage.
    3. Add guards for extremely large and small values.
    4. Apply logarithmic compression to spectra.
    5. Avoid re-running the full inverse transform on every mouse-move event.
    6. Scale large images down before using them in teaching demonstrations.
    7. Move computation into a background worker thread when necessary to avoid blocking page interaction.

    A direct 2D discrete transform has high complexity. In an engineering implementation, it can be optimized by separating row and column computations, reducing redundant trigonometric calculations, and caching sine/cosine tables. For interactive scenarios, throttling can also be applied so that expensive restoration runs only after the user stops dragging.

    9. Recommended Page Workflow

    A complete page can include the following controls:

    • Image selection button
    • Transform mode dropdown
    • Execute transform button
    • Start doodling button
    • Undo and clear buttons
    • Restore button
    • Four display areas: original image, transformed image, doodled image, and restored image
    • Current image dimensions, transform duration, and error indicators

    The recommended workflow:

    1. Load the image and scale it uniformly.
    2. Convert it to a grayscale matrix.
    3. Save a copy of the original data.
    4. Execute the selected forward transform.
    5. Render the result onto the canvas.
    6. Let the user doodle.
    7. Map the strokes into data modifications.
    8. Execute the inverse transform.
    9. Clamp the restored result to a valid range.
    10. Display the restored image and allow restarting.

    10. Conclusion

    The value of a “transform—doodle—restore” page is not in producing a fixed visual effect, but in turning abstract image mathematics into an operable, observable experiment.

    The matrix inversion mode illustrates invertibility, numerical error, and ill-conditioning. The magnitude spectrum demonstrates changes in frequency energy. The phase spectrum shows the importance of structural position. Modifying magnitude and phase together demonstrates compound perturbation, and the horizontal derivative helps explain the relationship between edge detection, differencing, and integral restoration.

    In implementation, keep data separate from display, original data separate from edited data, and forward transforms separate from inverse transforms. With modular design, the page can support not only the five modes described above but also be extended with 2D convolution, edge enhancement, noise injection, filter visualization, and more—ultimately forming an interactive tool suited for teaching, experimentation, and front-end image processing research.