Scribble and Restore Image Transforms in JavaScript

    This article shows how to build a browser page that transforms an image, lets users scribble on the transformed data, and restores the image with the inverse transform. It covers a shared data pipeline and five modes: inverse matrix, Fourier magnitude and phase editing, joint editing, and row-difference integration. It includes JavaScript code for each mode, along with notes on numerical stability, performance, and maintainability.

    A web page that transforms an image, lets users scribble on the transformed data, and then restores the image is, at its core, a reversible transform split into three stages: a forward transform, an interactive edit, and an inverse transform. The page first maps the source image into a transform domain and displays it. Users then draw over the transform-domain data with a brush. Finally, the matching inverse operation returns the result to the image domain. This process suits image processing teaching, algorithm visualization, interactive experiments, and front-end engineering practice. This article discusses implementation approaches and engineering details for five common modes, using vanilla JavaScript and the general Canvas interface.

    1. Overall Architecture and Unified Data Flow

    A maintainable implementation should avoid writing five unrelated page logics for the five modes. Instead, it should share one data flow:

    1. Source image layer: Draw the image onto an offscreen canvas, read the pixel data, and extract the luminance channel as a single-channel matrix. Keep the alpha channel for the final compositing.
    2. Transform domain layer: Apply the forward transform to the luminance matrix according to the current mode. Map the resulting transform-domain array to an editable canvas using a display rule.
    3. Scribble mask layer: Listen for pointer events and record the transform-domain cells covered by the user’s strokes. The result is either a mask or a direct modification of the transform-domain array.
    4. Inverse transform layer: Pass the modified transform-domain data to the matching inverse transform to get the restored image matrix.
    5. Rendering and comparison layer: Display the original image, the transform-domain view, the scribble layer, and the restored image as separate layers, so users can see how each edit affects the result.

    Display normalization and computation data must stay separate. Transform-domain values can fall outside the range 0 to 255. If you clip them for display, the clipped values must not feed into the inverse transform, because that introduces irreversible error. The correct approach is to keep the original floating-point array and apply only a linear or logarithmic mapping when drawing to the canvas. When the user scribbles, convert the display values back to the computation domain, or restrict edits to an agreed finite range.

    A generic skeleton can be simplified as follows:

    1. function toGray(imageData) {
    2. const { data, width, height } = imageData;
    3. const gray = new Float32Array(width * height);
    4. for (let i = 0, p = 0; i < data.length; i += 4, p++) {
    5. gray[p] = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
    6. }
    7. return gray;
    8. }
    9. function renderGray(canvas, gray, width, height, min, max) {
    10. const ctx = canvas.getContext('2d');
    11. const img = ctx.createImageData(width, height);
    12. const scale = 255 / Math.max(1e-6, max - min);
    13. for (let p = 0, i = 0; p < gray.length; p++, i += 4) {
    14. const v = Math.max(0, Math.min(255, (gray[p] - min) * scale));
    15. img.data[i] = img.data[i + 1] = img.data[i + 2] = v;
    16. img.data[i + 3] = 255;
    17. }
    18. ctx.putImageData(img, 0, 0);
    19. }

    2. Inverse Matrix Mode: Scribbling in an Invertible Linear Transform Domain

    The key to the inverse matrix mode is not to invert the image matrix directly. Instead, choose an invertible linear transform matrix (A) that maps the image data into the transform domain, (y = Ax). After the user edits (y), restore the image with (x = A^{-1}y). A single-channel image cannot be multiplied directly by an arbitrary two-dimensional matrix, so engineering implementations typically use a block strategy. One option groups adjacent pixels into two-dimensional vectors. The other applies an invertible affine sampling transform to the whole image. The first option suits demonstrating matrix inversion, and the second suits geometric transforms such as rotation and shear.

    Take adjacent pixel pairs as an example. Let:

    [
    \begin{bmatrix}y_0\y_1\end{bmatrix}
    =
    \begin{bmatrix}a&b\c&d\end{bmatrix}
    \begin{bmatrix}x_0\x_1\end{bmatrix},\quad \det=ad-bc\neq 0
    ]

    The inverse matrix is:

    [
    A^{-1}=\frac{1}{\det}
    \begin{bmatrix}d&-b\-c&a\end{bmatrix}
    ]

    The implementation must handle odd-length data, boundary pixels, and dynamic range. Scribble edits change (y). After restoration, the edit spreads across neighboring pixel pairs and produces a visible linear mixing effect. When the matrix is close to singular, the inverse transform amplifies numerical error. The interface should therefore limit the parameter range or warn the user when the determinant is too small.

    1. function invert2x2(A) {
    2. const [[a, b], [c, d]] = A;
    3. const det = a * d - b * c;
    4. if (Math.abs(det) < 1e-8) throw new Error('矩阵不可逆');
    5. return [[d / det, -b / det], [-c / det, a / det]];
    6. }
    7. function applyPairMatrix(src, A, inverse = false) {
    8. const M = inverse ? invert2x2(A) : A;
    9. const out = new Float32Array(src.length);
    10. for (let i = 0; i < src.length; i += 2) {
    11. const x0 = src[i], x1 = i + 1 < src.length ? src[i + 1] : 0;
    12. out[i] = M[0][0] * x0 + M[0][1] * x1;
    13. if (i + 1 < src.length) {
    14. out[i + 1] = M[1][0] * x0 + M[1][1] * x1;
    15. }
    16. }
    17. return out;
    18. }

    Note: the error message in the code above, '矩阵不可逆', means “matrix is not invertible.” If you use the code as written, translate it to 'Matrix is not invertible'.

    3. Magnitude Spectrum, Phase Spectrum, and Joint Scribbling

    The discrete Fourier transform decomposes an image into frequency components. For a two-dimensional image (I(x,y)), the frequency-domain result contains real and imaginary parts. From these, you can derive the magnitude and phase spectra:

    [
    M(u,v)=|F(u,v)|,\quad \phi(u,v)=\arg F(u,v)
    ]

    The implementation supports three interaction modes:

    • Magnitude scribbling: Edit only the magnitude (M), keep the phase (\phi), and apply the inverse transform. Phase usually carries structural information, so the restored image typically keeps its main outlines, but brightness, contrast, and some textures change.
    • Phase scribbling: Edit only the phase, keep the magnitude, and apply the inverse transform. Phase changes usually cause more dramatic structural changes, which makes this mode useful for showing how important phase is to image structure.
    • Joint scribbling: Edit both magnitude and phase, then apply the inverse transform. This mode gives the most freedom, but it also produces strong artifacts most easily. Handle numerical clipping and dynamic range normalization carefully.

    When implementing this, display the spectrum with a logarithm of the magnitude, (\log(1+M)). Otherwise, low-magnitude regions are nearly invisible. Phase can be mapped linearly to grayscale. After a user scribbles, convert canvas coordinates back to frequency-array indices, and modify only the cells the stroke covers. The simple two-dimensional DFT has high computational cost, so use it only for small demo images. For larger images, use separable computation or fast Fourier transform methods, and run the calculation in a background thread so it does not block interaction.

    1. function dft2d(gray, w, h) {
    2. const re = new Float32Array(w * h);
    3. const im = new Float32Array(w * h);
    4. for (let v = 0; v < h; v++) {
    5. for (let u = 0; u < w; u++) {
    6. let sr = 0, si = 0;
    7. for (let y = 0; y < h; y++) {
    8. for (let x = 0; x < w; x++) {
    9. const angle = -2 * Math.PI * (u * x / w + v * y / h);
    10. const c = Math.cos(angle), s = Math.sin(angle);
    11. const p = gray[y * w + x];
    12. sr += p * c;
    13. si += p * s;
    14. }
    15. }
    16. re[v * w + u] = sr;
    17. im[v * w + u] = si;
    18. }
    19. }
    20. return { re, im };
    21. }
    22. function spectrumView(re, im, mode) {
    23. const out = new Float32Array(re.length);
    24. for (let i = 0; i < re.length; i++) {
    25. const mag = Math.hypot(re[i], im[i]);
    26. const phase = Math.atan2(im[i], re[i]);
    27. if (mode === 'magnitude') out[i] = Math.log1p(mag);
    28. else if (mode === 'phase') out[i] = (phase + Math.PI) / (2 * Math.PI) * 255;
    29. else out[i] = Math.log1p(mag) + phase;
    30. }
    31. return out;
    32. }

    The inverse step recombines the data according to the mode. Magnitude mode combines the scribbled magnitude with the original phase. Phase mode combines the original magnitude with the scribbled phase. Joint mode uses both scribbled values. Finally, take the real part and apply global normalization. Centering the frequency domain is only a display convention. The computation-domain indices must match the display coordinates.

    4. Row Derivative Mode: Difference Scribbling and Integration Restoration

    The row derivative mode takes differences along the row direction to produce edge or gradient responses. The user then edits the difference image, and the cumulative sum restores the image. Let:

    [
    D(i,j)=I(i,j)-I(i-1,j)
    ]

    The restoration step is:

    [
    I(i,j)=I(0,j)+\sum_{k=1}^{i}D(k,j)
    ]

    The first row or a boundary constant must be preserved. Otherwise, the restored image shifts overall. A scribble that edits one cell in the difference domain affects all later rows in that column through the cumulative sum. It appears as a vertical smear or a brightness shift. To reduce accumulated error, apply mean correction after integration, or provide a switch that keeps the first row as a reference.

    1. function rowDiff(gray, w, h) {
    2. const diff = new Float32Array(gray.length);
    3. for (let y = 1; y < h; y++) {
    4. for (let x = 0; x < w; x++) {
    5. diff[y * w + x] = gray[y * w + x] - gray[(y - 1) * w + x];
    6. }
    7. }
    8. return diff;
    9. }
    10. function rowIntegrate(diff, firstRow, w, h) {
    11. const out = new Float32Array(diff.length);
    12. for (let x = 0; x < w; x++) out[x] = firstRow[x];
    13. for (let y = 1; y < h; y++) {
    14. for (let x = 0; x < w; x++) {
    15. out[y * w + x] = out[(y - 1) * w + x] + diff[y * w + x];
    16. }
    17. }
    18. return out;
    19. }

    5. Interaction, Performance, and Maintainability Recommendations

    First, use layered canvases. Draw the base image, the transform-domain view, and the scribble mask separately. This avoids recalculating the whole transform each time the stroke moves. Second, control the experiment resolution. Frequency-domain and matrix operations are sensitive to pixel count. Scale the image down for interactive editing, then render a full-resolution result when needed. Third, use typed arrays and batch loops to reduce object allocation. Fourth, cache expensive transforms. When the transform parameters do not change, recompute only the inverse transform, not the forward transform. Fifth, provide a round-trip error metric, such as mean squared error or maximum absolute error, to check whether the forward and inverse transforms restore the image closely when nothing is scribbled. Sixth, handle edge cases explicitly: division by zero, non-finite values, dynamic range overflow, odd pixel counts, and empty masks each need a clear policy. Seventh, provide undo and redo, and clear the state when the user switches modes, so data from different transform domains never mix.

    In summary, the inverse matrix mode depends on an invertible linear mapping and numerical stability. The magnitude, phase, and joint modes depend on frequency decomposition and visualization mapping. The row derivative mode depends on the boundary handling and cumulative error of differencing and integration. Organizing all five modes around the same pipeline (source image, transform, scribble, inverse transform, comparison) keeps the implementation manageable and gives a clear base for adding more reversible transforms later.