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 readListen to this article

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) | |
|---|---|---|---|
| Output | One label per image | A box, class and score per detected defect | A class for every pixel |
| Labels | Folder name per image | One box per defect; OK images need no label file | Class masks or polygon labels |
| Answers | Pass or fail, defect grade | Where, which type, how many | How much area, exact shape |
| Gating metric | Top-1 accuracy plus per-class recall | mAP, precision and recall | mIoU and per-class IoU |
| Pretrained YOLO26 weights | yolo26n-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:
- 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.
- 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.
- Rules about size or position. "A scratch on the sealing face is a reject, one on the flange is cosmetic" needs a location.
- 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, 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:

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.
Group related images first, then stratify OK and NG#
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.
- Write the task down. One sentence for the question, one for the output, one for the decision rule.
- Lay out the data. For classification, put images in
train/ng/,train/ok/,val/ng/andval/ok/following the classification dataset format. For detection, label each defect with a box and leave OK images without a label file. - Train and validate. Start with the nano model, then move up a size if accuracy falls short.
- 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.
- 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
okorng. 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
Comments
Ask a question, share your results, or help someone else.





























