Reconstructing Each Pixel Only From Its Surroundings for Real-Time Defect Detection

A common way to find defects without defect examples is to train a network to reconstruct normal images and flag the pixels it reconstructs badly. This often fails because a capable network learns to copy whatever it is shown, defects included. The usual fixes, such as memory banks of normal patterns, quantized codebooks and adaptive capacity budgets, shrink what the network can represent. That costs latency. It also usually requires downsampling, which erases tiny defects such as hairline cracks and pinholes before scoring happens.

We propose removing the copy path from the architecture instead of starving the model. Each pixel is predicted only from a ring of context around it, while a central "hole" stays hidden from the predictor. The ring comes from dilated convolutions, which are convolutions whose taps are spread apart so they cover a wide area cheaply. The network runs at full resolution in one forward pass, using several hole sizes at once. A defect smaller than the hole is invisible to the predictor, so the predictor fills in what normal material would look like there, and the defect stands out. Two consequences follow. Tiny defects are favored rather than penalized, because they fit easily inside small holes. And how well the model reconstructs normal images no longer has to trade against how well it detects defects.

Core Claim

The network can only reproduce what its receptive field can see. Hiding the target region from the predictor therefore separates two things that standard autoencoders tie together: how well normal images are reconstructed, and how easily defects are reproduced. On the Pitfalls of Using the Residual Error as Anomaly Score motivates this work. It shows that higher-capacity generative models reconstruct normal data better but detect anomalies worse, and that residual scores collapse when an anomaly's intensity matches the background.

Our claim is specific and testable. With a hole-masked, multi-radius context predictor, increasing capacity should improve detection rather than hurt it. Detection quality should be highest for defects smaller than the largest hole. And the whole system should fit a real-time budget at native resolution, because it needs neither downsampling, nor a nearest-neighbor search, nor repeated masked passes.

We do not claim the method fixes the pure-intensity blind spot. If a defect has the same intensity and the same texture as the tissue around it, no pixel predictor can see it. We do expect gains where the texture differs, for example shuffled pixels inside smooth tissue. A context predictor forecasts a smooth value there, whereas a blurry autoencoder's output already resembles the local mean.

Research Program

The model has two parts. The first is a shallow feature extractor at full resolution, with a small known receptive field of radius $\rho$ (a few factorized $3\times3$ layers). The second is a set of ring heads. Each ring head aggregates those features only at offsets far enough from the target pixel $p$ that no contributing feature's receptive field enters a central square of half-width $c$.

Ring heads with hole sizes $c \in \{2, 4, 8, 16\}$ pixels share the extractor. Each one is a sparse dilated convolution whose taps are dense enough around the ring to avoid gridding. Gridding is the failure noted by Fully Convolutional Neural Network with Augmented Atrous Spatial Pyramid Pool and analyzed as aliasing in Frequency-Adaptive Dilated Convolution for Semantic Segmentation. That analysis acts as a constraint on our design: rings sampled too sparsely skip exactly the thin structures we care about. The ring idea itself extends dilated-convolution inpainting, as in Learning to Inpaint for Image Compression, which predicts missing content from dilated context. We apply that predictor to every pixel at once rather than to a fixed missing region.

Each head predicts a mean and a variance for the hidden pixel and is trained on normal images with a Gaussian negative log-likelihood. The variance term lets the model admit uncertainty in naturally variable areas, such as cable strands, rather than flagging them. The anomaly score at pixel $p$ is

$$s(p) = \max_{c} \frac{\big(x_p - \hat{\mu}_c(p)\big)^2}{\hat{\sigma}^2_c(p)},$$

where $x_p$ is the observed value, and $\hat{\mu}_c(p)$ and $\hat{\sigma}^2_c(p)$ are the mean and variance predicted by the head with hole size $c$. Taking the maximum over hole sizes lets the smallest hole that fully hides a defect determine the score. Holes too small for a given defect partly see it and mostly reproduce it, which lowers their score, so the maximum ignores them. Holes larger than needed give blurrier predictions, but their predicted variance is also larger, which tempers their score.

The hardest engineering question is how much context the predictor needs. Large holes need long-range context to predict object structure, such as screw threads or transistor leads, and this is where we use multi-scale aggregation. We borrow the idea from Rethinking Dilated Convolution for Real-time Semantic Segmentation (RegSeg): place parallel dilated branches inside the backbone instead of a heavy pyramid head. RegSeg also supplies the gridding rule $r \le k/s$ (dilation rate $r$, kernel size $k$, stride $s$). We additionally use the channel-wise dilation pyramid of CFPNet: Channel-wise Feature Pyramid for Real-Time Semantic Segmentation, which keeps the parameter count in the sub-million range. Both papers supply method but were designed for supervised street-scene segmentation. Neither has a hole constraint, and the hole constraint is the new ingredient here.

The analysis has three parts. The first is a capacity sweep that reproduces the protocol of On the Pitfalls of Using the Residual Error as Anomaly Score for both a standard autoencoder and our predictor. The second stratifies localization quality by annotated defect area on MVTec AD. The third is a latency study at native resolution with batch size 1.

Baselines

The naive reference point is a convolutional autoencoder trained with an SSIM loss. This is the setup MVTec AD found better than an $\ell_2$ loss. We match its parameter count and training schedule to ours, and we tune both on the same held-out normal images. Our method should beat it in pixel-level average precision in every defect-size bin. If it does not, the hole constraint adds nothing.

The strongest existing competitor is FastFlow, a normalizing flow (a density model) placed on pretrained features. It is the strongest because it is both accurate and fast. Benchmarking Unsupervised Anomaly Detection and Localization reports 99.4% image-level AUROC and 98.6% pixel-level AUROC on MVTec AD at 21.8 FPS on a GTX 1080Ti. We also report ReConPatch, which ReConPatch describes as reaching 99.72% on MVTec AD and 95.8% on BTAD. We will rerun FastFlow, PatchCore and ReConPatch from their public settings on the same GPU, at the same input resolution, with batch size 1.

Image-level AUROC on MVTec AD is nearly saturated, so we do not expect to win there. Beating these methods means one of two outcomes. The first is higher pixel-level AP or per-region overlap on defects below roughly $16\times16$ pixels, at equal or lower latency. The second is matching their overall pixel AUROC while running at least twice as fast at native resolution. These feature-based methods inherit downsampling from their backbones, which is the mechanism by which Preserving Tiny Features Against Spatial Resolution Degradation says tiny features are lost.

Among reconstruction methods with capacity control, we compare against OCR-GAN, which splits images into frequency bands and trains against synthetic forgeries. Omni-frequency Channel-selection Representations for Unsupervised Anomaly Detection reports 98.3 AUC on MVTec AD and 99.3 AUC on DAGM. It reports no KolektorSDD number in our file. We also compare against PVQAE from Patch-aware Vector Quantized Codebook Learning, for which we found no reported result on Lacuna for MVTec AD, BTAD or MTSD. We will rerun it and report both accuracy and latency.

Two ablations isolate the key ingredient. The first removes the hole while keeping the identical architecture, so each pixel's own neighborhood is visible. The second replaces the hole with a full-resolution memory bottleneck in the style of Memorizing Normality to Detect Anomaly. This is the "obvious" combination of a dilated real-time backbone with prototype memory, and it tests whether structural exclusion beats capacity restriction at the same speed.

Why not just…?

Why not just use PatchCore or FastFlow, which already work? This is the real threat. On the overall MVTec AD numbers above, we may lose. Our bet is narrower: methods built on pretrained backbones score at a coarse feature stride, so they blur sub-stride defects. Nearest-neighbor variants can also be slow; the same benchmark reports 0.67 FPS for SPADE. The defect-size-stratified evaluation settles this question. If FastFlow matches us on the smallest-defect bin at equal latency, the proposal's main motivation fails, and we will report that outcome.

Why not just train an inpainting autoencoder with random masks and run several masked passes at test time? Functionally this is the same idea, and it is the closest relative. Covering every pixel, however, requires many passes per image, which multiplies latency. Our single-pass ring heads should give the same scores. We will build this as a baseline with a matched architecture and compare quality per millisecond. If it is equally accurate at an affordable number of passes, our contribution reduces to an efficiency trick, and we will describe it as one.

Why not just shrink the autoencoder until it stops copying defects? The Pitfalls paper shows the bind this creates. Less capacity means worse reconstruction of normal regions, and those normal errors swamp the defect signal. The capacity sweep tests our claim directly: our curve should rise with capacity while the standard autoencoder's falls.

Why not just add a memory bank, as MemAE does? Memory lookup is cheap. MemAE reports about 0.0004 s of overhead per frame, yet it gains only from 0.697 to 0.712 AUC over a plain autoencoder on ShanghaiTech. It also requires tuning the shrinkage threshold and the number of memory slots. The memory ablation, run at the same resolution and speed, tests whether memory adds anything beyond the hole.

Proposed Experiments

Training uses only normal images from MVTec AD, BTAD, MTSD, DAGM and KolektorSDD. MTSD and KolektorSDD contain thin cracks, which suit the method.

Metrics are image AUROC, pixel AUROC, pixel AP and per-region overlap. MVTec AD defects are additionally binned by annotated area. Latency is measured at native resolution with batch size 1 on a single T4-class GPU. For reference, RegSeg reports 37 FPS on a T4 for a 3.34M-parameter segmentation network. We target under 33 ms per frame.

For the blind-spot question, we follow the MOOD synthetic-intensity protocol of the Pitfalls paper and sweep anomaly intensity across the 0.2–0.6 range. We expect our predictor to recover average precision for texture anomalies such as pixel shuffling, and to fail, like everything else, on anomalies matching in both intensity and texture.

Three decisive checks determine the outcome. The method fails if removing the hole does not degrade small-defect AP. It fails if the capacity sweep shows the same downward trend as a standard autoencoder. And it fails if FastFlow equals it on the smallest defect bin at equal latency.