Some original image labels are retained; figure captions and explanations are provided in English.

PART V: DEEP LEARNING

What Is Anomaly Detection? Autoencoders, PaDiM, and PatchCore

Reconstruction- and feature-based methods are compared for tasks with limited defect examples. PaDiM and PatchCore illustrate score and map generation, memory costs and image- versus pixel-level metrics. A change in lighting between shifts shows how normal variation can trigger alarms, leading into the conversion of anomaly maps into production decisions.

Article sectionsWhat is image anomaly detection?How does it differ from supervised classification?The principle behind reconstruction-based methodsWhy does DRAEM offer a different approach?How does PaDiM work?How does PatchCore work?PaDiM or PatchCore?How should we read an anomaly map?What do MVTec AD and MVTec AD 2 tell us?The difference between image AUROC and pixel AUROCDistinguishing natural variation from defectsWhen is anomaly detection unsuitable?Numerical example: why is 99% detection not enough?Acceptance checks before production deploymentHow can a normal dataset become representative?Calibrating the anomaly scoreThe localization accuracy of an anomaly mapMemory and search costs at high resolutionWhy are hard negative examples valuable?Drift and controlled retraining in productionFrequently asked questionsImage sources

Learning from normal examples, reconstruction-based and feature-based anomaly detection; PaDiM, PatchCore, DRAEM, and error maps. This guide examines the assumptions behind these methods, the conditions in which they can be used, reasons for failure, and practical decision points in deployment.

What is image anomaly detection?

Short answer: Visual anomaly detection attempts to flag regions or images that fall outside the appearance learned from normal examples. It is an appealing approach in production environments where collecting hundreds of labeled examples of every defect class is not feasible. However, not everything that is 'different from normal' is a product defect. Camera movement, lighting changes, a new supplier, legitimate surface texture, or a dirty protective window can also produce an anomaly score.

Three distinct outputs should be considered separately in anomaly detection: an anomaly score for the entire image, a pixel-level anomaly map, and the final quality decision. The first two may be model outputs; the third generally incorporates operational criteria, thresholding, and human review. Applications that fail to make this distinction may achieve high benchmark scores yet produce many false rejects in deployment.

Learning from normal examplesExamples outside the reference distribution are flaggednormalfeaturesdistancescoreConceptual technical diagram: not an architectural drawing to scale
Original diagram: Examples outside the reference distribution are flagged

How does it differ from supervised classification?

A supervised classifier learns from labels such as 'scratch,' 'dent,' or 'stain.' An anomaly detection method can work with normal images alone or with predominantly normal data. This creates the potential to detect a previously unseen defect. However, there is no inherent guarantee that every new defect will be noticed. A defect may be missed if it resembles a pattern that the model treats as normal variation.

Anomaly detection is particularly strong when normal data is abundant, defective examples are scarce, and the range of possible defects is open-ended. Conversely, for a few well-defined, well-labeled critical defects, a supervised detector or segmentation model may offer greater control. The two methods do not have to compete: anomaly screening can monitor unknown conditions while a supervised model monitors known critical defects.

The principle behind reconstruction-based methods

An autoencoder converts its input into a compressed representation and attempts to reconstruct it. When trained on normal images, it is expected to reproduce normal patterns more accurately and leave larger differences in anomalous regions. The absolute difference between the input and reconstructed image, or a difference in perceptual features, can be converted into an anomaly map. The idea is simple and intuitive, but reliable operation depends on its assumptions holding.

A high-capacity autoencoder may also reconstruct an anomalous example well. In that case, the difference becomes small and the defect may be missed. Conversely, if a normal reflection or fine texture detail is reconstructed poorly, a false alarm occurs. Reconstruction error is therefore not a direct probability of a physical defect.

ReconstructionReconstruction error may provide a clue to an anomalyimageencoderdecoderdifferenceConceptual technical diagram: not an architectural drawing to scale
Original diagram: Reconstruction error may provide a clue to an anomaly

Why does DRAEM offer a different approach?

DRAEM is one of the methods that combine reconstruction and discrimination tasks by generating synthetic anomalies from normal images. The aim is for synthetic defects to help the model learn features sensitive to anomalous regions. However, the visual distribution of artificial anomalies may not represent real cracks, bubbles, or coating defects. The gap between synthetic texture and real defects affects the method's generalization limits.

When evaluating methods of this kind, how the artificial anomaly is generated is a critical question. Generating scratches at random angles in every direction may not be physically meaningful if real scratches can occur only in a particular direction. If a defect is supposed to alter the surface's light reflection or topography, simply drawing a line over the pixels is not a realistic synthesis.

Real CC0 texture photograph: normal appearance.
Real photograph / transformation: Real CC0 texture photograph: normal appearance.

How does PaDiM work?

PaDiM is known for statistically modeling the distributions of normal features at spatial locations in feature maps extracted from a pretrained network. Statistics such as the mean and covariance can be calculated from normal features at corresponding locations. The extent to which a region in a new image deviates from this normal distribution can be assessed using, for example, the Mahalanobis distance.

This assumption fits more naturally when objects in the images are aligned in a comparable way. If a product constantly changes position within the camera frame, different physical surfaces are compared at the same coordinates. In that case, ROI alignment or pose control is needed first. Covariance estimation may also require attention to numerical stability when features are high-dimensional and the number of examples is limited.

How does PatchCore work?

PatchCore uses a memory bank of representations of local features extracted from normal images. During testing, an anomaly score can be calculated from the distance between new patch features and normal examples in the bank. Approaches such as coreset selection can reduce the size of this representation bank, so not every normal patch needs to be retained in memory.

The approach's success depends on how well the pretrained features represent the industrial texture in question and how fully the memory bank captures normal diversity. An overly narrow normal dataset may cause even a normal surface variation to be treated as an anomaly. Conversely, an excessively diverse or improperly cleaned normal bank may include examples close to real defects, reducing sensitivity. Memory size, search speed, and the number of patches at high resolution introduce separate engineering costs.

PaDiM and PatchCoreRegional statistics and representation memoryfeaturesstatisticsmemorydistanceConceptual technical diagram: not an architectural drawing to scale
Original diagram: Regional statistics and representation memory

PaDiM or PatchCore?

There is no universal answer to this question. PaDiM's regional distribution approach and PatchCore's neighboring-feature search rely on different assumptions. Statistical modeling may be useful for aligned images, while a representation bank may offer different advantages when local diversity is high. Both methods should be evaluated on test photographs covering different lighting, camera, and supplier conditions.

Aspect PaDiM PatchCore
Representation of normality Location-specific feature distribution Memory bank of local feature examples
Test score Distance from the distribution Distance to the nearest normal feature
Memory characteristics Statistics and covariances Memory bank and search structure
Critical assumption Spatial comparability Normal diversity in the representation bank
Deployment risk Alignment and distribution shift Memory size and search cost

Although methods may appear comparable when each uses a different image resolution, backbone, or data preparation pipeline, the results may not be fair. Equivalent experimental conditions must be established first. Resource consumption is especially decisive on edge devices with limited GPU memory.

How should we read an anomaly map?

Warm-colored regions in an anomaly map generally represent high anomaly scores. However, colors are often normalized separately for each image. A score displayed in red in one photograph cannot be assumed to have the same numerical meaning as red in another. Visual comparisons require a shared color scale and threshold.

A threshold is selected when converting an anomaly map into a binary mask. Lowering it too far may detect small defects but also trigger alarms on normal texture. Raising it may reduce false alarms but miss a small critical defect. The threshold used for production acceptance decisions should be determined using independent validation data and the relevant costs. Tuning the threshold on test data contaminates the evaluation.

Anomaly mapA heatmap and a pixel mask are not the same thingmapthresholdmaskdecisionConceptual technical diagram: not an architectural drawing to scale
Original diagram: A heatmap and a pixel mask are not the same thing
Gradient map calculated from the original photograph; not a PatchCore output.
Real photograph / transformation: Gradient map calculated from the original photograph; not a PatchCore output.

What do MVTec AD and MVTec AD 2 tell us?

MVTec AD is an industrial anomaly detection dataset that combines normal training images with defective and defect-free test images across various object and texture categories. Pixel-level defect masks enable localization comparisons. However, a high score on MVTec AD alone does not guarantee a system that will work on every production line.

MVTec AD 2 includes more challenging industrial scenarios and lighting changes that may not appear in training. Some test labels are reserved for a dedicated evaluation server. This design helps measure performance under conditions closer to real distribution shifts. Both datasets have licenses that restrict commercial use, so permissions and license terms must be considered when reusing their images in a blog.

The difference between image AUROC and pixel AUROC

Image AUROC measures the score ranking of normal and anomalous examples at image level, while pixel AUROC measures the discriminative power of pixel scores. These address different questions. A system can correctly identify a photograph as anomalous while indicating the wrong defect location. Conversely, a system that accurately localizes a small defect may have a poorly chosen image-level decision threshold.

AUROC is a threshold-independent ranking metric; it does not directly tell you how many false alarms and missed defects will occur at the single threshold chosen for production. With highly imbalanced pixel classes, a high pixel AUROC can hide operational failures on small defects. Region-focused metrics such as PRO and recall at a fixed false alarm rate are therefore valuable additional evaluations.

EvaluationImage AUROC, pixel AUROC, and production alarms are distinctimagepixeleventcostConceptual technical diagram: not an architectural drawing to scale
Original diagram: Image AUROC, pixel AUROC, and production alarms are distinct

Distinguishing natural variation from defects

Lathe marks on a metal surface, texture that varies by manufacturer, and light reflections may all be normal variation. If the model has seen these only in particular training batches, it may flag a new batch as defective. The acceptance region in image space must reflect the actual diversity of normal appearance, not merely a 'normal' label. A good data collection plan covers shifts, material batches, tool wear, and lighting conditions after maintenance.

Contamination of normal training data is another major problem in anomaly detection. If unnoticed small defects are added to the normal bank, the model's definition of expected normality expands. The opposite problem is excluding rare but normal variations from training, which causes excessive rejects. Expert review and data sampling standards are as decisive as the technical model itself.

Domain shiftLighting changes must be distinguished from defectstrainlightingshiftfalse alertConceptual technical diagram: not an architectural drawing to scale
Original diagram: Lighting changes must be distinguished from defects
Version with artificial noise added to a real texture; not a defect captured in the photograph.
Real photograph / transformation: Version with artificial noise added to a real texture; not a defect captured in the photograph.

When is anomaly detection unsuitable?

If a production line has many labeled defect examples of a single critical crack type, a dedicated defect detector may be better suited to the objective. An anomaly detection method may unnecessarily flag noncritical surface variations. Logical defects such as a missing screw or a misplaced label may also look normal in terms of local texture. In such cases, rules for position, count, and relationships between parts may be needed.

If production conditions change very quickly, continually readjusting an anomaly model is also costly. Engineering and quality teams must clearly define the boundaries of accepted normality. The assumption that 'the model finds everything unknown' is particularly dangerous for this task.

Numerical example: why is 99% detection not enough?

Suppose a production line has a true defect rate of 0.5%, an anomaly detection rate of 99%, and a false alarm rate of 3% on good parts. Among 100,000 products, there are approximately 500 defects. About 495 are correctly flagged, while five may be missed. Of the 99,500 good products, approximately 2,985 trigger false alarms. Only about 14% of the 3,480 total alarms correspond to real defects. The operator team may have to perform thousands of unnecessary inspections.

This result alone does not mean the method has failed. The workload may be acceptable if the cost of a missed defect is extremely high. However, the calculation illustrates the link between the threshold and system capacity. An attractive anomaly map does not mean that alarm handling is operationally viable on the line.

Operational precision simulator

Adjust the defect rate and false alarm rate for a hypothetical shift of 10,000 parts. This calculation is not model training.

Probability that an alarm corresponds to a real defect: —

Total alarms: —

Acceptance checks before production deployment

Different normal product variants, different lighting conditions, and real defects should be tested in separate subsets. The reference normal data should be checked for contamination, the source of each alarm investigated, and optical variables outside the model recorded. The decision threshold should be based on acceptance criteria, not a single benchmark score. Human review for uncertain examples and a data feedback loop should also be defined.

When the model is retrained, its effect on previously accepted batches should be compared. Good performance on new data alone is not enough; it is also necessary to check whether the new model narrows the previously accepted boundaries of normal variation. A rollback strategy should be available when needed.

How can a normal dataset become representative?

An anomaly model can fail even with thousands of normal production images if they lack diversity. A thousand images of the same product captured within the same minute may contain less information than a hundred images captured across different shifts, material batches, and lighting conditions. Anomaly detection learns the visual boundaries of 'normal.' Those boundaries must encompass real production diversity.

The data collection plan should record variables such as product variant, camera ID, lighting parameters, supplier batch, tool wear, and production date. Deliberately collecting rare but acceptable normal examples can reduce false alarms. During data cleaning, however, real defects must not be added to the bank as 'normal variation.' These two needs must be managed together.

Even when defect labels are scarce, a quality expert's review of examples provides a valuable check. Random and suspicious examples can be selected from the training bank for review. A powerful anomaly model cannot automatically correct an incorrect normal label; it attempts to represent the distribution it saw during training.

Calibrating the anomaly score

In most anomaly detection methods, the score is a distance or reconstruction difference rather than a probability. It can be interpreted as distance from a distribution in PaDiM, or distance to the nearest normal feature in PatchCore. Score scales from different model versions may not be comparable. A score of 0.7 may indicate a strong anomaly in one model but be normal in another.

Threshold selection should be performed on validation data. An acceptable false alarm rate can be defined for normal images; if real defect examples are available, detection performance at that operating point can then be examined. An elevated anomaly score on an example outside the training data may also be caused by a lighting change. Rather than initiating retraining after a single alarm, collecting several examples under the same conditions and examining physical causes may be more reliable.

How scores are aggregated at image level matters. Using the highest pixel score is sensitive to a single noisy point, while an average score can suppress a small defect. Options such as the top 1% of scores, region area, or the maximum score within a critical ROI can be considered. The balance between false alarms and missed defects for each option should be evaluated against production metrics.

The localization accuracy of an anomaly map

An anomaly map may produce a warm-colored region around a defect without accurately covering its true boundary. Some backbone features have low spatial resolution, and boundaries may blur during upsampling. Using the map directly to measure the physical defect area is therefore risky. Pixel-level and boundary-level validation is needed first.

If the true areas of defective regions are known, pixel recall and the false-positive rate can be examined at different thresholds. The miss rate for very small defects should also be reported separately. It is possible to achieve a high average pixel AUROC while missing very fine cracks. The importance of critical production defects must be reflected in the evaluation protocol.

The meaning of red in the map should be documented. Maps automatically normalized per image can look visually impressive but make it difficult to compare scores across images. A common scale and an explicitly documented threshold are more appropriate for a technical report.

Memory and search costs at high resolution

In methods such as PatchCore, retaining normal features in memory can increase resource consumption as the data grows. A high-resolution photograph produces many patch representations. Storing all of these features may be unnecessary; a coreset or sample selection strategy can reduce memory requirements. However, aggressive reduction may leave rare normal variations unrepresented in memory.

Nearest-neighbor search performs differently on CPUs and GPUs. An operation that is fast on a desktop may incur delays on an edge device. Feature vector dimensionality, memory layout, the number of patches per image, and the search infrastructure must be planned together. A method that 'requires no training' should not be assumed to have no inference cost.

For PaDiM, feature dimensionality and the numerical stability of covariance matrices are important. High-dimensional covariance may not be reliably estimated from a small number of normal examples; regularization or dimensionality reduction may be required. These technical choices can affect the model's sensitivity to anomalies.

Why are hard negative examples valuable?

Reflections, machining marks, or surface textures that look like defects but remain within quality limits are valuable hard negatives for an anomaly model. While these examples expand the definition of normality, they can also blur the boundary with real defects. Rather than adding them all unquestioningly to the normal pool, they should be classified according to the quality policy.

For example, if a bright spot moves when the camera angle changes, it is likely a reflection. A real surface defect remains fixed on the physical part. Capturing the same part under a different lighting angle can provide a simple yet powerful check before involving a learning model. Planning such contrasting conditions in the data design can be more effective than changing the algorithm.

False alarm analysis should include not just the model score but also the physical region where the apparent defect appears. If every false alarm in a particular region is caused by reflections from the mold, adjusting the ROI, optical geometry, or lighting may be sufficient.

Drift and controlled retraining in production

Over time, the anomaly score distribution may shift as new part variants appear, tools wear, or the camera position changes. Drift monitoring should examine the conditions under which shifts occur, not just the mean score. A sudden deterioration in image quality and a genuine deterioration in product quality require different interventions.

Retraining carries the risk of expanding the model's normal distribution and normalizing real defects. New normal data should therefore undergo expert review, followed by retesting on a fixed acceptance set of previously observed critical defects. A new model should not automatically be considered successful simply because it produces fewer alarms; the number of missed defects may have increased.

When comparing model versions, it is useful to rerun recorded examples captured under the same lighting and camera conditions. Rollback and traceability are fundamental maintenance requirements for an anomaly detection system. They make production changes diagnosable even when the algorithm is not their cause.

Advanced engineering considerations for deployment

Is the normal data truly normal?

One of the most common misconceptions in anomaly detection is assuming that every image placed in the good-parts folder is defect-free. Even a small number of undetected defects in the training data can cause defects to enter the normal representation memory, especially with memory-bank approaches. It is important to recheck operator decisions, keep borderline examples separate, and sample from different production batches. Collecting only 'defect-free' images must not restrict diversity, either: acceptable surface textures, tonal differences, and machining marks should be represented in the normal distribution. Otherwise, the model detects natural production diversity rather than defects.

Turning an anomaly map into a production decision

Methods such as PaDiM and PatchCore often produce a score and a spatial map for an image. In production, however, the required output may be 'accept part' or 'reject part.' Using the maximum pixel score is sensitive to small, random highlights, while an average score can suppress small but critical scratches. Connected components exceeding a specified minimum area, regional thresholds, or rules based on part geometry may be more appropriate. The decision rule should be defined alongside the critical defect types and fixed for independent testing. Finding a map visually convincing does not prove the measurement result is correct.

The gap between benchmarks and deployment

Although datasets such as MVTec AD are valuable for comparative research, the ranking of models by image AUROC on a single dataset may not match their ranking in deployment. Lighting, camera angle, batch, surface treatment, and operator interventions vary on a production line. The more challenging imaging conditions and lighting changes in MVTec AD 2 are a reminder that this gap matters. Benchmark performance can serve as an initial signal when selecting a method; the main decision should be based on independent testing that includes deployment data from different days and batches. The commercial use terms of the datasets must also be checked separately.

Memory and inference costs

In memory-bank systems such as PatchCore, the number of stored representations can affect speed and memory requirements. More normal examples do not always produce better decisions; redundant representations may increase computation without providing benefit. Approaches such as coreset selection aim to reduce memory size while preserving representation diversity. For methods that model distributions, such as PaDiM, feature dimensionality and covariance calculations become important. Nearest-neighbor search that is fast on a GPU may perform differently on the target edge hardware. When choosing an anomaly detection method, the per-example memory and latency profile should therefore be reported alongside AUROC.

Application scenario: detecting lighting changes instead of scratches

Suppose a system trained on normal examples considers the same metal part good during the day shift but anomalous during the night shift. The cause may be light intensity or surface reflection rather than real damage. Diagnosis begins by separating score distributions by shift and camera. Before new images are automatically added to the normal memory bank, any physical change in lighting is measured. Mistakenly learning this kind of shift may reduce sensitivity to critical defects.

Field test checklist

  • Is it documented which tests were kept independent by product, shift, and image capture conditions?
  • Have failures that can be corrected by the algorithm alone been distinguished from those requiring optical or process changes?
  • Has it been verified that the model score does not replace the physical acceptance criterion?
  • Are input resolution, model version, threshold, and runtime hardware fixed in the experimental records?
  • Are illustrative visuals clearly distinguished from actual measured model results?
  • Are false rejects, missed defects, latency, and reinspection workload reported separately?

Frequently asked questions

Are defective examples needed for anomaly detection?

Some methods can start with normal training data alone. However, defective examples are extremely valuable for threshold selection and reliable evaluation. There is no guarantee of detecting every defect without having seen defects.

Can PatchCore show the location of a scratch?

It can generate an anomaly map from local feature distances. How well the map overlaps the actual scratch boundary must be measured separately.

Why can an autoencoder reconstruct an anomalous image well?

A high-capacity model can also reproduce some anomalous structures. In that case, the reconstruction difference remains small and a defect may be missed.

What is the difference between MVTec AD and MVTec AD 2?

AD 2 places greater emphasis on more challenging imaging scenarios and lighting changes that may not be present in training. Dataset licenses must also be checked separately.

Is an anomaly score the probability of a real defect?

Generally, no. The score measures distance from the normal representation; without calibration and field validation, it should not be treated as the probability of a physical defect.

References and image provenance

Technical references and original publications are listed below. The photographs used in the visual examples are genuine CC0/public-domain images; transformations made for comparison are explained. The diagrams are original designs. Illustrative examples are not presented as the performance of a trained model.

  1. https://www.mvtec.com/research-teaching/datasets/mvtec-ad
  2. https://www.mvtec.com/research-teaching/datasets/mvtec-ad-2
  3. https://arxiv.org/abs/2106.08265
  4. https://arxiv.org/abs/2011.08785
  5. scikit-image example data: source photographs and reuse notes

Image sources and illustration disclaimer

The sample photographs come from the scikit-image example data collection. Added boxes, masks, synthetic defects, and heatmaps are illustrations explaining the concepts; they are not outputs of a trained model or validated performance results. The technical diagrams are original drawings included in the package.

Source and usage notes for the sample images