Image Transform Domain Scribble Editing and Invertible Restoration: A Web Implementation

    This article explains how to build a web app that transforms an image, lets users scribble on the transformed view, and restores the edited image through the inverse transform. It covers the design goals, a layered architecture, and five transform modes: inverse matrix, magnitude spectrum, phase spectrum, joint magnitude and phase, and row derivative. It includes example JavaScript for the matrix, Fourier, and derivative operations, along with engineering practices for testing reversibility and keeping computation separate from display.

    Image Transform Domain Scribble Editing and Invertible Restoration: A Web Implementation

    1. Problem Definition and Design Goals

    Scribble editing followed by restoration in the transform domain is not a simple filter overlay. It is a complete, invertible editing loop. The system first applies a reversible transform to the image, producing a transform-domain view that is suitable for interaction. The user draws on that transform-domain canvas. The system writes the strokes back into the transform-domain data, then applies the matching inverse transform to rebuild the edited image. The main value of this approach is that developers can see how different image representations affect pixel reconstruction. It also gives image editing, teaching demos, and algorithm validation a single web framework.

    The design goals fall into four points:

    1. The transform must be reversible. At minimum, it must approximately restore the original image when no scribbles are applied.
    2. Scribbles must act on the transform domain, not on the final image, so the editing meaning stays clear.
    3. Display normalization must be separated from computation. Operations such as logarithmic display or grayscale mapping must not contaminate the reversible calculations.
    4. All five modes share one state management system and one rendering pipeline, which keeps the cost of extending the app low.

    2. Unified Web Architecture

    The recommended structure has four layers: data, transform, interaction, and reconstruction. The data layer stores the original image, the floating-point grayscale matrix, the transform-domain cache, the scribble mask, and the first-column reference. The transform layer runs the forward transform for the selected mode. The interaction layer uses a canvas brush and accumulates the strokes into a mask. The reconstruction layer applies the mask to the transform-domain data, runs the inverse transform, and renders the result.

    A typical state object looks like this:

    1. const state = {
    2. mode: 'matrix', // matrix | amplitude | phase | both | rowDerivative
    3. width: 0,
    4. height: 0,
    5. original: null, // Float32Array grayscale raw data
    6. transformed: null, // transform-domain cache
    7. transformedBackup: null, // for undo
    8. mask: null, // Uint8Array scribble mask
    9. params: {} // extra parameters for each mode
    10. };

    The processing flow is as follows. Load the image and convert it to a floating-point grayscale matrix. Run the forward transform and generate a visualization. While the user draws, update only the mask. When the user releases the stroke or clicks “Restore,” replace the transform-domain data inside the masked area with the brush values, or blend them in proportion to the mask. Then run the inverse transform, clip the values to the valid range, and render the result. The display layer may use logarithmic, gamma, or linear mapping, but the computation layer must keep the original floating-point values.

    3. Implementation of the Five Transform Modes

    1. Inverse Matrix Mode

    Inverse matrix mode demonstrates a reversible linear transform. You can define a non-singular 2×2 matrix and use it to mix two channels, or a grayscale channel and an auxiliary channel:

    1. function applyMatrix2(data, a, b, c, d) {
    2. const out = new Float32Array(data.length);
    3. for (let i = 0; i < data.length; i += 2) {
    4. const x = data[i], y = data[i + 1];
    5. out[i] = a * x + b * y;
    6. out[i + 1] = c * x + d * y;
    7. }
    8. return out;
    9. }
    10. function invert2(a, b, c, d) {
    11. const det = a * d - b * c;
    12. if (Math.abs(det) < 1e-8) throw new Error('Matrix is not invertible');
    13. return [d / det, -b / det, -c / det, a / det];
    14. }

    After the forward transform, the user scribbles in the transform domain, which modifies the corresponding values. Restoration then uses the inverse matrix. If you use a spatial affine transform, pay attention to inverse-mapping sampling, boundary padding, and interpolation error. If you only apply a linear mix across color channels, reversibility is more stable, which makes this approach better suited to teaching demos. In either case, check the determinant and limit floating-point clipping error.

    2. Magnitude Spectrum Mode

    The two-dimensional discrete Fourier transform decomposes an image into magnitude and phase. The magnitude spectrum shows the strength of each frequency component. The phase spectrum carries information about structural positions. To implement this, compute the complex spectrum first, then take its magnitude:

    1. function amplitudeOf(re, im) {
    2. const out = new Float32Array(re.length);
    3. for (let i = 0; i < re.length; i++) {
    4. out[i] = Math.hypot(re[i], im[i]);
    5. }
    6. return out;
    7. }

    When displaying the magnitude, log(1 + amplitude) is often used to compress the dynamic range. However, scribble editing should return to the linear magnitude domain. When the user draws on the magnitude spectrum view, the system changes only the magnitude values inside the mask, keeps the original phase, and then runs the inverse Fourier transform. Magnitudes must be non-negative, so clip the scribble values to a reasonable range.

    3. Phase Spectrum Mode

    The phase spectrum is highly sensitive to image structure. Phase values usually wrap within the interval [-π, π]. For visualization, you can map them linearly to grayscale. For computation, however, you must use the original phase values. When the user modifies the phase, keep the magnitude unchanged, then run the inverse transform. Avoid treating display grayscale values as phase values directly, because doing so introduces uncontrolled error.

    4. Joint Magnitude and Phase Mode

    Joint mode lets users edit magnitude and phase at the same time. You can design it with two canvases or with layer switching: one canvas shows the magnitude, another shows the phase, and each has its own mask. During reconstruction, apply each set of changes separately, then combine them into the complex spectrum. This mode carries the most information, but it also produces the most visible artifacts. Provide reset, undo, and local brushes so that users do not irreversibly damage the whole image.

    5. Row Derivative Mode

    Row derivative mode computes a first-order difference along each row:

    1. function rowDerivative(gray, w, h) {
    2. const d = new Float32Array(w * h);
    3. for (let y = 0; y < h; y++) {
    4. for (let x = 0; x < w; x++) {
    5. const idx = y * w + x;
    6. d[idx] = x === 0 ? gray[idx] : gray[idx] - gray[idx - 1];
    7. }
    8. }
    9. return d;
    10. }
    11. function integrateRows(d, firstCol, w, h) {
    12. const out = new Float32Array(w * h);
    13. for (let y = 0; y < h; y++) {
    14. let acc = firstCol[y];
    15. for (let x = 0; x < w; x++) {
    16. const idx = y * w + x;
    17. if (x === 0) out[idx] = acc;
    18. else {
    19. acc += d[idx];
    20. out[idx] = acc;
    21. }
    22. }
    23. }
    24. return out;
    25. }

    After the user modifies the derivative map, restore the image by accumulating the values. The first-column reference must be saved separately. Otherwise, the DC component is lost. This mode shows the relationship between differentiation and integration. It also makes it easy to see how a local edge change affects the reconstruction of an entire row.

    4. Fourier Transform Core Example

    For small image sizes, a direct discrete Fourier transform works well. It is easy to follow and needs no extra libraries. A two-dimensional transform can first run a row transform and then a column transform. In the inverse transform, divide each dimension by its length, which is equivalent to dividing the whole result by the total pixel count.

    1. function dft1d(re, im, inverse) {
    2. const n = re.length;
    3. const outRe = new Float64Array(n);
    4. const outIm = new Float64Array(n);
    5. const sign = inverse ? 1 : -1;
    6. for (let k = 0; k < n; k++) {
    7. let sr = 0, si = 0;
    8. for (let t = 0; t < n; t++) {
    9. const ang = sign * 2 * Math.PI * k * t / n;
    10. const c = Math.cos(ang), s = Math.sin(ang);
    11. sr += re[t] * c - im[t] * s;
    12. si += re[t] * s + im[t] * c;
    13. }
    14. outRe[k] = inverse ? sr / n : sr;
    15. outIm[k] = inverse ? si / n : si;
    16. }
    17. return { re: outRe, im: outIm };
    18. }
    19. function dft2d(gray, w, h, inverse) {
    20. let re = Array.from({ length: h }, (_, y) =>
    21. Float64Array.from(gray.subarray(y * w, y * w + w))
    22. );
    23. let im = Array.from({ length: h }, () => new Float64Array(w));
    24. for (let y = 0; y < h; y++) {
    25. const r = dft1d(re[y], im[y], inverse);
    26. re[y] = r.re; im[y] = r.im;
    27. }
    28. for (let x = 0; x < w; x++) {
    29. const cr = new Float64Array(h), ci = new Float64Array(h);
    30. for (let y = 0; y < h; y++) { cr[y] = re[y][x]; ci[y] = im[y][x]; }
    31. const r = dft1d(cr, ci, inverse);
    32. for (let y = 0; y < h; y++) { re[y][x] = r.re[y]; im[y][x] = r.im[y]; }
    33. }
    34. return { re, im };
    35. }

    This implementation suits teaching and validation at small sizes. For real-time interaction in production, use block processing, downsampled previews, and a cache of forward transform results. Run the inverse transform only when the user releases the stroke, and move heavy computation to a background thread.

    5. Engineering Practice and Validation

    First, strictly separate the computation domain from the display domain. Logarithmic magnitude, phase grayscale, and derivative normalization are for canvas display only. They must never overwrite the original transform-domain arrays.

    Second, use soft brushes for the scribble mask and accumulate opacity. Apply edits only to pixels where the mask is greater than zero. This makes local editing and undo easier.

    Third, set up reversibility tests. With no scribbles, compare the reconstructed image with the original using mean squared error or peak signal-to-noise ratio (PSNR). With scribbles, check that the changes stay in the expected area.

    Fourth, pay attention to numerical stability. Check all transform results for NaN, infinite values, and out-of-range values, and clip the output to the valid range after reconstruction.

    Fifth, provide reset, undo, mode switching, and result download, so that a single mistake does not lose the user’s state.

    Sixth, perform file reading and image processing locally whenever possible to reduce unnecessary data uploads. Make the processing scope clear in the interface.

    6. Conclusion

    The key to a transform-domain scribble and invertible restoration web app is not any single filter effect. It is the closed loop of forward transform, mask editing, and inverse transform, together with a clear separation between computation data and display data. The five modes (inverse matrix, magnitude spectrum, phase spectrum, joint spectrum, and row derivative) each show how an image can be represented from the perspective of linear algebra, frequency analysis, or differentiation and integration. Through unified state management, a floating-point data pipeline, mask compositing, and reversibility testing, you can build an image transform web app that is clear in structure, easy to extend, and suited to teaching and experimentation.