License YOLO
Guides

Image classification vs object detection for industrial inspection: how to choose

A classifier returns one OK/NG label per image; a detector boxes the defects it finds. How to choose for inspection, split OK/NG data and handle stains.

Jing Qiu13 min read

Listen to this article

A classifier returns one OK/NG label per image; a detector boxes the defects it finds. How to choose for inspection, split OK/NG data and handle stains.

An inspection station has one job: decide whether a part passes. So should the model behind it be a classifier that labels each image OK or NG (not good), or an object detector that draws a box around each defect it finds? Choose by the output the line needs. Use image classification when a pass/fail verdict for the whole image is enough. Use object detection when you need to know where defects are, how many there are or which type. Use segmentation when the reject rule depends on a defect's exact shape or area, as it often does for water stains.

This guide walks through that decision for industrial inspection: what each task returns, how to build an OK/NG dataset for each, how to split it so validation scores mean something, and how to run both with Ultralytics YOLO26.

Classification answers "is it OK?", detection answers "what is wrong, and where?"#

A classifier reads the whole image and returns one label with a probability for each class. For an inspection camera that sees one part per frame, that label is the decision: ok or ng. The labels are the simplest to make: each image goes in a folder named after its class, and nobody draws anything.

A detector returns a bounding box, a class and a confidence for each defect it detects. The OK/NG decision becomes a rule you write: no defect boxes above your confidence threshold means OK. The extra output is what makes detection useful beyond the verdict: the box directs an operator to the detected region, the class records the defect type, and the count and box size let you write rules such as "reject two or more scratches."

Here is how the three tasks compare for inspection in Ultralytics YOLO:

Classification (classify)Detection (detect)Semantic segmentation (semantic)
OutputOne label per imageA box, class and score per detected defectA class for every pixel
LabelsFolder name per imageOne box per defect; OK images need no label fileClass masks or polygon labels
AnswersPass or fail, defect gradeWhere, which type, how manyHow much area, exact shape
Gating metricTop-1 accuracy plus per-class recallmAP, precision and recallmIoU and per-class IoU
Pretrained YOLO26 weightsyolo26n-cls.pt (ImageNet, 224 px)yolo26n.pt (COCO, 640 px)yolo26n-sem.pt (Cityscapes)

Speed favors the classifier, but not by as much as people expect. On the Classify task page, YOLO26n-cls runs in 1.1 ms on an NVIDIA T4 with TensorRT 10 at 224 pixels, averaged over ImageNet validation images. On the Detect task page, YOLO26n runs in 1.7 ms on the same GPU and runtime at 640 pixels, averaged over COCO validation images. On a CPU with ONNX, the gap is wider: 5.0 ms for YOLO26n-cls against 38.9 ms for YOLO26n. Measure your complete pipeline, from capture to reject signal, on your own hardware before ruling either one out on speed.

A pass/fail label is enough when the defect is large in the frame#

Classification is the right first model when three things hold:

  • One part per image. The camera is fixed, the part is centered, and the background is the same every time.
  • Defects stay visible at the classifier's input size. YOLO26 classifiers are pretrained at 224 pixels. A 2,048 x 2,048 image resized to 224 x 224 shrinks about 9 times on each side, so a scratch 9 pixels wide ends up about 1 pixel wide. Check your smallest defects after the actual training and inference transforms, which also crop the image, as the next paragraph explains. You can train at a larger imgsz, at the cost of speed.
  • Nobody needs the location. The reject gate only needs a yes or no, and no one downstream asks which defect it was or where.

There is one classifier-specific trap to check before you trust it. Ultralytics classification uses a random resized crop for training and a center crop for validation and inference, as the Classify docs explain. On a wide image, the center crop drops the left and right edges, and a defect sitting there is never seen. If your images aren't close to square, swap in the ClassifyLetterBox transform the docs show, which keeps the whole image and pads it instead.

Classification also works as a second stage. When the part is small in a wide frame, detect the part first, then classify each full-resolution crop. The Academy lesson on combining tasks in one pipeline shows this detect-then-classify pattern and why the classifier's training data should come from the detector's own crops.

You need boxes when defects are small, many, or must be shown to a person#

Detection earns its extra labeling effort in four situations that come up constantly on inspection lines:

  1. Small defects on large surfaces. A detector trains at 640 pixels by default and finds objects across the whole frame. For very high-resolution images, tiled inference and the high-resolution tiling guide keep small defects at a size the model can see.
  2. Several defect types with different consequences. A dent may mean rework and a crack may mean scrap. Per-class boxes give you both the type and a count.
  3. Rules about size or position. "A scratch on the sealing face is a reject, one on the flange is cosmetic" needs a location.
  4. Human verification. A box directs the reviewer straight to the detected region instead of leaving them to search the whole image.

Public inspection data shows what these datasets look like in practice. KolektorSDD2 on Ultralytics Platform has 3,335 color images of production items in one defect class, and most of its items are defect-free. MVTec AD goes further: 5,354 high-resolution industrial photos in 73 classes, each pairing an object or texture with a defect type, such as a bottle with large breakage or a cable with a bent wire. Its boxes are derived from the original defect masks.

The MVTec AD dataset page on Ultralytics Platform with a grid of industrial object and texture photos

The MVTec AD dataset page on Ultralytics Platform, where you can browse its 5,354 industrial photos and 73 object-and-defect classes before training on them.

Detection handles OK images without any extra labeling. In the Ultralytics YOLO format, an image with an empty or missing label file is a background image, and training penalizes any confident prediction on it. So your OK images go in as they are. The Ultralytics training tips suggest about 0 to 10% background images for general datasets, as a guide rather than an inspection target. An inspection line produces far more OK parts than that, so favor OK images that look like defects, such as harmless tool marks, reflections and dust, and add the OK images your first model flags by mistake, a practice known as hard negative mining.

The cost is labeling time. Every defect needs a box, and annotators need a written rule for edge cases, such as whether two touching scratches are one box or two. On detection datasets, Smart annotation in Ultralytics Platform drafts boxes from your class names with Ultralytics VLM1, so reviewers correct and approve boxes instead of drawing each one from scratch.

Segment stains when the reject rule depends on their area#

Some defects have no edges a box can follow. A water stain, an oil film, corrosion or a coating void spreads in an irregular shape and fades into the clean surface around it. A detector can still locate it, and if "is there a stain, and where?" is the whole question, a box is enough. But a box around a sprawling stain covers mostly clean material and says little about how much surface is affected.

When the reject rule is about area, semantic segmentation labels every pixel instead. The output answers "how much": the share of the inspected part region that is stained, which you can compare against a reject threshold in a few lines of code. Severstal on Ultralytics Platform shows the format: 18,074 grayscale steel-sheet images from PAO Severstal's 2019 Kaggle competition, set up for semantic segmentation with four anonymized defect types.

YOLO26 semantic segmentation models carry the -sem suffix and come pretrained on the 19 Cityscapes classes or the 150 ADE20K classes, per the Semantic Segmentation task page, so fine-tune them on your own surfaces before trusting the map. They train on class masks or polygon labels, as the semantic dataset docs describe. If you need to count separate defects and measure each one, use instance segmentation instead; our guide to semantic vs instance segmentation covers that choice.

Putting it together, the decision comes down to what the output must answer:

Decision diagram: if nobody needs to know where the defect is, classify OK/NG; if location matters but the reject rule does not depend on area or shape, detect with boxes; if it depends on area or shape, segment pixels

The Academy lesson on picking the task and planning the pipeline turns this into a plan table: the question, task, weights, label format, result field and gating metric for each model. Its main rule applies directly to inspection: name the line of code that consumes the output before anyone labels, because changing the task later means relabeling.

Imbalance and leakage can make OK/NG validation scores misleading#

Whichever task you choose, the dataset decides whether the validation score means anything, and two problems can quietly inflate it.

Inspection stations often capture the same part several times: from different angles, under different lights, or on a second pass. If those near-duplicates land in both train and validation, the model is graded on images it has effectively seen, a form of data leakage. Group images by part serial number, batch or capture session, and assign whole groups to one split. The Academy lesson on splits that tell the truth shows how to audit a dataset for these twins.

Within that constraint, aim for similar OK/NG proportions in train, validation and a separate test set. Stratified sampling does this when examples are independent; scikit-learn's train_test_split does it with stratify=labels, and StratifiedGroupKFold approximates it while keeping groups intact. Ultralytics YOLO's automatic 80/20 classification split shuffles images within each class, but it doesn't know your parts or batches, so make grouped splits yourself when images are related. After splitting, check that every class appears in every split.

Gate on NG recall, not accuracy#

NG parts are rare. If 2 images in 100 are NG, a model that answers "OK" every time scores 98% accuracy and catches nothing. Gate on part-level NG recall and false rejects: compare each part's final OK, NG or review decision with its true status, and report the parts sent to review separately as review workload. A classifier's confusion matrix gives these per image; a detector's confusion matrix counts matched and unmatched boxes, so compute the part-level numbers from your own decision rule.

Make sure every split holds enough NG images to measure them, and collect NG examples across every defect type and condition the line sees: shift lighting, part variants, camera refocus. A classifier always answers, even for images unlike anything it has seen, so a new defect type gets labeled as whichever class it resembles most.

How to train an OK/NG classifier and a defect detector with Ultralytics YOLO#

Both start the same way: pip install ultralytics, then fine-tune a pretrained YOLO26 model on your images.

  1. Write the task down. One sentence for the question, one for the output, one for the decision rule.
  2. Lay out the data. For classification, put images in train/ng/, train/ok/, val/ng/ and val/ok/ following the classification dataset format. For detection, label each defect with a box and leave OK images without a label file.
  3. Train and validate. Start with the nano model, then move up a size if accuracy falls short.
  4. Set thresholds on held-out data. Pick the confidence that meets your NG recall target, and measure part-level NG recall, false rejects and review workload together.
  5. Export for the line. Export to ONNX, TensorRT, OpenVINO or another runtime that matches your inspection PC.

A classifier that sends uncertain parts to review:

from ultralytics import YOLO

# path/to/parts/train/{ng,ok}/ and path/to/parts/val/{ng,ok}/
model = YOLO("yolo26n-cls.pt")
model.train(data="path/to/parts", epochs=50, imgsz=224)

for result in model.predict("path/to/line_images", stream=True):
    label = result.names[result.probs.top1]  # look up names, never hard-code indices
    confidence = float(result.probs.top1conf)
    verdict = label if confidence >= 0.90 else "review"
    print(result.path, verdict, f"{confidence:.2f}")

A detector whose boxes become the decision, with a review band for low-confidence detections:

from ultralytics import YOLO

model = YOLO("yolo26n.pt")
model.train(data="path/to/defects.yaml", epochs=100, imgsz=640)

for result in model.predict("path/to/line_images", conf=0.10, stream=True):
    scores = result.boxes.conf.tolist()
    if any(s >= 0.25 for s in scores):
        verdict = "NG"
    elif scores:
        verdict = "review"  # only weak detections: let a person decide
    else:
        verdict = "OK"
    print(result.path, verdict, [result.names[int(c)] for c in result.boxes.cls])

The 0.90, 0.10 and 0.25 thresholds are starting points; set yours on held-out data. A defect the detector misses entirely still comes back as OK, which is why NG recall is the number to gate on. The Academy lesson on training an image classifier shows how to pick a review threshold. You can also train YOLO26 classification, detection and segmentation models without code in Ultralytics Platform cloud training.

Who should use classification, detection, or both#

Start with classification if your station images one part at a time, defects are clearly visible at the training size, and the line only needs a reject signal. Its image-level labels need no drawing, which makes it a quick baseline.

Choose detection if defects are small relative to the frame, you have more than one defect type with different consequences, you need counts or positions in your reject rules, or operators verify each flagged part. For a wider view of how these systems fit on a line, see our overview of automated defect detection in manufacturing and the defect detection solutions page.

Add semantic segmentation for stains, corrosion and other spreading defects where the reject rule is about area. Combine tasks only when one cannot answer the question: every added model adds labeling, validation and monitoring work.

Frequently asked questions

  • Image classification assigns one label to a whole image, such as ok or ng. Object detection finds each object it can in the image and returns a bounding box, a class and a confidence score for each one. For inspection, classification gives you a verdict, while detection also tells you where each detected defect is and how many there are.

  • Choose by the output the line needs. Our visual inspection solution page shows both in production settings. Classification suits fixed stations that image one part at a time, with defects large enough to see at the training size. Detection suits small defects on large surfaces, multiple defect types and any process where a person checks the flagged parts.

  • Label only the defects. OK images go into the detection dataset with an empty or missing label file, and Ultralytics YOLO treats them as background images, so confident predictions on them count as errors. Favor OK images that resemble defects, and judge the model on part-level NG recall and false rejects on a realistic OK/NG mix.

  • Yes. A common pattern detects the part or region of interest first, then classifies each full-resolution crop for a fine-grained call such as defect grade, as the Academy lesson on combining tasks in one pipeline shows. The Classify task docs cover training the second-stage classifier. Train the classifier on crops produced by the detector, so it sees the same framing and blur it will meet in production.

  • Use segmentation when the reject rule depends on a defect's exact shape or affected area, as it often does for water stains, oil films or corrosion. A detector can still locate those defects if location is all you need. Semantic segmentation labels every pixel and answers "how much"; instance segmentation separates individual defects so you can count and measure each one. Our guide to semantic vs instance segmentation covers the choice.

Written by

Jing Qiu
Jing Qiu

Senior Machine Learning Engineer · Ultralytics

Jing Qiu is a Senior Machine Learning Engineer at Ultralytics, focused on improving the performance, scalability, and real-world applicability of state-of-the-art computer vision models. His work spans model architecture, training optimization, and deployment, helping ensure Ultralytics YOLO delivers industry-leading accuracy and efficiency for developers and enterprises worldwide.

Comments

Ask a question, share your results, or help someone else.

Similar articles

Multi-camera computer vision: how to size hardware and scale one detector across many streams

Multi-camera computer vision: how to size hardware and scale one detector across many streams

How many cameras can one device run? Size multi-camera YOLO26 deployments by throughput, decode limits and batching, then measure streams per device.
Learn more
Train, validation and test splits for computer vision: ratios, class balance and leakage

Train, validation and test splits for computer vision: ratios, class balance and leakage

Start at 70/15/15, split by camera or clip, check every class in every split, and score val and test separately with Ultralytics YOLO and Platform.
Learn more
Document layout analysis datasets for historical pages, and why old prints are hard

Document layout analysis datasets for historical pages, and why old prints are hard

Six historical document layout analysis datasets on Ultralytics Platform, from The History of England to a 15th-century music manuscript, compared.
Learn more
Pseudo-labeling for object detection: when a teacher model's labels help and when they hurt

Pseudo-labeling for object detection: when a teacher model's labels help and when they hurt

Unbiased Teacher reached 20.75 COCO mAP50-95 with 1% of images labeled, vs 9.05 supervised. When teacher labels help a detector and when they hurt.
Learn more
How to choose an edge AI device for computer vision, with measured Ultralytics YOLO26 results

How to choose an edge AI device for computer vision, with measured Ultralytics YOLO26 results

Measured YOLO26 results on Jetson, DGX Spark, Raspberry Pi 5 with Hailo-8 or DEEPX, RK3588, Snapdragon, iPhone, Apple M4 and STM32, each with its setup.
Learn more
Ultralytics Platform export options for YOLO26n: TensorRT for a Jetson Orin Nano Super at 4.57 ms and NCNN for a Raspberry Pi 5 CPU at 67.03 ms, from separate published benchmarks

Jetson Orin Nano Super vs Raspberry Pi 5 for YOLO26 object detection

YOLO26n inference: 4.57 ms on a Jetson Orin Nano Super (TensorRT FP16) vs 67.03 ms on a Pi 5 CPU, in separate tests. Choose by model, FPS and cameras.
Learn more
Ultralytics cover for the Azure Custom Vision migration checklist: the Ultralytics Platform New Dataset dialog with a panel mapping Custom Vision detection projects, tagging, training iterations and prediction endpoint to Platform datasets, annotation editor, cloud training and dedicated endpoints

Azure Custom Vision is retiring: a migration checklist for your vision models

Azure Custom Vision retires on September 25, 2028. Plan your migration, export your labeled data and retrain on Ultralytics Platform.
Learn more
Ultralytics Platform export list with the NCNN row highlighted above MNN, the format recommended for running YOLO26 on a Raspberry Pi 5 CPU

Raspberry Pi object detection: YOLO26 on a Pi 5 CPU, no accelerator

YOLO26n runs at 67.03 ms per image with NCNN on a Raspberry Pi 5 CPU, and Arm's open-source runtime measures 36.60 ms in its own test. Here's how to run both.
Learn more
Ultralytics licensing page showing the free AGPL-3.0 card and the paid Ultralytics Enterprise License card

Is Ultralytics YOLO free for commercial use? AGPL-3.0 vs the Enterprise License

Ultralytics YOLO is free under AGPL-3.0 if you open-source your whole project. Compare licensing for internal tools, SaaS and devices.
Learn more
Ultralytics security page cards for ISO/IEC 27001:2022 and SOC 2 Type I, with Ultralytics Platform workspace roles in front, on a gold gradient cover titled Regulated industries

Computer vision for regulated industries: an Ultralytics security review checklist

A security review checklist for computer vision in regulated industries: SOC 2 and ISO 27001 scope, on-premise and air-gapped options, privacy and SLAs.
Learn more
The Ultralytics Platform SAM smart annotation editor segmenting boxes on a warehouse conveyor, with a Batch Annotation estimated cost of $0.05 for 49 images

Budgeting for Image Annotation: Seats, AI and Exports

Compare image annotation software costs, free-plan limits and AI allowances. Estimate software and project costs with a worked three-person team example.
Learn more
Aerial view of a busy intersection with cars boxed by Ultralytics YOLO26s using 640-pixel tiles, dashed lines marking the tile seams

Small object detection with image tiling in Ultralytics YOLO, from Python to Rust

See when image tiling helps YOLO detect small objects, compare its costs, and run built-in tiled inference in Python or Rust without SAHI.
Learn more
A confusion matrix from model evaluation in Ultralytics Platform, beside compare workflows: no-code, developer control and edge export

Best platforms for training custom image classifiers

Image classifier training platforms compared: no-code AutoML, developer platforms and edge tools, and how to choose by control, deployment and cost.
Learn more
A rendered street scene with a bus, cars and people carrying pixel-perfect segmentation labels, beside three methods: simulation, generation and augmentation

Best synthetic data tools for computer vision training

Synthetic data tools for computer vision compared by method: 3D simulation, generative models and augmentation, and how to test them with Ultralytics YOLO.
Learn more
Missing PPE detection: train Ultralytics YOLO on Construction-PPE

Missing PPE detection: train Ultralytics YOLO on Construction-PPE

See how Construction-PPE labels missing helmets, vests and gloves, then train Ultralytics YOLO to detect missing PPE on your own site cameras.
Learn more
Drone detection dataset guide: train Ultralytics YOLO on tiny UAVs

Drone detection dataset guide: train Ultralytics YOLO on tiny UAVs

Compare DUT Anti-UAV, Drone-vs-Bird and thermal drone detection datasets, then train Ultralytics YOLO26 to find tiny drones and cut false alarms.
Learn more
A YOLO26 depth estimation prediction in Ultralytics Platform showing a dense depth map of a street scene with a bus, with timings and depth range

Best Depth Estimation Models: How to Choose

Compare monocular depth models such as Depth Anything, Depth Pro, Metric3D, UniDepth and Ultralytics YOLO26 for metric depth, edge devices and robotics.
Learn more
Two leaves classified as healthy and rust by an image classification model, with confidence scores

Best Image Classification Models: How to Choose

Compare the leading image classification models, from ConvNeXt V2 and DINOv3 to EfficientNetV2, ViT and Ultralytics YOLO26-cls, and learn how to choose.
Learn more
YOLO26 semantic segmentation of a street scene with a bus and people in Ultralytics Platform, each class shown in its own color

Semantic vs Instance Segmentation: How to Choose the Right Task

Semantic segmentation labels every pixel by class; instance segmentation separates each object. Learn which one your computer vision project needs, and why.
Learn more
An engineer with a tablet beside industrial machinery, beside the costs beyond compute: data and labeling, cameras and hardware, integration and operations

What Enterprise Computer Vision Costs: A TCO Framework

A total-cost framework for enterprise computer vision covering data, annotation, cameras, edge hardware, training, inference, integration and retraining.
Learn more
Ultralytics Platform deployment monitoring showing total requests, active deployments and a ready YOLO26 segmentation endpoint

Computer Vision Inference at Scale: Seven Platforms Compared

Seven computer vision inference platforms compared: Azure ML, KServe, NVIDIA Triton, Roboflow, SageMaker AI, Ultralytics and Vertex AI, on latency and scale.
Learn more
Ultralytics Platform SAM smart annotation outlining a leopard, beside two different jobs: propose labels and select useful frames

How to Label Less: Auto-Labeling and Active-Learning Tools Compared

Ten auto-labeling and active-learning tools compared: CVAT, Encord, Label Studio, Labelbox, Lightly, Roboflow, SuperAnnotate, Ultralytics, V7 and FiftyOne.
Learn more
Elevated security-camera view of a city intersection with cars, a bus and pedestrians detected by Ultralytics YOLO26, beside three routes: analytics layer, VMS upgrade and self-hosted models

How to Add AI Analytics to Existing Security Cameras

Three routes to adding AI analytics to existing security cameras: analytics layers, VMS upgrades, or self-hosted models, and the constraints that decide.
Learn more
Metal castings on a conveyor with cracks and damaged parts detected, a magnified crack, and what to test: accuracy on your images, edge deployment and licensing

Choosing a Computer Vision Vendor: An Enterprise Procurement Guide

A procurement view of eight computer vision vendors: AWS, Azure, Cognex, Encord, Landing AI, NVIDIA, Roboflow and Ultralytics, with licensing checks.
Learn more
An edge computing board with a processor, beside where inference runs: managed endpoint, own hardware or hybrid

Managed Cloud vs Self-Hosted Computer Vision Deployment

Compare managed cloud and self-hosted computer vision deployment on cost, latency, data boundaries, scaling and exit risk, with three deployment patterns.
Learn more
A parcel on a modern conveyor detected by Ultralytics YOLOE, beside production readiness steps: validate, integrate, assign owners and monitor

Scaling Computer Vision from Pilot to Production

Six stage gates for taking computer vision from pilot to production, covering coverage matrices, workflow validation, model operations and site readiness.
Learn more
Bottles on a high-speed bottling line under an inspection camera, each detected by Ultralytics YOLO26

Computer Vision Platforms for Manufacturing: YOLO, Cognex and Keyence Compared

Compare computer vision platforms for manufacturing: Cognex, Edge Impulse, Keyence, Landing AI and Ultralytics YOLO, on inspection and MES fit.
Learn more
An Ultralytics Platform dataset gallery of labeled wildlife images, beside the question service or software: managed labeling or annotation software

Scale AI Alternatives for Data Labeling

Alternatives to Scale AI for vision data labeling: iMerit, SuperAnnotate and Ultralytics Platform, compared on cost, control, ramp time and data handling.
Learn more
Overhead view of people passing ticket gates in a bright concourse, detected by Ultralytics YOLO26, beside the four people-counting measurements: entries, occupancy, dwell time and queues

How People Counting and Occupancy Analytics Actually Work

How people counting and occupancy analytics work: comparing WiFi, ToF, thermal and camera-based vision methods, the products available, and how to build it.
Learn more
An industrial robot lifting a tyre from a stack in a warehouse, with the tyre detected by Ultralytics YOLOE

Vision-Guided Robotics for Assembly and Pick-and-Place

How vision-guided pick-and-place works across sensing, perception, calibration, grasp planning, motion and recovery, with a 2D versus 3D decision guide.
Learn more

Let's build the future of AI together!

Begin your journey with the future of machine learning