Building a Visual Anomaly Detector with PatchCore

In manufacturing, semiconductor inspection, and pharmaceutical packaging, collecting thousands of labeled defect images is nearly impossible—defects are rare, unpredictable, and constantly evolving. Supervised binary classifiers fail when an unseen scratch, dent, or contamination pattern appears on the assembly line.

PatchCore solves industrial visual inspection using one-class nominal modeling: it learns exclusively from defect-free ("normal") images without requiring any gradient-based fine-tuning. By extracting multi-scale mid-level patch features from a pretrained backbone, compressing them into a representative memory bank via greedy coreset subsampling, and scoring test patches by nearest-neighbor distance, PatchCore achieves state-of-the-art image-level detection and pixel-level defect localization.

Why PatchCore Excels at Industrial Defect Detection

Unlike reconstruction-based autoencoders or GANs—which often blur fine textures or accidentally reconstruct small defects—PatchCore preserves high-resolution spatial patch descriptors directly in a searchable index:

Anomaly Detection ParadigmTraining RequirementPixel-Level LocalizationInference Latency (CPU/GPU)Failure Mode
Supervised CNN / ViTNormal + all defect classesRequires pixel masksFast (5–15 ms)Fails completely on novel, unseen defect types
Autoencoder / Diffusion ReconstructionNormal images onlyModerate (residual diff)Slow (50–300 ms)Over-generalizes and reconstructs subtle defects
PatchCore (Memory Bank + Coreset)Normal images only (no training loop)Sharp pixel-level heatmapsFast (15–35 ms)Memory scales with dataset size without coreset subsampling

How the PatchCore Pipeline Works

PatchCore operates in two distinct phases—offline memory bank construction and online inference:

  1. Multi-Scale Mid-Level Feature Extraction: Input images ($224 \times 224$) pass through a frozen ImageNet-pretrained WideResNet-50-2. Rather than using deep semantic features from Layer 4 (which lose spatial resolution and overfit to ImageNet classes), PatchCore extracts feature maps from Layer 2 ($28 \times 28 \times 512$) and Layer 3 ($14 \times 14 \times 1024$).
  2. Locally Aware Patch Aggregation: Each spatial location undergoes local neighborhood average pooling ($3 \times 3$, stride $1$) so every patch vector encodes both local texture and immediate spatial context. Layer 3 is bilinearly upsampled to $28 \times 28$ and concatenated with Layer 2 into a $28 \times 28 \times 1536$ feature grid ($784$ patch vectors per image).
  3. Greedy Coreset Subsampling: Storing $784$ vectors across $500$ normal images produces $392,000$ vectors—too slow for real-time nearest-neighbor search. PatchCore applies Iterative Greedy Coreset Subsampling (using random Johnson-Lindenstrauss projections for speed) to select $1\%$–$10\%$ of patches that maximally cover the nominal feature manifold.
  4. Anomaly Scoring & Heatmap Upsampling: At test time, each query patch finds its nearest neighbor $m^*$ in the memory bank $\mathcal{M}$. The image-level anomaly score $s$ is the maximum patch distance reweighted by neighborhood density, while reshaping the $28 \times 28$ distances and applying Gaussian smoothing ($\sigma = 4$) yields a pixel-accurate defect heatmap.

Project Structure & Dependencies

Organize the project cleanly to separate feature extraction, coreset compression, and inference visualization:

TEXT
patchcore-inspector/
├── data/
│   └── bottle/
│       ├── train/good/          # Defect-free reference images
│       └── test/
│           ├── good/            # Clean validation images
│           └── broken_large/    # Defective test samples
├── artifacts/
│   └── memory_bank.pt           # Saved coreset patch index
├── src/
│   ├── extractor.py             # Multi-scale WideResNet-50 patch extractor
│   ├── coreset.py               # Greedy coreset subsampling
│   ├── build_index.py           # Offline memory bank builder
│   └── infer.py                 # Anomaly scoring & heatmap overlay
└── requirements.txt

Install the required packages:

Bash
pip install torch torchvision timm scikit-learn scipy opencv-python matplotlib tqdm

Step 1: Multi-Scale Patch Feature Extractor (src/extractor.py)

We hook intermediate feature maps from wide_resnet50_2, apply local neighborhood pooling, and align spatial grids into unified $1536$-dimensional patch embeddings:

Python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import Wide_ResNet50_2_Weights, wide_resnet50_2


class PatchCoreExtractor(nn.Module):
    """Extracts locally aware multi-scale patch features from WideResNet-50-2."""

    def __init__(self, device: str = "cuda") -> None:
        super().__init__()
        self.device = torch.device(device if torch.cuda.is_available() else "cpu")
        self.backbone = wide_resnet50_2(weights=Wide_ResNet50_2_Weights.IMAGENET1K_V1)
        self.backbone.eval().to(self.device)

        self._features: dict[str, torch.Tensor] = {}
        self.backbone.layer2.register_forward_hook(self._save_hook("layer2"))
        self.backbone.layer3.register_forward_hook(self._save_hook("layer3"))

        self.patch_pool = nn.AvgPool2d(kernel_size=3, stride=1, padding=1)

    def _save_hook(self, name: str):
        def hook(_module, _inp, output: torch.Tensor) -> None:
            self._features[name] = output

        return hook

    @torch.no_grad()
    def extract(self, images: torch.Tensor) -> tuple[torch.Tensor, tuple[int, int]]:
        """
        Args:
            images: Normalized tensor [B, 3, H, W]
        Returns:
            patches: [B * H_p * W_p, 1536]
            grid_size: (H_p, W_p) spatial resolution of patch map
        """
        images = images.to(self.device)
        _ = self.backbone(images)

        feat2 = self.patch_pool(self._features["layer2"])  # [B, 512, 28, 28]
        feat3 = self.patch_pool(self._features["layer3"])  # [B, 1024, 14, 14]

        # Upsample layer3 to match layer2 spatial dimensions (28x28)
        feat3_up = F.interpolate(
            feat3,
            size=feat2.shape[-2:],
            mode="bilinear",
            align_corners=False,
        )

        # Concatenate along channel dimension -> [B, 1536, 28, 28]
        combined = torch.cat([feat2, feat3_up], dim=1)
        batch_size, channels, h_p, w_p = combined.shape

        # Flatten spatial grid into patch vectors: [B * H_p * W_p, 1536]
        patches = combined.permute(0, 2, 3, 1).reshape(-1, channels)
        patches = F.normalize(patches, p=2, dim=-1)
        return patches, (h_p, w_p)

Step 2: Greedy Coreset Subsampling (src/coreset.py)

To compress hundreds of thousands of nominal patch vectors without losing boundary coverage of rare normal patterns, we project vectors to $128$ dimensions and iteratively pick the farthest point from the already selected set:

Python
import torch
from sklearn.random_projection import SparseRandomProjection
from tqdm import tqdm


def greedy_coreset_subsampling(
    patches: torch.Tensor,
    sampling_ratio: float = 0.05,
    projection_dim: int = 128,
    seed: int = 42,
) -> torch.Tensor:
    """
    Selects a representative coreset of patch embeddings using k-center greedy search.
    """
    num_patches = patches.shape[0]
    target_size = max(1, int(num_patches * sampling_ratio))
    if target_size >= num_patches:
        return patches

    # Reduce dimensionality for fast Euclidean distance updates
    projector = SparseRandomProjection(n_components=projection_dim, random_state=seed)
    projected = torch.from_numpy(
        projector.fit_transform(patches.cpu().numpy())
    ).float()

    device = patches.device
    projected = projected.to(device)

    torch.manual_seed(seed)
    first_idx = torch.randint(0, num_patches, (1,), device=device).item()
    selected_indices = [first_idx]

    # Track minimum squared distance from every patch to the current coreset
    min_distances = torch.cdist(
        projected, projected[first_idx : first_idx + 1]
    ).squeeze(1)

    for _ in tqdm(range(1, target_size), desc="Building Coreset"):
        next_idx = torch.argmax(min_distances).item()
        selected_indices.append(next_idx)

        new_distances = torch.cdist(
            projected, projected[next_idx : next_idx + 1]
        ).squeeze(1)
        min_distances = torch.minimum(min_distances, new_distances)

    return patches[selected_indices]

Step 3: Building the Nominal Memory Bank (src/build_index.py)

Run this script once over your clean train/good directory to generate and serialize the compressed memory bank:

Python
from pathlib import Path
import torch
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms

from coreset import greedy_coreset_subsampling
from extractor import PatchCoreExtractor


IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]


class NominalImageDataset(Dataset):
    def __init__(self, image_dir: str, image_size: int = 224) -> None:
        self.paths = sorted(Path(image_dir).glob("*.png")) + sorted(
            Path(image_dir).glob("*.jpg")
        )
        self.transform = transforms.Compose(
            [
                transforms.Resize((image_size, image_size)),
                transforms.ToTensor(),
                transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
            ]
        )

    def __len__(self) -> int:
        return len(self.paths)

    def __getitem__(self, idx: int) -> torch.Tensor:
        img = Image.open(self.paths[idx]).convert("RGB")
        return self.transform(img)


def build_memory_bank(
    train_dir: str,
    output_path: str,
    sampling_ratio: float = 0.05,
) -> None:
    dataset = NominalImageDataset(train_dir)
    loader = DataLoader(dataset, batch_size=16, shuffle=False)
    extractor = PatchCoreExtractor()

    all_patches: list[torch.Tensor] = []
    for batch in loader:
        patches, _ = extractor.extract(batch)
        all_patches.append(patches.cpu())

    full_bank = torch.cat(all_patches, dim=0).to(extractor.device)
    print(f"Total nominal patches extracted: {full_bank.shape[0]}")

    coreset_bank = greedy_coreset_subsampling(
        full_bank, sampling_ratio=sampling_ratio
    )
    Path(output_path).parent.mkdir(parents=True, exist_ok=True)
    torch.save(coreset_bank.cpu(), output_path)
    print(f"Saved compressed memory bank ({coreset_bank.shape}) to {output_path}")


if __name__ == "__main__":
    build_memory_bank(
        train_dir="data/bottle/train/good",
        output_path="artifacts/memory_bank.pt",
        sampling_ratio=0.05,
    )

Step 4: Anomaly Scoring & Pixel-Level Heatmap Generation (src/infer.py)

At inference time, we compute nearest-neighbor distances against the coreset memory bank, calculate the image-level anomaly score, and render a smoothed defect localization overlay:

Python
from pathlib import Path
import cv2
import numpy as np
import torch
from PIL import Image
from scipy.ndimage import gaussian_filter
from torchvision import transforms

from build_index import IMAGENET_MEAN, IMAGENET_STD
from extractor import PatchCoreExtractor


class PatchCoreInspector:
    def __init__(self, memory_bank_path: str, image_size: int = 224) -> None:
        self.extractor = PatchCoreExtractor()
        self.device = self.extractor.device
        self.memory_bank = torch.load(memory_bank_path, map_location=self.device)
        self.image_size = image_size
        self.transform = transforms.Compose(
            [
                transforms.Resize((image_size, image_size)),
                transforms.ToTensor(),
                transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
            ]
        )

    @torch.no_grad()
    def predict(self, image_path: str) -> tuple[float, np.ndarray]:
        pil_img = Image.open(image_path).convert("RGB")
        tensor = self.transform(pil_img).unsqueeze(0)

        query_patches, (h_p, w_p) = self.extractor.extract(tensor)
        # Compute pairwise Euclidean distances: [784, num_coreset_patches]
        distances = torch.cdist(query_patches, self.memory_bank)
        min_dists, _ = torch.min(distances, dim=1)

        # Image-level anomaly score = maximum patch distance
        image_score = float(torch.max(min_dists).item())

        # Reshape to 2D patch grid and upsample to original image dimensions
        anomaly_map = min_dists.reshape(h_p, w_p).cpu().numpy()
        anomaly_map = cv2.resize(
            anomaly_map,
            (self.image_size, self.image_size),
            interpolation=cv2.INTER_CUBIC,
        )
        anomaly_map = gaussian_filter(anomaly_map, sigma=4)
        return image_score, anomaly_map

    def save_heatmap_overlay(
        self,
        image_path: str,
        anomaly_map: np.ndarray,
        output_path: str,
        vmax: float = 0.85,
    ) -> None:
        orig = cv2.imread(image_path)
        orig = cv2.resize(orig, (self.image_size, self.image_size))

        norm_map = np.clip(anomaly_map / vmax, 0.0, 1.0)
        heatmap = cv2.applyColorMap(np.uint8(255 * norm_map), cv2.COLORMAP_JET)
        overlay = cv2.addWeighted(orig, 0.6, heatmap, 0.4, 0)

        Path(output_path).parent.mkdir(parents=True, exist_ok=True)
        cv2.imwrite(output_path, overlay)


if __name__ == "__main__":
    inspector = PatchCoreInspector("artifacts/memory_bank.pt")
    test_img = "data/bottle/test/broken_large/000.png"
    score, heatmap = inspector.predict(test_img)
    inspector.save_heatmap_overlay(test_img, heatmap, "artifacts/defect_overlay.png")
    print(f"Image Anomaly Score: {score:.4f}")

Calibration & Evaluation Metrics

Before deploying on an inspection line, calibrate your decision threshold $\tau$ and validate across both detection and localization benchmarks:

  • Image-Level AUROC & F1-Optimal Threshold: Compute scores across held-out good and defective validation samples. Set the rejection threshold $\tau = \mu_{\text{good}} + 3\sigma_{\text{good}}$ (or tune via Youden's $J$ statistic on a small defect validation set) to control false-positive scrap rates.
  • Pixel-Level AUROC & AUPRO (Area Under Per-Region Overlap): Unlike pixel AUROC—which is biased toward large defects—AUPRO weights small hairline cracks equally with large structural damage, making it the gold standard for industrial inspection.
  • Fixed Colorbar Normalization (vmax): Never normalize each image's heatmap independently (anomaly_map / anomaly_map.max()), or clean images will display bright red noise; always normalize against a fixed dataset-wide upper bound calibrated from nominal validation data.

Best Practices for Production Visual Inspection

  • Lock camera lighting, exposure, and white balance: PatchCore compares raw appearance descriptors against stored nominal patches; uncompensated ambient lighting shifts trigger false alarms across the entire frame.
  • Use $k$-NN density reweighting for noisy textures: For stochastic surfaces like wood grain, fabric weave, or brushed aluminum, reweight the maximum patch distance using its $k=9$ nearest neighbors in the memory bank to suppress isolated outlier noise.
  • Accelerate search with FAISS (IndexFlatL2): When scaling above $50,000$ coreset vectors or high-FPS conveyor belts, replace torch.cdist with a GPU faiss.IndexFlatL2 index for sub-$5\text{ ms}$ nearest-neighbor lookup.
  • Store separate memory banks per SKU or camera angle: Isolate memory banks per product variant rather than mixing unrelated parts into a single index, preserving tight decision boundaries.

Common Mistakes

  • Extracting features from layer4 of ResNet: Deep Layer 4 features have coarse $7 \times 7$ spatial resolution and encode high-level ImageNet object semantics rather than fine surface scratches, causing PatchCore to miss subtle micro-defects.
  • Omitting local neighborhood average pooling (AvgPool2d): Comparing single $1 \times 1$ spatial cells makes embeddings overly sensitive to 1-pixel alignment jitter on the conveyor belt.
  • Including unverified images in train/good: Even two defective samples accidentally left in the nominal training folder get preserved by greedy coreset sampling (because they are outliers!), blinding the detector to that defect class.

Summary

PatchCore delivers high-precision industrial defect detection and pixel-level localization without requiring labeled anomaly data or fragile generative training loops. By combining mid-level WideResNet-50 patch embeddings, greedy coreset subsampling, and nearest-neighbor distance scoring, you can deploy a fast, interpretable visual inspection pipeline on standard manufacturing hardware.