Work  /  Applied AI

Visual defect detection

An autoencoder that learns what a good product looks like, rejects anything it can't rebuild, and watches for drift in production.

merciven.co/work/defect-detection/live/LiveOpen ↗
The Visual defect detection app, running with sample data

The problem

Manual visual inspection is slow and inconsistent, and defects are rare, so there are too few examples of each fault to train a normal classifier.

Objectives

  1. Learn from good items only
  2. Flag cracks, contamination and breakage without labelled defects
  3. Serve predictions fast enough for a line
  4. Notice when the camera or lighting changes

Process

  1. DiscoverChose an anomaly-detection framing because defect examples are scarce.
  2. DefineReconstruction error against a threshold picked on validation data.
  3. BuildA convolutional autoencoder trained with MSE plus SSIM loss, exported to ONNX and served by FastAPI.
  4. ProveAUROC per epoch, ROC curve, reconstructions and an Evidently drift report.

Who it's for

Quality engineers

Get a pass or reject with the error score behind it.

Operations

See when inputs drift and the model needs a look.

Challenges

  • Very few defective examples
  • Pixel loss alone misses fine texture damage
  • Deployment must not depend on PyTorch
  • Lighting changes quietly break vision models

What we built

Trained on good items

The model only ever sees good bottles, so any defect shows up as reconstruction error.

MSE + SSIM loss

Structural similarity catches texture damage that plain pixel loss blurs over.

ONNX inference API

A FastAPI endpoint takes an image and returns the error, threshold and verdict.

Drift monitoring

Evidently compares live inputs with training data and raises drift.

Flow

  1. Camera image
  2. Resize and normalise
  3. Autoencoder rebuilds it
  4. Reconstruction error
  5. Compare with threshold
  6. Pass or reject
  7. Drift report

Tools & languages

  • PyTorch
  • ONNX Runtime
  • FastAPI
  • Evidently AI
  • OpenCV
  • Docker

The code

Training, ONNX export, the FastAPI server, drift detection, tests and the proof images (loss curves, AUROC, ROC and reconstructions).

View the code on GitHubTalk it through on a call