Image Transform-Domain Graffiti and Restoration in JavaScript
This article explores how to apply reversible transforms to images, inject graffiti in a chosen representation domain, and restore the result using JavaScript in the browser. It covers five modes—inverse-matrix reconstruction, magnitude-spectrum graffiti, phase-spectrum graffiti, combined magnitude and phase graffiti, and row-derivative-domain graffiti—along with the underlying principles, browser-side engineering practices, and error metrics. Readers will learn which components carry structure and which carry detail, and how to build an interactive experiment for image coding, compression, watermarking, and robustness studies.
1. Background and Overall Approach
In image processing and front-end visualization, there is a particularly interesting and instructive class of problems: first apply a reversible transform to an image, moving pixels from the spatial domain into another representation domain; then add graffiti (perturbations) in that domain; and finally apply the inverse transform to return to the spatial domain and observe how badly the image is damaged—or how well it survives. This process both demonstrates how information is distributed across different transform domains and helps developers understand which components carry structure and which carry detail.
The original material is organized around five modes: inverse-matrix reconstruction, magnitude-spectrum graffiti, phase-spectrum graffiti, simultaneous magnitude and phase graffiti, and row-derivative-domain graffiti. Together they form a complete experimental framework. This article reorganizes the logic and fills in the engineering implementation details to produce a practical guide that runs directly in the browser.
The overall workflow can be abstracted into four steps:
- Read the image and normalize it into a numeric matrix suitable for computation.
- Apply the forward transform to obtain coefficient representations in the target domain.
- Overlay a graffiti mask in the target domain (sine stripes, random noise, block occlusion, and so on).
- Apply the inverse transform, write the result back to the canvas, and compare the restoration quality.
It is worth emphasizing that all computation should be performed in the browser as much as possible, avoiding the privacy and bandwidth costs of uploading images. For large pixel counts, chunked processing and asynchronous scheduling can prevent blocking the main thread.
2. Technical Principles of the Five Transform Domains
2.1 Inverse-Matrix Reconstruction Mode
The core of this mode is to construct an invertible linear transform matrix that maps the flattened image vector to a coefficient vector, then restore the image via matrix inversion. Let the transform matrix be A and the original vector be x; the coefficients are y = A x. After graffiti, y’ = y + d, and the restored result is x’ = A⁻¹ y’. Because of the linear superposition property, the final error is exactly A⁻¹ d, which provides an analytical basis for studying how graffiti propagates.
From an engineering standpoint, matrix size matters. If the image has N pixels, the matrix is N×N and the complexity is extremely high, so this mode is only practical for small demonstrations (such as a 16×16 grayscale image). An orthogonal matrix can be chosen to reduce numerical error, and a tiny regularization term can be added during inversion to avoid ill-conditioning.
Illustrative code:
function matMul(A, B) {const n = A.length, m = B[0].length, k = B.length;const C = Array.from({length: n}, () => new Array(m).fill(0));for (let i = 0; i < n; i++)for (let p = 0; p < k; p++)for (let j = 0; j < m; j++) C[i][j] += A[i][p] * B[p][j];return C;}// Restoration: x' = A_inv * (A * x + d)const restored = matMul(Ainv, add(matMul(A, x), d));
2.2 Magnitude-Spectrum Graffiti and Restoration
The 2D discrete Fourier transform decomposes an image into a magnitude spectrum and a phase spectrum. The magnitude spectrum describes the strength of each frequency component and determines the overall energy distribution and contrast structure of the image; the phase spectrum describes the relative position of each frequency component and determines the spatial arrangement of edges and textures.
A common approach to magnitude-spectrum graffiti is to add low-amplitude sine stripes or random blocks near the center of the frequency domain, then apply the inverse transform. Because the human eye is relatively insensitive to magnitude perturbations, the image outline remains recognizable after mild graffiti, but overall brightness drift and periodic artifacts appear. In practice, centering must be applied first (moving low frequencies to the center), and after graffiti the inverse centering is applied.
// Pseudocode: magnitude-spectrum graffiticonst F = fft2(image); // complex 2D spectrumconst mag = magnitude(F), phase = angle(F);const magMasked = mag + graffitiPattern(mag.length, mag[0].length);const restored = ifft2(combine(magMasked, phase));
2.3 Phase-Spectrum Graffiti and Restoration
Phase-spectrum graffiti usually has a more severe effect than magnitude graffiti. Because spatial structure depends heavily on phase alignment, even a slight phase perturbation causes edge misalignment and disintegration of object contours, and the restored image is often unrecognizable. This is very intuitive in experiments: keeping the magnitude and scrambling the phase degrades the image into something close to noise texture; keeping the phase and scrambling the magnitude preserves the outline but distorts brightness.
Phase graffiti is therefore well suited to demonstrating the conclusion that “structure information mainly resides in the phase.” In engineering terms, a spatial gradient or random field can be added to the phase, then recombined with the original magnitude for the inverse transform.
2.4 Simultaneous Magnitude and Phase Graffiti
Perturbing both at once produces a combined destructive effect, and the restored image is usually completely unreadable. This mode works well as a control experiment for quantifying the sensitivity difference between the two components. Under the same mask strength, the mean squared error can be recorded separately for magnitude-only, phase-only, and dual perturbations, and a sensitivity curve can be plotted to help readers build a quantitative understanding.
2.5 Row-Derivative-Domain Graffiti
The row derivative is a spatial-domain difference transform: apply a first-order difference to each row to obtain a matrix of adjacent-pixel differences; restoration is exact via a prefix sum. Its advantages are simple implementation, linear complexity, and no need for inversion. Graffiti added in the derivative domain appears in the restored image as accumulated drift along the horizontal direction, forming stripe-shaped errors. Because the error accumulates along rows, row-derivative graffiti noticeably damages horizontal structure while having little effect on vertical edges, offering another intuitive example of directional information.
// Row-derivative forward transformfor (let y = 0; y < h; y++) {d[y][0] = img[y][0];for (let x = 1; x < w; x++) d[y][x] = img[y][x] - img[y][x-1];}// Inverse transform (prefix sum)for (let y = 0; y < h; y++)for (let x = 1; x < w; x++) img[y][x] = img[y][x-1] + d[y][x];
3. Browser-Side Engineering Implementation
First, canvas and pixel access. Use an offscreen canvas to hold the original and restored results, and convert pixels into matrices via the pixel array. Grayscale conversion can be done with a weighted sum first to reduce computation.
Second, performance strategy. A naive 2D Fourier transform has complexity on the order of O(N²) and must be chunked and made asynchronous. The image can be split into fixed-size tiles, enqueued tile by tile, and computed during idle time slices to avoid UI jank. For real-time interaction, a downsampled preview can be shown first, then recomputed at full resolution on demand.
Third, graffiti mask design. Masks should be parameterized: stripe frequency, direction, amplitude, and random seed. A fixed random seed ensures reproducible results and makes teaching comparisons easier.
Fourth, error metrics. It is recommended to provide both mean squared error and structural similarity; the former reflects energy deviation, while the latter is closer to subjective perception.
Fifth, accessibility and fallback. For environments that do not support certain features, provide a pure numeric-matrix demonstration mode so the core conclusions can still be shown.
4. Conclusion and Extensions
The five modes reveal the same thing from three angles—linear algebra, the frequency domain, and spatial differencing: image information is highly unevenly distributed across representation domains. Magnitude carries energy, phase carries structure, the derivative carries local variation, and the inverse matrix yields an analytically tractable error-propagation model. Integrating these experiments into a single interactive web page not only demonstrates the algorithms but also serves as an entry-level testbed for image coding, compression, watermarking, and robustness research. Possible extensions include multi-resolution analysis, block discrete cosine transform-domain graffiti, and experiment data collection built on monitoring, alerting, and logging services to form a reusable teaching and evaluation pipeline.
