← All articles

AI / Machine Learning · 12 October 2026 · 12 min read

Building a Defect Detection System with YOLO

A practical walkthrough of building an object detection system for real-world visual inspection, covering dataset preparation, annotation, model training, evaluation, deployment, and lessons learned.

  • YOLO
  • Computer Vision
  • Object Detection
  • Deep Learning
  • Python
Building a Defect Detection System with YOLO

Building a Defect Detection System with YOLO

Computer vision has become an important part of modern industrial automation. From identifying manufacturing defects to monitoring product quality, object detection models can help automate inspection processes that traditionally require manual effort.

In this article, I'll walk through the process of building a defect detection system using YOLO (You Only Look Once), covering the complete workflow from dataset preparation and annotation to model training, evaluation, and deployment.

The goal was to explore how an object detection model could identify visual defects in images and how such a system could eventually be integrated into a real-world inspection workflow.

Industrial visual inspection system

1. Understanding the Problem

Traditional quality inspection often relies on human operators examining products and identifying visible defects.

Although this approach can work, it introduces several challenges:

  • Manual inspection can become repetitive and time-consuming.
  • Inspection quality may vary between operators.
  • Small defects can be difficult to identify consistently.
  • Scaling inspection operations requires additional resources.
  • Maintaining consistent inspection standards can be challenging.

Computer vision offers an alternative by allowing machines to analyze images and identify specific visual patterns.

Why object detection?

There are several computer vision approaches that could be used for defect inspection.

Approach Description Potential use case
Image Classification Assigns a label to an entire image Determining whether a product is defective
Object Detection Identifies objects and their bounding boxes Locating defects within an image
Image Segmentation Identifies individual pixels belonging to a class Measuring the exact area of a defect

For this project, object detection was particularly interesting because identifying the location of a defect is just as important as determining its presence.

2. Why YOLO?

YOLO is a family of real-time object detection models designed to predict object classes and bounding boxes in a single inference pipeline.

Unlike traditional region-proposal-based approaches, YOLO processes an image through a unified neural network.

YOLO object detection illustration

Key advantages

  • Real-time inference capabilities.
  • Good balance between accuracy and computational cost.
  • Multiple model sizes for different hardware requirements.
  • Support for custom datasets.
  • A well-established ecosystem for training and deployment.

Understanding the model variants

YOLO implementations offer different model sizes depending on the accuracy and speed requirements.

Model size Relative complexity Typical application
Nano (n) Very low Edge devices and lightweight inference
Small (s) Low Resource-constrained applications
Medium (m) Moderate General-purpose detection
Large (l) High Accuracy-focused applications
Extra Large (x) Very high More demanding detection workloads

The appropriate model depends on dataset complexity, hardware availability, latency requirements, and the desired detection accuracy.

3. Dataset Collection and Preparation

The quality of an object detection system depends heavily on the quality of its training dataset.

A model cannot reliably identify defects it has never learned to recognize.

For this reason, dataset preparation is one of the most important stages of the entire workflow.

Dataset requirements

A useful dataset should contain:

  • Images representing normal products.
  • Images containing different defect categories.
  • Variations in lighting and image quality.
  • Different product orientations and backgrounds.
  • Both obvious and subtle defects.

The dataset should represent the conditions under which the final system is expected to operate.

Dataset directory structure

A typical YOLO dataset can be organized as follows:

dataset/
├── images/
│   ├── train/
│   ├── val/
│   └── test/
│
├── labels/
│   ├── train/
│   ├── val/
│   └── test/
│
└── data.yaml

Each image has a corresponding annotation file containing the object classes and bounding-box coordinates.

Dataset splitting

The dataset should be divided into separate subsets.

Dataset Suggested proportion Purpose
Training 70% Learning model parameters
Validation 20% Monitoring model performance
Testing 10% Final evaluation

These proportions are illustrative. The actual split should account for dataset size, class distribution, and the risk of similar images appearing across different subsets.

4. Image Annotation

Object detection requires labeled bounding boxes around the objects that the model should identify.

For example, if an image contains a scratch on a metal surface, the annotation should identify the scratch's location and assign it the appropriate class.

Example industrial defect inspection

Annotation tools

Some commonly used annotation tools include:

Tool Main purpose
Label Studio Image annotation and dataset management
CVAT Computer vision annotation workflows
Roboflow Dataset preparation, annotation, and augmentation
LabelImg Bounding-box annotation

For a YOLO workflow, annotations are generally stored in text files using the YOLO format.

Understanding YOLO annotation format

Each object is represented using five values:

class_id x_center y_center width height

The coordinates are normalized relative to the image dimensions.

For example:

0 0.512 0.438 0.120 0.085
1 0.325 0.612 0.090 0.110

Here:

  • class_id identifies the defect category.
  • x_center represents the normalized horizontal center.
  • y_center represents the normalized vertical center.
  • width represents the normalized bounding-box width.
  • height represents the normalized bounding-box height.

All coordinates except the class identifier are generally between 0 and 1.

5. Configuring the YOLO Dataset

YOLO uses a dataset configuration file to identify image directories and class names.

Example data.yaml:

path: ./dataset
 
train: images/train
val: images/val
test: images/test
 
names:
  0: scratch
  1: dent
  2: crack
  3: contamination

The class names should correspond exactly to the class identifiers used during annotation.

A mismatch between annotation identifiers and class definitions can lead to incorrect training labels.

6. Training the Model

Once the dataset is prepared, the next step is training the detection model.

For this example, I'll use the Ultralytics YOLO Python interface.

Installing dependencies

pip install ultralytics

Training example

from ultralytics import YOLO
 
# Load a pretrained YOLO model
model = YOLO("yolo11n.pt")
 
# Train on the custom dataset
results = model.train(
    data="dataset/data.yaml",
    epochs=100,
    imgsz=640,
    batch=16,
    patience=20,
    project="runs/defect_detection",
    name="yolo_experiment"
)

This example uses YOLO11 Nano as a starting point. The model can be replaced with another compatible YOLO checkpoint depending on the requirements.

Understanding training parameters

Parameter Description
data Dataset configuration file
epochs Number of training iterations over the dataset
imgsz Input image resolution
batch Number of images processed per batch
patience Early-stopping patience
project Output directory
name Experiment name

Monitoring training

During training, it is important to monitor:

  • Training box loss.
  • Classification loss.
  • Distribution focal loss (DFL), where applicable.
  • Validation losses.
  • Precision and recall.
  • Mean Average Precision (mAP).

A decreasing training loss alone does not guarantee good generalization. Validation performance is essential for understanding whether the model is learning useful features.

7. Evaluating Model Performance

After training, the model needs to be evaluated on data it has not seen during training.

This helps determine whether it can identify defects beyond the examples it learned from.

Important evaluation metrics

Precision

Precision measures how many predicted defects were actually correct.

Recall

Recall measures how many actual defects were successfully detected.

F1-score

F1-score combines precision and recall using their harmonic mean.

Mean Average Precision (mAP)

mAP summarizes detection performance across classes and confidence thresholds, under a specified IoU evaluation protocol.

Metric What it tells us
Precision How reliable positive predictions are
Recall How many actual defects are detected
F1-score Balance between precision and recall
mAP@50 Detection performance at IoU 0.50
mAP@50-95 Performance averaged across IoU thresholds from 0.50 to 0.95

Running validation

from ultralytics import YOLO
 
model = YOLO(
    "runs/defect_detection/yolo_experiment/weights/best.pt"
)
 
metrics = model.val(
    data="dataset/data.yaml",
    split="test"
)
 
print(metrics.results_dict)

The evaluation results should be recorded for every experiment so that different model configurations can be compared objectively.

8. Running Inference

Once the model has been trained and evaluated, it can be used to detect defects in new images.

Example:

from ultralytics import YOLO
 
model = YOLO(
    "runs/defect_detection/yolo_experiment/weights/best.pt"
)
 
results = model.predict(
    source="sample_product.jpg",
    conf=0.35,
    save=True
)
 
for result in results:
    for box in result.boxes:
        class_id = int(box.cls[0])
        confidence = float(box.conf[0])
 
        print({
            "class": model.names[class_id],
            "confidence": round(confidence, 3)
        })

The model returns bounding boxes, class predictions, and confidence scores.

The confidence threshold can be adjusted depending on the inspection requirements.

Computer vision object detection example

9. Deploying the Model

Training a model is only one part of building a useful computer vision system.

To make the model accessible to other applications, we can expose it through an API.

FastAPI is one option for creating a lightweight inference service.

Example architecture

Image Input
    |
    v
FastAPI Endpoint
    |
    v
Image Preprocessing
    |
    v
YOLO Detection Model
    |
    v
Postprocessing
    |
    v
JSON Response

FastAPI implementation

from fastapi import FastAPI, UploadFile, File
from ultralytics import YOLO
from PIL import Image
import io
 
app = FastAPI()
 
model = YOLO("best.pt")
 
@app.post("/detect")
async def detect(file: UploadFile = File(...)):
 
    image_bytes = await file.read()
    image = Image.open(
        io.BytesIO(image_bytes)
    ).convert("RGB")
 
    results = model.predict(
        image,
        conf=0.35
    )
 
    detections = []
 
    for result in results:
        for box in result.boxes:
            class_id = int(box.cls[0])
 
            detections.append({
                "class": model.names[class_id],
                "confidence": float(box.conf[0]),
                "bbox": box.xyxy[0].tolist()
            })
 
    return {
        "success": True,
        "detections": detections
    }

This provides a basic inference endpoint that accepts an image and returns detection results.

For production deployment, additional considerations include input validation, file-size limits, model warm-up, concurrency management, authentication, logging, and GPU resource management.

10. Challenges and Lessons Learned

Building a computer vision system involves more than selecting a model and starting training.

Some of the most important challenges to consider are:

Dataset quality

Poor annotations and inconsistent image quality can significantly affect model performance.

Improving annotation consistency and reviewing difficult examples can be more valuable than simply increasing the number of training epochs.

Class imbalance

If one defect category appears much more frequently than another, the model may become biased toward the dominant class.

Possible solutions include:

  • Collecting more examples of underrepresented classes.
  • Applying suitable data augmentation.
  • Monitoring per-class precision and recall.
  • Using appropriate sampling strategies.

Overfitting

A model can perform well on training data while struggling with unseen images.

Validation monitoring, early stopping, augmentation, and careful dataset splitting help reduce this risk.

Inference performance

A model that performs well during training may still be unsuitable for real-time inspection if its inference latency is too high.

Model size, input resolution, hardware acceleration, and batch processing all influence deployment performance.

11. Future Improvements

There are several directions in which this project could be extended.

Improvement Potential benefit
Real-time camera integration Continuous defect inspection
Object tracking Tracking defective products across frames
Segmentation More precise defect boundaries
Model quantization Reduced inference resource requirements
Edge deployment Running inspection locally
Inspection dashboard Monitoring detections and system activity
Dataset expansion Better coverage of defect variations

One particularly interesting direction would be integrating object detection with a production monitoring dashboard, allowing operators to review detections and track inspection statistics.

12. Conclusion

Building a defect detection system with YOLO demonstrates how deep learning can be applied to practical industrial computer vision problems.

The overall workflow involves much more than model training. Dataset preparation, annotation quality, evaluation methodology, inference optimization, and deployment architecture all play important roles in building a reliable system.

For me, the most interesting part of this process is understanding how individual machine learning components come together to form a complete application.

Computer vision is not just about getting a model to make predictions. It is about building a system that can produce useful, consistent, and measurable results in real-world conditions.

There is still plenty of room to experiment with different architectures, datasets, and deployment strategies, and that is what makes this area particularly interesting to explore.


References and Further Reading

Disclaimer: The code, class names, dataset split, and training parameters in this article are illustrative examples. Actual project results should be added only after running and evaluating the corresponding experiments.

AS

Aditya Manoj Shinde

Author

I'm Aditya, a developer passionate about AI, Machine Learning, and software development. I love exploring new technologies, building projects, and sharing what I learn along the way.