Skip to article
← All writing

Computer Vision / An inspection field note

Why My Anomaly Detector Improved but Still Missed Every Defect

How ROI masking improved anomaly ranking—and exposed a deeper problem with threshold calibration.

Earlier ROI evaluationHistorical observations

Anomaly ranking / AUROC

~0.64→~0.81

Approximately +0.17 AUROC. A masking-only causal effect is not established.

Inspection flags / threshold 0.72

0 / 50

No evaluated image crossed the configured inspection threshold.

Better ranking did not automatically produce useful inspection decisions.

The detector appeared to be getting better. An earlier ROI evaluation reported stronger anomaly ranking. But at the configured inspection threshold, not one of the evaluated images was flagged.

I could have stopped at the improved AUROC. Instead, that mismatch became the more useful result. It exposed a gap between recognizing visual differences and turning those differences into an inspection decision.

HistoricalROI investigation

LaterFrozen calibration

ReservedIndependent holdout

01 / The inspection problem

The scene was part of the signal.

I was working with a reference-based anomaly detector built on pretrained DINOv2 representations. Instead of learning a conventional classifier for named defect categories, the workflow compared incoming component images with a small collection of confirmed-good references. The question was whether an image departed from normal appearance—not which specific defect it contained.

That comparison depends on what the representation sees. An inspection image contains a component, but also a work surface, fixtures, shadows, reflections, and incidental edges. Positioning changes can move all of those relationships. A visual difference can be real without being relevant to the inspection task.

Consider a normal casting photographed against an unfamiliar background and a defective casting against a familiar one. In principle, background differences could raise the normal component’s score while familiar context could make the defective one look less unusual. This is a failure mode to investigate, not a claim about two particular experiment images.

Reference-based visual inspectionConceptual workflow
  1. Reference / 01Confirmed-good images
  2. Reference / 02DINOv2 encoder
  3. Reference / 03Reference features
  1. Inspection / 01Inspection image
  2. Inspection / 02DINOv2 encoder
  3. Inspection / 03Patch features

Reference features + patch embeddings

  1. 01Reference matching
  2. 02Anomaly scoring
  3. 03Threshold → decision
s(p) = minr ∈ R ‖f(p) − r‖₂

p is an image patch; f(p) its embedding; R the reference features. This nearest-reference formulation illustrates the idea, not the proprietary distance or image-level aggregation implementation.

DINOv2 supplies pretrained visual features. Patch embeddings describe local image regions; reference matching asks how far those representations depart from confirmed-good features. An anomaly score summarizes deviation, and a threshold turns that score into a binary inspection decision. Each step answers a different question.

02 / The masking hypothesis

Give the inspection a boundary.

ROI masking makes the intended inspection region explicit. A binary mask assigns one to locations that should contribute and zero outside them. The engineering hypothesis is that excluding irrelevant regions will make anomaly scores more responsive to the component itself.

Synthetic inspection scene

Conceptual illustration — synthetic component.

Keep the component. Question the context.

The component shares the frame with fixture edges, a work surface, and a shadow. All are visual input; only some belong to the inspection task.

M(x, y) = 1 inside the ROI; 0 outside.

But ‘apply a mask’ is not one operation. There are different places to restrict the signal, with different consequences. The approved information does not establish which exact masking mechanism the project used; the approaches below are conceptual alternatives.

01 / Masking approach

Image-level

Restrict input pixels before encoding. The encoder sees the changed image, including the boundary introduced by masking.

02 / Masking approach

Feature-level

Restrict which patch embeddings contribute to matching. The features were still extracted from a particular visual context.

03 / Masking approach

Score-level

Restrict the spatial anomaly scores used in aggregation. The mask changes what contributes to the inspection score.

An earlier ROI evaluation reported AUROC increasing from approximately 0.64 to 0.81—about +0.17. That suggested better separation in that historical evaluation. The available records do not establish a fully controlled masking-only experiment, so I cannot attribute the entire change to masking alone.

AUROC measures how well scores rank defective examples above good ones across possible thresholds. Around 0.50 represents chance-level ranking; 1.00 represents perfect ranking. A stronger ranking result was encouraging. It did not tell me whether the configured inspection cutoff was useful.

03 / The unexpected result

A better ranking. No inspection flags.

The earlier inspection run used a configured threshold of 0.72. It flagged zero of the 50 evaluated images. The ranking metric suggested progress, yet the decision rule produced no positive flags. Without looking at the score scale, it would have been easy to mistake an improved AUROC for an improved inspection system.

There is no mathematical contradiction. Defective examples can score above good ones while every score remains below the cutoff. Ranking asks about relative order. A threshold asks which side of one particular line each score occupies. Moving the line changes decisions without changing the order.

The example below deliberately uses four invented teaching scores. It is not a reconstruction of the historical run or the later calibration data. Lower the threshold and watch the flags change while the score positions stay fixed. The visualization does not recalculate AUROC.

Same scores. Different decisions.Illustrative example — not experimental data.
0.001.00
Good A0.22
Not flagged
Good B0.27
Not flagged
Defect A0.34
Not flagged
Defect B0.41
Not flagged
0 / 4 illustrative flags0 false alarms · 2 missed defects

A score ≥ threshold is flagged. The score positions and ranking stay fixed; moving the slider does not recalculate AUROC. These four teaching scores are separate from every measured result in this article.

This changed the investigation. I needed to understand score distributions and decision trade-offs separately from representation quality. A useful inspection policy needs evidence about missed defects and false alarms, not only a ranking statistic.

04 / A later, separate experiment

Calibration made the overlap visible.

A later workflow introduced a frozen calibration split containing 12 confirmed-good and 12 confirmed-defective examples. An independent holdout was reserved for later evaluation. The results discussed here come from calibration; they do not report an evaluation of that holdout.

Calibration AUROC was 0.784722. This belongs to a different experimental stage from the earlier approximate 0.81 ROI result. Reading those numbers as a controlled performance decline would erase changes in evaluation context that the comparison does not account for.

Later calibration / observed score rangesSummary statistics only
Mean markerOverlapping range

Confirmed good

Mean 0.286044

Observed range0.222846–0.357582

Confirmed defective

Mean 0.326223

Observed range0.273155–0.415787

0.20Anomaly score · displayed scale 0.20–0.440.44

Shared score range 0.273155–0.357582

Bars show minimum to maximum, not density. No individual measured scores, histogram, or fitted distribution are plotted. The higher mean defect score does not eliminate the overlap.

The mean defect score was higher than the mean good score, but their observed ranges overlapped. A high-scoring good example could sit above a lower-scoring defective one. No single high-score cutoff could perfectly separate these calibration observations.

Moving a threshold can exchange one kind of error for another. It cannot repair the relative ordering of examples whose scores are already interleaved. The range summary exposes that limitation without pretending to know the shape of the distributions or inventing individual observations.

05 / Threshold calibration

Three cutoffs. Different mistakes.

I examined three calibration-derived candidates. Youden uses both good and defect labels to maximize recall minus false-positive rate. The good-only P95 and P99 candidates use upper percentiles of the acceptable-component scores. They encode different ways to place a decision boundary; they do not change the representation.

On calibration, Youden found more defects and flagged more good components. P95 and P99 reduced false alarms in this sample, but missed more defects. P99 raised the cutoff further without improving the observed false-positive count. A more conservative threshold was not automatically a more useful inspection rule.

Calibration operating points12 good + 12 defective examples
RecallFalse-positive rate

Youdent = 0.315057

Recall
75.0%
FPR
25.0%

P95t = 0.33939625

Recall
25.0%
FPR
8.3%

P99t = 0.35394485

Recall
16.7%
FPR
8.3%
0%50%100%

Good + defect calibration labels

0.315057calibration threshold

Detects more defective calibration examples, with more false alarms. Maximizes J = Recall − FPR; ties prefer higher defect recall, then a lower threshold.

Actual class × inspection decision
ActualFlagNo flag
Defective9TP3FN
Good3FP9TN

TP: detected defect · FP: false alarm
TN: accepted good · FN: missed defect

Read all calibration confusion counts
Youden · 0.315057
TP 9 · FP 3 · TN 9 · FN 3
P95 · 0.33939625
TP 3 · FP 1 · TN 11 · FN 9
P99 · 0.35394485
TP 2 · FP 1 · TN 11 · FN 10

Recall = TP / (TP + FN). FPR = FP / (FP + TN). All operating points use calibration data. Percentiles are based on only 12 good examples and do not guarantee future false-positive rates. No production threshold is selected here.

Only 12 good calibration examples informed the upper-tail percentiles. P95 and P99 are therefore sensitive to the highest observed good scores. Their names do not promise corresponding future false-positive rates. Choosing a policy requires inspection requirements and the costs of false alarms and missed defects; this comparison does not select a universal winner.

06 / Statistical uncertainty

One estimate. A wide interval.

The calibration estimate also needed an uncertainty statement. With 12 examples in each class, individual observations can materially affect the measured ranking. Reporting the point estimate alone would suggest more precision than this sample supports.

The workflow used stratified bootstrap resampling: sample 12 good scores with replacement, independently sample 12 defect scores with replacement, then recalculate AUROC. Repeating that process 10,000 times preserves the class counts while exploring variation under resampling. The 2.5th and 97.5th percentiles gave the reported 95% bootstrap interval.

Later calibration / AUROC uncertaintyStratified bootstrap · 10,000 resamples
0.785Calibration AUROC · exact estimate 0.784722

95% bootstrap interval
0.583333–0.944444

00.50 · chance-level ranking1.00

The wide interval indicates uncertainty in estimated anomaly-ranking performance. These are calibration-set results, not independent holdout or production performance.

The interval was 0.583333–0.944444. Its width matters more than the apparent precision of a six-decimal point estimate. The calibration sample provides limited precision for estimating broader anomaly-ranking performance.

Bootstrap resampling reuses the observations available. It cannot fix dataset bias, leakage, unrepresentative acquisition conditions, or distribution shift. A technically correct interval is still conditional on the data and workflow behind it; it is not proof of production reliability.

07 / Planned investigations

Improve the scores before moving the line again.

Once score overlap is visible, repeatedly adjusting the cutoff has a clear limit. The next question is how to improve the representations and comparisons that produced those scores. I would start with the simplest, most inspectable changes before increasing model capacity.

The investigations below remain planned. Increasing encoder capacity would come only after the simpler changes have been evaluated. None of these proposed experiments is presented as a completed improvement.

  1. Reference selection

    Improve the choice of confirmed-good reference images.

    Planned
  2. Scoring and aggregation

    Investigate nearest-neighbour aggregation and top-k patch scoring.

    Planned
  3. Inspection boundaries

    Refine manually defined ROIs around relevant component regions.

    Planned
  4. Encoder capacity

    Evaluate a larger DINOv2 encoder after simpler changes.

    Planned

A proposed development gate was calibration AUROC ≥ 0.90. That was a target, not an achieved result. A fair next comparison would record the reference selection, ROI definition, model fingerprint, split, and scoring policy, then freeze threshold candidates before an independent holdout evaluation. Better bookkeeping cannot guarantee a better model, but it makes a change interpretable.

08 / What the investigation changed

An inspection decision needs its own evaluation.

  1. The background can become evidence.

    Visual deviation and inspection relevance are different things.

  2. Masking needs an experiment.

    The historical AUROC improvement does not isolate a masking-only causal effect.

  3. A ranking is not a decision policy.

    The zero-flag result made the threshold’s score scale impossible to ignore.

  4. Every cutoff trades errors.

    Calibration recall and false alarms must be interpreted together.

  5. Uncertainty belongs beside the metric.

    Frozen splits, leakage prevention, and a wide bootstrap interval constrain the claims.

The historical ROI result was a useful signal, not the end of validation. The zero-flag observation forced the next question: was the detector ranking examples usefully while its decision rule operated on the wrong part of the score scale? Calibration then exposed overlap that a threshold alone could not resolve.

The practical lesson is to evaluate the connections between representation, scoring, and decisions. Better ranking can support a better inspection policy, but it does not establish one. Reliable inspection requires understanding where the scores come from, what errors the cutoff trades, and how much the available evidence can actually support.

Better anomaly ranking is a model result.
A reliable inspection decision is a system question.

The related case study

Explore the inspection workflow.

Reference features, ROI-aware processing, calibration, and the engineering decisions around visual anomaly detection.

Industrial Visual Anomaly Detection
  • Computer Vision
  • DINOv2
  • Anomaly Detection
  • ROI Masking
  • Model Evaluation
  • Threshold Calibration
  • Industrial AI
← Back to all writing