---
title: "The MVTec Anomaly Detection Dataset: A Comprehensive"
description: "The MVTec AD paper introduces an industrial defect dataset and tests how well methods locate damage after learning from defect-free images."
canonical: "https://research.elamur.ai/free/en/papers/bergmann-2021-mvtec-anomaly-detection-dataset-comprehensive/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/) · [Constitution](https://md.constitution.elamur.ai/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/bergmann-2021-mvtec-anomaly-detection-dataset-comprehensive/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2021](https://md.research.elamur.ai/free/en/papers/2021/) / The MVTec Anomaly Detection Dataset: A Comprehensive Real-World Dataset for Unsupervised Anomaly Detection

# The MVTec Anomaly Detection Dataset: A Comprehensive Real-World Dataset for Unsupervised Anomaly Detection

Paper · 2021 · Paul Bergmann, Kilian Batzner, Michael Fauser et al.

**Authors:** Paul Bergmann, [Kilian Batzner](https://md.research.elamur.ai/free/en/authors/kilian-batzner/), Michael Fauser, David Sattlegger and Carsten T. Steger · **Year:** 2021 · **Venue:** International Journal of Computer Vision · **Licence:** [CC BY (OpenAlex best open-access location)](https://creativecommons.org/licenses/by/4.0/)

[Cited by **8** papers in our library of more than 163,000 papers whose bibliographies we read](https://md.research.elamur.ai/free/en/papers/bergmann-2021-mvtec-anomaly-detection-dataset-comprehensive/cited-by/) · International Journal of Computer Vision · [licence](https://creativecommons.org/licenses/by/4.0/)

- [PDF](https://link.springer.com/content/pdf/10.1007/s11263-020-01400-4.pdf)
- [DOI 10.1007/s11263-020-01400-4](https://doi.org/10.1007/s11263-020-01400-4)

## Summary

A part can look almost identical to a good one and still have a defect that matters. A scratch may occupy a small patch of a surface, or a component may be absent from an otherwise familiar object. Detecting these faults is especially difficult when an inspection system can learn only from examples of acceptable products. The MVTec Anomaly Detection dataset, or MVTec AD, gives researchers a way to test whether such a system can recognize a defect and show where it is.

The dataset contains 5354 high-resolution images across 15 categories of objects and textures. Its 3629 training images are all defect-free. Its 1725 test images include both good and defective samples. The authors created 73 kinds of defects on physical samples to represent faults that might occur in industrial inspection. They also marked the affected pixels, providing 1888 annotated regions. The masks make it possible to check whether a method found the actual defect, even when it flagged the image for the wrong reason.

The benchmark compares methods that reconstruct a normal-looking image, methods that use visual features learned on ImageNet, and classical inspection techniques. Student–Teacher, which learns to reproduce a pretrained network’s responses on good samples, leads the category-averaged comparisons. Its mean area under the precision–recall curve is 0.599, followed by 0.466 for the Feature Dictionary, which also uses pretrained features. Methods that learn to reconstruct the training images from scratch generally do worse. Even the leading approach can miss a missing transistor leg, a defect whose significance depends on the surrounding object.

The paper also shows how the scoring rules change what the benchmark reveals. A pixel-based measure gives a large defect more influence than a small one, whereas per-region overlap gives each connected defect the same weight. Restricting the evaluation to low false-positive rates changes the ranking of some methods. And a strong score across many thresholds gives no automatic way to choose the threshold an inspection system will actually use. When the authors derive thresholds from clean validation images, conservative choices sometimes miss every defect, while more permissive choices can flag too much of the image.

## Deep dive: The MVTec Anomaly Detection Dataset: A Comprehensive Real-World Dataset for Unsupervised Anomaly Detection

The MVTec AD paper introduces an industrial defect dataset and tests how well methods locate damage after learning from defect-free images. · about 37 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### Learning from the parts that pass inspection

In the industrial setting the authors want to represent, the easiest examples to collect are usually the good ones. A manufacturing process is designed to produce acceptable parts, so samples showing any particular fault may be scarce. The set of faults that will occur in the future may also be unknown when the system is trained. This makes the ordinary supervised recipe awkward. A collection of labeled examples for each known failure would still leave open what to do about a failure absent from that collection.

The paper studies a different use of [machine learning](https://md.research.elamur.ai/free/en/concepts/machine-learning/). During training, a detector sees acceptable instances of a product or material. At test time, it must decide whether an instance departs from what it learned, and the benchmark asks it to locate that departure. An image of a good hazelnut can show natural variation, for example, while a good rigid object can appear at a different angle. An inspection method needs to accommodate changes of that kind and still respond to damage. The meaning of an unusual appearance depends on how the object can legitimately vary.

The authors use *novelty detection* for a related task in which whole images come from substantially different distributions. A system might learn from some categories of a classification dataset and then be asked to recognize that an image from another category lies outside its experience. *Anomaly detection*, in the paper’s narrower sense, can concern a much smaller departure. Most of the test image can agree with what the system learned, leaving a local irregularity as the only significant evidence. A method that excels when the unfamiliar content takes up much of an image may face a different problem when the suspicious evidence is a dent or a short scratch.

Localization makes this distinction observable. An image-level decision tells the evaluator whether the detector raised an alarm. With a pixel mask, the evaluator can also ask what the detector responded to. A high score on a reflection or an object boundary could cause a defective item to be flagged even if the method overlooked the fault. That outcome might look like a success in image classification, while the spatial prediction shows that the signal the detector found does not match the defect. The paper treats this distinction as central to evaluating inspection methods.

#### Why existing datasets left a gap

One established evaluation design starts with class labels already available in datasets such as MNIST, CIFAR10, or ImageNet. Researchers designate some classes as unfamiliar and train on the others. Another design trains on one collection and takes unfamiliar test examples from another. Both designs give researchers labeled examples at scale. The authors’ concern is that separating categories or collections can make the difference between familiar and unfamiliar images broad, whereas an inspection system must often detect a small change within a familiar category. The paper cites the convolutional image-classification work associated with ImageNet. [ImageNet classification](https://md.research.elamur.ai/free/en/papers/krizhevsky-2012-imagenet-classification-deep-convolutional/)

The work by Saleh and colleagues moves toward a more specific comparison by using objects with unusually shaped forms. Its abnormal examples include objects whose ordinary counterparts belong to the same category. An evaluator can therefore ask whether a detector recognizes an atypical car or aircraft. The labels still concern whole images. A system’s decision offers no direct basis for assessing which portion of the outline or which part of the object gave it away.

Several previous resources make spatial evaluation possible for surfaces. NanoTWICE shows a nanofibrous material imaged with a scanning electron microscope. It has 45 grayscale images, of which five are clean training examples. The annotated irregularities include dust and flattened areas. This gives researchers a focused surface-inspection problem and leaves open whether success carries over to materials with very different textures. A dataset of magnetic tiles covers 1344 grayscale images and provides pixel-level labels for its faults. The steel-surface collection discussed in the paper covers 1800 grayscale images and uses bounding boxes. A box can identify the approximate position of a narrow scratch while leaving a large portion of normal surface inside the label.

The artificially generated texture collection discussed by the authors offers ten classes and supplies training and test patches for each class. Its elliptical labels describe the approximate extent of a defect, and the texture-generation procedures give the classes similar appearances. Synthetic surfaces are useful for making examples available, but their range of variation and the precision of their labels depend on how the images were constructed. The authors wanted a benchmark in which the input was a photograph of a physical sample and the affected area could be outlined in detail.

Fishyscapes and the CAOS benchmark provide another form of spatial evaluation. In the paper’s account, these driving-scene benchmarks ask systems to identify unfamiliar objects within images that already contain multiple semantic classes. Fishyscapes inserts images of novel objects into scenes from Cityscapes. CAOS includes rendered driving scenes with foreign objects and a collection built by holding out selected classes from driving data. These tasks can require precise localization, as industrial inspection does. They ask a different question about what counts as unusual. A missing feature on a familiar object does not have to look like a new object category.

#### What earlier detectors tried to learn

Reconstruction methods learn what acceptable examples look like and use that knowledge to recreate a test input. If the reconstruction preserves the good structure and loses an unfamiliar detail, comparing the input and output can reveal where the detail was. This can work only when the reconstruction is faithful on the ordinary parts of the image and sufficiently different in the faulty parts. Those are separate requirements. An accurate reconstruction of a defect can make it hard to detect, and a poor reconstruction of a good edge can produce a conspicuous false alarm.

Earlier adversarial methods train a generator and a discriminator together. The generator learns to produce images that the discriminator will accept as resembling examples from training. One approach described by the paper searches at test time for a latent input that lets the generator reproduce the image being inspected. A later version trains an encoder to estimate that latent input directly, avoiding a fresh numerical search for each test case. The paper traces the underlying generative approach to the work on [Generative adversarial nets](https://md.research.elamur.ai/free/en/papers/goodfellow-2014-generative-adversarial-nets/).

Convolutional autoencoders learn to compress and reconstruct clean examples in a single architecture. The paper discusses earlier work that compares neighborhoods through structural similarity, a way of assessing how local image structure changes between an input and its reconstruction. It also describes variants that augment an autoencoder with a memory or learn a probability distribution over its compressed representation. The authors cite evidence that the latter approach had yielded little improvement over standard autoencoders in the applications they discuss, as well as research questioning whether likelihoods from deep generative systems reliably identify unfamiliar inputs. Their benchmark uses deterministic autoencoders. [Memory-augmented autoencoder for anomaly detection](https://md.research.elamur.ai/free/en/papers/gong-2019-memorizing-normality-detect-anomaly-memory/) · [Auto-Encoding Variational Bayes](https://md.research.elamur.ai/free/en/papers/kingma-2013-auto-encoding-variational-bayes/)

A different approach starts with a network that already describes images and learns which of its responses are normal for the product at hand. The paper describes earlier uses of clustering to summarize features and a method that fits a Gaussian distribution to features extracted by a fully convolutional network. These designs face different restrictions. A compact cluster representation can miss uncommon normal appearances, while a single Gaussian can be too simple for a feature distribution with several forms of normal variation. The authors also discuss earlier work that uses a more flexible density estimator and their own preceding Student–Teacher approach. [Deep-anomaly](https://md.research.elamur.ai/free/en/papers/sabokrou-2018-deep-anomaly-fully-convolutional-neural/)

Classical inspection methods give the comparison another point of reference. One represents normal local texture through hand-designed measurements and learns the range of measurements expected on good surfaces. Another aligns clean objects to a common frame and estimates how far each location can vary from a reference appearance. The former can be applied without making each patch correspond to a particular position on a particular object. The latter can exploit that correspondence when it exists. By bringing both into the same benchmark as reconstruction and pretrained-feature approaches, the paper gives each family examples suited to its assumptions and examples on which those assumptions are strained.

### The method, step by step

#### Capturing and labeling physical samples

The authors chose categories that cover several kinds of visual variation. Carpet and grid are regular textures, while leather, tile, and wood provide less regular patterns. The object categories include rigid items with a relatively fixed appearance and items that vary across examples. A cable can deform, and a hazelnut can differ naturally from another hazelnut. Some objects were approximately aligned when photographed. Others, including metal nuts and screws, could appear at random rotations. This variety lets the same inspection protocol test methods that rely on exact positions and methods that learn the appearance of local neighborhoods.

The images were captured with a 2048 × 2048 pixel industrial RGB sensor. The setup used bilateral telecentric lenses with magnification factors of 1:5 and 1:1. The authors cropped the photographs to resolutions between 700 × 700 and 1024 × 1024 pixels. Grid, screw, and zipper are distributed in grayscale. Illumination was generally controlled, though the team intentionally varied it for some categories to broaden their appearance. Each dataset image represents a distinct physical sample. The dataset was assembled without padding it with different poses of an already photographed part.

The team made the faults by hand on the physical samples with industrial inspection in mind. These include marks and contamination on surfaces, changes in shape, and missing pieces. A specimen with a surface scratch can frequently be labeled by following the visible mark. A deformed or incomplete specimen calls for a rule about what the mask means. For a local deformation, the authors included both the deformed area and the place where that part should have been. For a missing piece, the mask covers its expected position. At uncertain borders, the annotators favored including ambiguous pixels in the defect. The authors reviewed the masks after labeling.

The result is a publicly available dataset in which the visual evidence is separated from its use in training. A detector fits its representation of acceptable appearance using good images. The experimenter uses the test masks to score the detector afterward. The benchmark reserves 10% of the defect-free training images in each category for validation, randomly selected and shared across methods. The validation images supply clean data for choosing thresholds. Test images include acceptable items as well as damaged ones, so test pixels away from a defect and pixels in completely clean images both matter when measuring false alarms.

From physical samples to scored defect masks The steps in order.

#### Producing scores by reconstruction

Fast AnoGAN, or f-AnoGAN, trains a generative adversarial network on clean patches and then trains an encoder to find the latent representation used for reconstruction. The benchmark uses the original authors’ public implementation. For each category, images from the training, validation, and test splits are resized to 256 × 256 pixels and converted to grayscale. The authors randomly draw 50,000 training patches of size 64 × 64 pixels. The generator uses a latent space of dimension 128 and produces images of size 64 × 64 pixels. The authors report that this configuration gave relatively stable training across the categories.

Adversarial training uses Adam for 100 epochs, starting with a learning rate of 10⁻⁴ and processing batches of 64. The encoder runs for 50,000 iterations with RMSProp, an initial learning rate of 5 × 10⁻⁵, and a batch size of 64. At test time, the method moves across the image with a stride of 64 pixels along each axis. A stride is the distance between successive patch positions. The input and generated patch are then compared pixel by pixel using ℓ₂ differences. The resulting score is evidence about how difficult the input was to reproduce at a location. Its interpretation as a defect depends on how often equally large errors occur on good material.

The ℓ₂ and SSIM autoencoders use a shared convolutional architecture with different reconstruction objectives. The ℓ₂ version emphasizes deviations between pixel values. The structural similarity index, or SSIM, compares local neighborhoods. This gives the comparison a way to respond to changes in nearby structure, including cases in which the differences at individual pixels give an incomplete account of the change. The benchmark uses an SSIM window of 11 × 11 pixels and converts images to grayscale for the SSIM implementation.

The authors start from an architecture that reconstructs patches of size 128 × 128 and add a convolutional layer to process images at 256 × 256. The latent space has dimension 128. The paper reports that increasing that dimension yielded little improvement in reconstruction quality, while decreasing it produced poor reconstructions. Both autoencoders train for 100 epochs with Adam. The initial learning rate is 2 × 10⁻⁴, and the batch size is 128.

The autoencoder training uses 10,000 derived samples per category. For textures, the authors take randomly located crops distributed over the clean training images. For objects, they translate and rotate whole images, resize them for the architecture, and mirror them where the object allows it. These transformations belong to the training procedure. The original dataset images still come from distinct samples. At inference, the object workflow reconstructs the image directly. In the texture workflow, patches are reconstructed in 64-pixel steps, and their score maps are averaged in overlapping regions. This difference affects both the appearance of the resulting map and the amount of computation needed to obtain it.

#### Producing scores from pretrained features

The Feature Dictionary starts with a ResNet-18 pretrained on ImageNet. Its patch description is the response of the network’s 512-dimensional average-pooling layer. The benchmark implementation uses principal component analysis to keep directions that explain 95% of the training-feature variance. It then runs K-means with 50 cluster centers. For each center, it retains the observed descriptor closest to it. The resulting collection is a compact representation of common training appearances. The underlying visual representation comes from [deep residual learning](https://md.research.elamur.ai/free/en/papers/he-2015-deep-residual-learning-image-recognition/).

For the dictionary, the authors extract 100,000 patches of size 128 × 128. This procedure is used for objects as well as textures. Test images are evaluated at their original resolution, sampling locations at a stride of 8 pixels to obtain a spatial map. Grayscale images are replicated across the input channels expected by ResNet-18. A patch that falls away from the represented training descriptors can receive a high anomaly score. This makes the learned coverage of normal appearances important. The dictionary can signal an unusual patch even if that patch lies within an otherwise recognizable object, and it can also respond to a perfectly good patch whose appearance has little support among its stored examples.

Student–Teacher uses responses from pretrained networks in a different way. A teacher supplies a feature description at each image location. Student networks learn to reproduce those descriptions using clean training images. At test time, prediction errors and disagreement among students provide evidence of an anomaly. A region can be suspicious because the students collectively predict the teacher’s response poorly, or because the training experience has left them with divergent predictions there. The teacher provides the target response for this comparison. It does not need a set of labeled industrial faults.

The implementation uses three teacher networks with receptive field sizes of 17, 33, and 65 for inputs of size 256 × 256 pixels. A receptive field is the portion of the input that can influence a descriptor at a particular position. Using different sizes lets the system compare details viewed within different amounts of surrounding material. Each teacher has an ensemble of 3 students. The teacher pretraining protocol uses feature matching and correlation losses for distillation, which passes information from a pretrained network into the teacher’s descriptors. Training runs for 100 epochs with Adam, an initial learning rate of 10⁻⁴, and a batch size of 1.

Teacher and student networks compute their local features densely, so the procedure produces a score for each input pixel without running a separate patch evaluation at each location. The training procedure uses all available feature vectors. Dense computation and dense training coverage are distinct properties here. The first concerns where the system can put a score at inference. The second concerns which clean descriptors can influence the learned prediction. Neither changes the fact that a descriptor gathers evidence from a neighborhood with a limited extent.

#### Producing scores with classical inspection

The GMM-based Texture Inspection method uses an optimized implementation from the HALCON machine vision library. GMM stands for Gaussian mixture model. A mixture represents a distribution using several Gaussian components, allowing common patches to have more than one characteristic appearance. The inputs are converted to grayscale and resized to 400 × 400 pixels. An image pyramid represents the input at successive resolutions. The implementation uses four layers and examines neighborhoods of 7 × 7 pixels at each layer. Training uses a maximum of 50 images randomly selected from the original training split.

A separate mixture is fitted for each pyramid level, using a dense covariance matrix to account for joint variation among the measurements. The method takes the negative log-likelihood of the local measurements as the anomaly score at that level. Rare appearances under the fitted distribution receive high scores. The authors standardize the scores from each level using the clean validation data so that the mean is 0 and the standard deviation is 1 there. They then average the normalized scores over the pyramid at corresponding image positions. This keeps a level whose raw scores have a larger numerical scale from dominating merely for that reason.

The Variation Model learns a reference image and a map of local tolerance. Using the available training images at their native dimensions, it estimates a mean and a standard deviation for every pixel location. Where a suitable alignment is possible, the authors place the specimens in a common coordinate frame before comparison. They use shape-based matching for bottle and metal nut, template matching with normalized cross-correlation for grid and transistor, and a rigid transformation based on the segmented shape for capsule and screw. These alignment choices are part of the experimental implementation.

At a given location, the score reflects the distance between the observed pixel value and the reference mean, scaled by a multiple of the standard deviation there. An ordinary location with little training variation can therefore receive a high score for a change that would be acceptable at a more variable location. For images with multiple channels, the method computes the departures separately and uses the largest channel score. Sometimes alignment moves a test pixel outside the area covered by the learned reference. The benchmark assigns such positions a score of 0, the minimum attainable value, because there is no corresponding mean and deviation with which to compare them.

#### Turning scores into measurable outcomes

All the methods produce an anomaly map, a set of numerical scores indexed by image position. A large score indicates stronger evidence of a defect. The score is compared with a threshold to produce a binary prediction. The paper’s rule is strict, so a pixel tied with the threshold is treated as normal.

```
Aᵢ(p) > t
```

Here `Aᵢ` is the anomaly map for test image `i`, and `p` is a position in that image. The notation `Aᵢ(p)` means the score at that position. The symbol `t` is a real-valued threshold, and `>` means the score must exceed it for the pixel to be predicted as defective.

The authors count the outcomes of that decision over the test set. The positive class is the annotated defect, and the negative class is everything else. Each count follows from intersecting a set defined by the test mask with a set defined by the score map.

```
TP = ∑ᵢ₌₁ⁿ |{p : Gᵢ(p) = 1} ∩ {p : Aᵢ(p) > t}|
```

`TP` counts true positives, or annotated defect pixels that were flagged. The sum `∑ᵢ₌₁ⁿ` combines counts from image `i` in a test set of `n` images. `Gᵢ(p)` is the ground-truth label at pixel `p`, with `1` denoting a defect. The braces define sets of positions satisfying the stated conditions, `∩` takes their intersection, and the vertical bars count the positions in that intersection. `Aᵢ(p) > t` is the flagging rule.

```
FP = ∑ᵢ₌₁ⁿ |{p : Gᵢ(p) = 0} ∩ {p : Aᵢ(p) > t}|
```

`FP` counts false positives. For each image `i`, the intersection `∩` contains pixels `p` whose ground-truth label `Gᵢ(p)` is `0`, meaning normal, even though their score `Aᵢ(p)` exceeds threshold `t`. The bars count those pixels, and the sum covers all `n` test images.

```
TN = ∑ᵢ₌₁ⁿ |{p : Gᵢ(p) = 0} ∩ {p : Aᵢ(p) ≤ t}|
```

`TN` counts true negatives. The set intersection selects pixels `p` in image `i` that have label `0` in `Gᵢ` and whose anomaly score from `Aᵢ` is at or below `t`, as indicated by `≤`. The bars give the count per image, and the sum adds those counts over the `n` images.

```
FN = ∑ᵢ₌₁ⁿ |{p : Gᵢ(p) = 1} ∩ {p : Aᵢ(p) ≤ t}|
```

`FN` counts false negatives. Here the label at `p` in `Gᵢ` is `1`, while its score in `Aᵢ` is at or below `t`. The intersection takes the positions meeting both conditions, the bars count them, and the sum adds the counts from the `n` test images indexed by `i`.

These totals let the authors describe the same threshold from different points of view. Recall asks how much of the annotated defect area was retrieved. The false-positive rate asks how much of the normal area was incorrectly flagged. Precision asks how much of the flagged area is actually defective.

```
TPR = TP / (TP + FN)
```

`TPR` is the true-positive rate, also called recall. Its numerator `TP` is the correctly flagged defect area measured in pixels. The denominator adds `FN`, the missed defect pixels, and so gives the complete annotated defective area. The slash denotes division.

```
FPR = FP / (FP + TN)
```

`FPR` is the false-positive rate. `FP` counts clean pixels that were flagged, and `TN` counts clean pixels that were accepted. Their sum in the denominator is the total number of clean pixels for the evaluation.

```
PRC = TP / (TP + FP)
```

`PRC` is precision. The denominator adds the correctly flagged defective pixels `TP` and the incorrectly flagged clean pixels `FP`. It represents all flagged pixels. The fraction measures how much of that prediction agrees with the annotation.

Intersection over union measures the overlap between the predicted and annotated areas relative to all the pixels covered by either. When the sets are pooled across test images, a position in one image is distinct from the same coordinates in another.

```
IoU = |P ∩ G| / |P ∪ G| = TP / (TP + FP + FN)
```

`IoU` is intersection over union for the defect class. `P` collects the predicted defect pixels across the test set, and `G` collects the annotated defect pixels. The symbol `∩` selects pixels present in both sets, `∪` gathers pixels present in either set, and the bars give their sizes. The equivalent count expression divides `TP`, the correct defect predictions, by the sum of those predictions, `FP` for excess predicted area, and `FN` for missed annotated area.

A large fault contains more pixels than a small one. A detector can therefore obtain substantial pixel recall from a few large defects even if its coverage of small faults is poor. To make that distinction visible, the paper also measures per-region overlap, abbreviated PRO. Each annotated mask is split into connected components, groups of defect pixels that form contiguous regions. The evaluator computes the fraction of each region covered by the prediction, then averages those fractions.

```
PRO = (1 / N) ∑ᵢ ∑ₖ |Pᵢ ∩ Cᵢ,ₖ| / |Cᵢ,ₖ|
```

`PRO` is per-region overlap. The outer sum runs over test images `i`, and the inner sum runs over their annotated connected components `k`. The set `Pᵢ` contains the pixels predicted as defective in image `i` at the chosen threshold. `Cᵢ,ₖ` contains the pixels in annotated component `k` of that image. The intersection `∩` selects the covered defect pixels, and the bars count pixels in each set. `N` is the total number of annotated components in the evaluated set, so `1 / N` gives equal weight to each component’s coverage.

PRO describes how thoroughly the prediction covers the annotated regions. Excess predictions elsewhere enter the evaluation through the accompanying false-positive rate. A region-level version of precision or IoU would need a rule for assigning those extra pixels to particular defects. That assignment is straightforward for true-positive pixels, which already lie within a labeled region. It is ambiguous for false positives that may lie far from every annotated fault or occur on a wholly clean image.

#### Sweeping thresholds and estimating operating points

To see how the maps behave across thresholds, the authors plot pairs of measures. The ROC curve gives true-positive rate against false-positive rate. The precision–recall curve gives precision against recall. The PRO and IoU curves put false-positive rate on the horizontal axis and per-region overlap or intersection over union on the vertical axis. Sweeping the threshold lets the evaluator assess the order in which defect and normal pixels are flagged without first choosing an operating point for every method.

The area under a curve compresses that tradeoff into a score. For curves with false-positive rate on the horizontal axis, the authors can integrate only up to a specified ceiling, then normalize the area so that the maximum attainable result is 1. They evaluate the entire precision–recall curve. Precision directly accounts for false alarms among the predicted positives, which is particularly relevant when the defective class occupies a small share of the image. The restricted false-positive curves answer a different question about how much detection the method achieves within a chosen allowance for incorrectly flagged clean pixels.

The operating-threshold experiment uses only the scores of clean validation images to choose where to put the cutoff. The Maximum estimator uses the largest score anywhere in those images. Because the prediction rule flags scores strictly above the cutoff, it allows no flagged validation pixels. The p-Quantile estimator sets the cutoff at a level where a specified percentage `p` of validation pixels is treated as clean. A few extreme scores can have less influence over this percentile than over the maximum.

The k-Sigma estimator uses the mean and spread of the validation scores.

```
t = μ + kσ
```

`t` is the score threshold, `μ` is the mean score over the clean validation pixels, and `σ` is the standard deviation of those scores. `k` is the chosen multiplier, and `kσ` is the amount added to the mean. If the score distribution is Gaussian, this multiplier can be related to a chosen tail probability. Its actual effect on validation or test pixels depends on the shape of the scores and how they transfer to new images.

Max-Area uses the spatial arrangement of high scores. It sets the threshold by allowing connected false-positive patches on the validation images only up to a specified permissible size. This reflects an inspection setting in which scattered small regions may be tolerable while a coherent patch of the same combined area can be a problem. The rule sets a threshold for the score map using a size assumption. Its usefulness depends on how that assumption relates to the faults the inspection is supposed to catch.

### Experiments and results

#### How the benchmark compares methods

The main segmentation experiments use the test images across the 15 categories of MVTec AD. Every tested method has access to defect-free images from the category it is fitted to, with the same held-out validation selection. Pretrained-feature methods additionally start from a representation learned on ImageNet. Evaluation uses the test masks to judge where high scores land. The paper reports category results and averages the areas over categories, so a mean expresses performance over the kinds of objects and surfaces in the dataset. It does not describe the outcome for any particular type of fault.

An important constraint comes from the fraction of the image that can be defective. Only 2.7% of pixels in the test set carry a defect label. Consequently, the absolute area flagged on good material can be substantial even at a threshold where the false-positive rate looks modest as a fraction. The paper illustrates this with a metal-nut color defect. At a threshold giving a false-positive rate of 1% for that example image, the segmentation picks out the defect well. At 30%, the mask is already badly degraded. At 100%, the entire image has been marked. Each contour comes from the same score map, which makes the effect of changing the cutoff visible.

#### Overall ranking and category differences

Student–Teacher achieves the highest mean precision–recall area. The Feature Dictionary follows, and GMM-based Texture Inspection leads the classical and reconstruction approaches on that mean. The gap between the pretrained-feature methods and the reconstruction methods is consistent with the paper’s finding that a useful representation of visual appearance can be transferred into this problem. The comparison itself is between complete implemented methods. Their differing scores reflect the full combination of feature source, training strategy, input treatment, and inference procedure.

Mean pixel precision–recall area on MVTec AD by method Student–Teacher leads the category average, followed by the Feature Dictionary.

**The numbers**

| System or setting | AU-PR |
| --- | --- |
| Student–Teacher (this paper) | 0.599 |
| Feature Dictionary | 0.466 |
| GMM Texture Inspection | 0.299 |
| ℓ₂ autoencoder | 0.241 |
| Variation Model | 0.234 |
| SSIM autoencoder | 0.148 |
| f-AnoGAN | 0.136 |

The mean advantage persists under several other views of the same predictions. With a false-positive ceiling of 30%, Student–Teacher records a normalized mean ROC area of 0.922, compared with 0.836 for the Feature Dictionary. Under the same ceiling, the corresponding mean IoU areas are 0.190 and 0.168. The lower values for IoU reflect a metric that charges the prediction for missed defect pixels as well as extra predicted area. They have their own interpretation and scale. For mean PRO area at that ceiling, Student–Teacher records 0.924, the Feature Dictionary 0.803, and Texture Inspection 0.741.

Some categories offer a much better fit to one method than the overall mean suggests. On bottle, the Feature Dictionary records a precision–recall area of 0.814, ahead of Student–Teacher’s 0.775. Cable also favors the dictionary on this measure, with 0.617 compared with 0.592. For metal nut, Student–Teacher reaches 0.940 in precision–recall area, compared with 0.760 for the dictionary and 0.384 for the Variation Model. Those examples show the value of keeping category results visible alongside the average. Which method leads can depend on the item being inspected.

Leather, hazelnut, and zipper show why classical texture inspection remains a relevant baseline. On leather, Texture Inspection reaches 0.603 in precision–recall area and Student–Teacher reaches 0.490. On hazelnut, Texture Inspection reaches 0.689, while the ℓ₂ autoencoder has an area of 0.590 and Student–Teacher 0.585. On zipper, Texture Inspection records 0.611 and Student–Teacher 0.588 on the same metric. The paper’s explanation for the leather result is grounded in the comparatively uniform texture shown in its qualitative example, which suits a method that estimates the normal distribution of local gray-value patterns.

A different category can be challenging for all the leading approaches. On transistor, the highest precision–recall area is 0.381 for the ℓ₂ autoencoder. The Feature Dictionary records 0.364 and Student–Teacher 0.346. Table-level rankings and image examples answer complementary questions here. The autoencoder can lead the category aggregate while still having a modest score. At the same time, a specific transistor fault can reveal a weakness in one of the better methods that is hard to identify from a category mean alone.

The relative standing of methods can also depend on what a correct prediction is meant to look like. On zipper, Texture Inspection’s mean over the category’s precision–recall curve is higher than Student–Teacher’s, but Student–Teacher has a normalized PRO area of 0.955 up to a 30% false-positive rate, compared with Texture Inspection’s 0.923. Precision–recall evaluates the balance of correct and incorrect predicted pixels as recall changes. PRO gives each annotated region the same influence on the coverage measure and compares that coverage with the background flagged at the threshold. The two results can coexist because they give weight to different aspects of a map.

#### What the predicted maps show

The paper pairs a good and a poor qualitative example for each approach. The maps are thresholded for the comparison at a test false-positive rate of 0.01. This presents outputs under a shared false-positive criterion. An individual image can still show more or less excess predicted area than another. These panels help distinguish a high score at the true defect surrounded by manageable noise from a map whose strongest response lies on an ordinary edge, mark, or reflection.

In the f-AnoGAN example, a defect at the tip of a screw is visible because of the contrast between screw and background. Edges and strongly reflective areas also produce errors where the reconstruction is imperfect. On a carpet with a structural defect, the reconstructed image changes too little at the faulty region for the input–output comparison to expose it. The method can therefore have two simultaneous problems. It assigns high scores to some clean detail it has difficulty reconstructing and low scores to some damaged structure whose reconstruction differs little from the input.

The Feature Dictionary locates a small crack in a capsule. It also gives elevated scores to part of the capsule’s ordinary imprint, which the authors attribute to incomplete representation of that appearance in the sampled training patches. The case illustrates a weakness that can arise even with pretrained descriptors. A strong feature representation still needs a useful account of which descriptors are ordinary for the particular product. In another example, the dictionary misses the wrong insulation color in part of a cable cross section. The authors connect that failure with the method’s limited view of overall object context.

Student–Teacher typically gives comparatively steady scores across normal parts of the illustrated images, which the authors associate with training on all available local features. Reflective transistor legs still evoke some elevated scores. More consequentially, the method misses a missing leg. Individual local appearances can be plausible while the object as a whole lacks an expected part. The annotation marks where the leg should be. That location asks the detector to recognize an absence using information about the relationship between the empty region and the rest of the object.

The autoencoder reconstructions can be blurry, particularly around fine structures. The paper illustrates spurious scores near the boundary of a hazelnut and around toothbrush bristles. The ℓ₂ method has difficulty with a transparent color fault on tile because the values in the reconstruction and the input do not differ strongly enough. The grayscale SSIM implementation misses a red stroke on leather. These cases show how both the representation going into a reconstruction system and the comparison coming out of it affect which changes can be seen.

Texture Inspection performs well on the leather example, where the ordinary surface can be described through repeated local measurements. The grayscale implementation is less suited to a pill defect expressed through color. It can also score object boundaries highly because their patches are underrepresented in training. The Variation Model does well on precisely aligned rigid objects such as a metal nut. Its carpet example is poor because pixel positions cannot be put into useful correspondence across samples. High estimated variation at many positions then makes a wide range of values appear permissible.

#### Inference costs and their interpretation

The paper reports timing in broad ranges because library choices, opportunities for parallel execution, and implementation details affect the result. The Feature Dictionary requires several seconds for a single image in the evaluated setup. It processes many patches and extracts one score for each patch. A larger stride would reduce the amount of computation and make the output map coarser. The time comparison is therefore tied to the spatial detail of the evaluated configuration.

The autoencoders can process object images with a single network evaluation on the GPU, taking a few milliseconds in the paper’s description. For textures, repeated evaluations of overlapping patches move the runtime into the range of several hundreds of milliseconds. The strided f-AnoGAN evaluation also takes several hundreds of milliseconds. Student–Teacher obtains dense maps, but evaluating each teacher and its ensemble requires multiple forward passes. According to the paper, each network takes tens of milliseconds to run, and the combined runtime is on the order of several hundred milliseconds. The optimized CPU implementations take tens of milliseconds for the Variation Model and hundreds for Texture Inspection.

The approximate parameter totals put the storage of learned weights in perspective. The paper reports 26.07 M for Student–Teacher, 24.57 M for f-AnoGAN, and 11.46 M for the Feature Dictionary. Each autoencoder has 1.20 M parameters. For neural methods, parameter count is a lower bound on memory use because intermediate features also take space during execution. The Variation Model stores means and deviations at image locations and can have a parameter count in a similar range to a neural approach. Its computation has different intermediate storage requirements, so equal counts across those approaches would give little basis for assuming equal memory consumption.

### What the ablations show

#### Restricting evaluation to cleaner masks

The paper gives no component-by-component ablation of Student–Teacher. Its controlled analyses instead change the metric, vary the allowable false-positive range, compare thresholds derived from clean validation data, and examine particular successes and failures. The autoencoders also share a basic architectural setup and differ in their reconstruction objective, though the corresponding image preprocessing differs as well. These comparisons support conclusions about the evaluated choices and their consequences for the outputs.

The clearest change in ranking occurs when the authors restrict the range over which they measure per-region overlap. At a ceiling of 30% false positives, the Feature Dictionary comes ahead of Texture Inspection in mean PRO area. At 5%, Texture Inspection has a mean of 0.488 and the dictionary 0.459. At 1%, the dictionary ranks fourth. The underlying test score maps are the same across these comparisons. Changing the ceiling changes which part of their threshold behavior contributes to the aggregate.

Mean normalized PRO area on MVTec AD up to a 1% false-positive rate Student–Teacher retains the lead, while Texture Inspection and the pixel-loss autoencoder move ahead of the Feature Dictionary.

**The numbers**

| System or setting | AU-PRO |
| --- | --- |
| Student–Teacher (this paper) | 0.432 |
| GMM Texture Inspection | 0.263 |
| ℓ₂ autoencoder | 0.218 |
| Feature Dictionary | 0.201 |
| Variation Model | 0.197 |
| f-AnoGAN | 0.113 |
| SSIM autoencoder | 0.075 |

The full PRO curve gives the Feature Dictionary a mean normalized area of 0.931 and Texture Inspection 0.890. Student–Teacher has 0.974 over the full curve. Thus a method can recover much of the annotated defect area as the threshold relaxes and still have difficulty placing defect pixels ahead of the strongest normal responses at stringent thresholds. The tighter integration limit makes that early ordering matter more. The authors report that narrowing the false-positive range reduces normalized PRO areas by factors ranging from 2 for Student–Teacher to 11 for the SSIM autoencoder in their comparison. The leading method is affected too, even though its relative advantage holds.

The comparison also shows why the evaluator has to understand where a method gains overlap. If an improvement appears mainly when the detector is already flagging substantial clean area, it may offer little help in a stringent inspection setting. Conversely, the ranking at the strictest reported ceiling expresses usefulness only within that part of the curves. An evaluator interested in locating small defects while allowing some extra area has a different tradeoff to examine from one who needs the cleanest attainable masks.

Zipper is the paper’s example for comparing curves directly. Its defect regions vary less in size than those of some other categories, and its ROC and PRO curves are consequently similar. Weighted by pixels, a reasonably uniform set of defect sizes already gives each region a more similar influence. The precision–recall curves add information about the flagged pixels themselves. For most recall values, the methods other than Student–Teacher and Texture Inspection have precision below 0.5 on zipper. At those operating points, more flagged pixels are false positives than true positives. The IoU curves are constrained further because missed defect pixels also enlarge the denominator.

#### Choosing thresholds with clean images alone

For the operating-point experiment, the authors estimate thresholds on the clean validation images for bottle, pill, and wood. The plotted comparison displays the three methods with the highest AU-PRO in each of those categories. They test the Maximum rule, a quantile with `p = 0.99`, a k-Sigma threshold chosen to correspond to a quantile of 0.99 under a Gaussian assumption, and a Max-Area rule that permits connected components smaller than 0.1% of the input image area. The thresholds are then applied to the corresponding test images, where false-positive rate and PRO show the balance actually obtained.

The Maximum rule gives the lowest test false-positive rates among the estimators in this experiment. It can also be so conservative that it produces no true positives. A high score in a single clean validation image can push the threshold above the scores generated by genuine faults in test images. This is a property of the rule’s dependence on the most extreme observation. It can occur even if the score map ranks many annotated defect pixels above most normal pixels and consequently performs reasonably in a threshold sweep.

The quantile and k-Sigma rules both aim at a false-positive rate of one percent under their respective settings. Their applied thresholds frequently give higher test false-positive rates, and their markers can be far apart even for the same method and category. The empirical quantile depends on the observed ordering of validation scores. The k-Sigma cutoff uses a mean and a standard deviation and relies on a Gaussian interpretation to hit its intended tail. Divergent operating points show that the Gaussian description frequently fails to supply the intended cutoff for these score distributions.

Max-Area permits small connected patches on clean validation images, so lowering the threshold can be acceptable while those patches stay below the size tolerance. In many comparisons, the resulting choice is only slightly more permissive than the Maximum threshold. The authors infer that connected false-positive regions of the size they care about often appear soon after dropping below the largest score. This gives a spatial reason why allowing some errors at validation time need not buy much extra detection. Errors may begin to cluster before a more useful cutoff is reached.

Comparing these markers with the underlying PRO curves clarifies what the operating-point experiment adds. A curve shows the detection and false-positive tradeoffs available across thresholds, using labels to measure the result after the fact. A marker shows where a rule arrived using clean validation data alone. A high curve can coexist with a poor marker because the clean validation data give the threshold estimator no direct evidence about where the scores of future faults will lie. The paper finds substantial differences across both the detector and the category when it evaluates this transfer.

#### What can be attributed to the reconstruction objective

The shared autoencoder architecture makes the ℓ₂ and SSIM comparison narrower than the comparison between an autoencoder and Student–Teacher. In the benchmark configuration, the ℓ₂ autoencoder has mean precision–recall area 0.241, and the SSIM autoencoder has 0.148. At a 30% false-positive ceiling, the mean PRO areas are 0.632 and 0.617, respectively. When the full PRO curve is used, the values are 0.838 for ℓ₂ and 0.840 for SSIM. The structural objective fares differently depending on which portion of the curve matters.

The comparison includes the practical condition that the SSIM implementation works on grayscale. A defect whose main evidence is a color change may be weakened or lost before that system has a chance to judge reconstruction quality. The red stroke on leather gives the paper a concrete example. The transparent tile fault illustrates a different problem for the pixel-loss autoencoder, since even an imperfect reconstruction can differ from the input too little to cause a useful alarm. These examples show different failure routes within the evaluated pipelines. The experiment gives no isolated estimate of how much of the aggregate gap comes from the objective or from the treatment of color.

The comparison between the pretrained approaches has similar limits on causal interpretation. Student–Teacher uses dense regression, multiple receptive field sizes, and disagreement among students. The dictionary compresses sampled patch descriptors into a finite set and evaluates patches at a stride. The paper’s observation that the dictionary can overreact to an uncommon but good imprint fits the difference in training coverage. The transistor and cable examples also fit the authors’ observation that both approaches have limited access to global context. Scores for the completed methods show how these choices work together, while the paper leaves the contribution of individual design choices unresolved.

### Limitations

#### Limits the authors identify

The authors see considerable room for improvement across the benchmark. Every method can locate some defects, and performance varies across object and texture categories. Pretrained local features give the strongest overall results, with the missing transistor leg and the cable cross section providing visible limits to local reasoning. The defect in such a case depends on how an expected part relates to the rest of the item. A good account of the appearance of individual patches can leave that relationship unrepresented.

Reconstruction-based approaches are vulnerable wherever normal structure is hard to reproduce or a defect leaves only a weak discrepancy. The authors show this sensitivity around thin parts, object boundaries, and reflections. They also identify a separate restriction of the grayscale implementations on faults expressed through color. Those observations qualify what a low score means for a particular region. Low reconstruction error may mean the system reproduced the fault, and low anomaly evidence in a grayscale pipeline may mean that the informative signal was removed beforehand.

The paper treats threshold selection on good validation images as an unresolved practical problem. Its tested rules can be too cautious to detect a fault or too permissive to give a usable segmentation, with outcomes that change across applications represented by different categories and methods. The authors favor estimating thresholds without defect examples because a limited set of known faults need not cover future ones. That choice makes the conditions of the evaluation clear, while leaving difficult questions about where an inspection system should set its decision boundary.

The authors also qualify the runtime and memory comparisons. The timings describe the evaluated implementations in broad terms. They depend on details such as forward-pass count, the libraries used, and parallelization. Parameter totals omit the space used by intermediate computations, and they carry different meanings for a neural network and a pixelwise reference. These results help explain relative costs in the particular benchmark configurations and give only limited evidence about resource use in another implementation.

#### Limits that follow from the experimental design

The samples are physical, and the photographs depict faults made to resemble industrial ones. The authors deliberately selected and created the damage under conditions that made local annotation practical. The dataset therefore supports comparison on a diverse set of inspection problems with known masks. It gives no estimate of the frequency of these defects in manufacturing, how they cluster over time, or the mix of defects an inspection station would actually encounter. The test-set proportion of anomalous pixels describes this collection, including how it was assembled.

Image acquisition was generally controlled, with deliberate variation for some categories. The benchmark therefore gives a detector examples of the pose, material, and lighting variation chosen by the authors. Its results leave open how a fitted detector would respond to a different acquisition process. The distinction matters because normal appearance is defined by the clean sample collection. The findings about false positives on ordinary imprints, thin parts, and reflections illustrate what happens when acceptable appearance is hard to represent even within that collection.

The masks encode informed decisions about faults that can have ambiguous boundaries. The annotation of a missing part means the expected location is treated as anomalous, while the annotation of a deformed part can extend through the region where it should have been. This makes the task more meaningful for inspection, since a missing component can be important without occupying visible pixels. Pixel-level agreement in such cases measures agreement with the labeling rule as well as localization of the visible evidence. Similarly, assigning uncertain border pixels to the defect can matter more for a small region whose boundary makes up a substantial part of its mask.

The category averages summarize segmentation performance. They do not determine a part-level false-rejection rate. A false-positive pixel in a background area, a cluster of false-positive pixels on an object, and a false alarm that causes an entire acceptable part to be rejected are different events. Turning the maps into decisions about parts would require a rule for aggregating pixels or components and an evaluation of the resulting image-level decisions. The dataset can support that kind of test, but the central quantitative comparisons here concern pixel and region scores.

The clean-validation experiment covers bottle, pill, and wood and shows selected leading methods for those categories. Its evidence is that threshold transfer can be difficult under the tested conditions, including on methods with strong curve areas. Estimating how often each rule would fail across all the categories, or how sensitive it is to a new validation split, would require additional experiments. The reported comparison gives concrete examples of conservative thresholds missing faults and permissive thresholds generating excess area, without establishing the frequency of either outcome beyond the tested setup.

Finally, the strongest average results compare methods that bring pretrained visual representations to the task with approaches that learn their reconstruction behavior from scratch. The configurations also differ in image sizes, color handling, training features, and how many computations they perform at each location. Pretraining is a common property of the leading methods in this benchmark. The experiments do not quantify the gain it would provide if the same detector were trained both ways with all its other choices held fixed. That distinction matters when using the result to select a direction for further experiments.

### What came after

The later work [EfficientAD](https://md.research.elamur.ai/free/en/papers/batzner-2023-efficientad-accurate-visual-anomaly-detection/) cites MVTec AD and takes up visual anomaly detection with efficiency and accuracy as joint concerns. Those concerns connect directly to the benchmark’s comparison of methods that produce dense score maps through different amounts of computation. MVTec AD treats localization quality and inference cost as distinct properties of a detector. Its results give the efficiency question a concrete setting in which a strong segmentation method can still require repeated network evaluations or extensive patch processing.

## Cite

Cite as Paul Bergmann, Kilian Batzner, Michael Fauser, David Sattlegger and Carsten T. Steger. 2021. The MVTec Anomaly Detection Dataset: A Comprehensive Real-World Dataset for Unsupervised Anomaly Detection. International Journal of Computer Vision.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.1007/s11263-020-01400-4](https://doi.org/10.1007/s11263-020-01400-4)

```bibtex
@article{bergmann2021mvtec,
  title = {{The MVTec Anomaly Detection Dataset: A Comprehensive Real-World Dataset for Unsupervised Anomaly Detection}},
  author = {Paul Bergmann, Kilian Batzner, Michael Fauser, David Sattlegger and Carsten T. Steger},
  journal = {International Journal of Computer Vision},
  year = {2021},
  doi = {10.1007/s11263-020-01400-4},
  url = {https://doi.org/10.1007/s11263-020-01400-4}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
