Artificial Intelligence • AI Application Domains • 12 min read

Image Classification, Detection, and Segmentation

Start with an example: Three questions about one street photograph

Imagine a street photograph containing a car, a pedestrian, and a traffic sign. An image classifier may answer “This image contains a car.” An object detector can locate the car with a bounding box. A segmentation system can label which individual pixels belong to the car or the road.

These are different outputs, not simply three accuracy levels of one prediction. For example, if a navigation system must identify the drivable road surface, the label “road present” is not enough: it needs spatial detail. If a photo-organizing app merely sorts pictures by subject, image classification may be sufficient.

Start every vision project by asking what decision the output will support. That answer tells you whether you need image-level labels, object boxes, or pixel-level annotations.

A computer vision system may need to answer three very different questions about an image: What is present? Where is it? Which pixels belong to it? These questions lead to three central computer vision tasks: image classification, object detection, and image segmentation.

All three can use neural networks, but they require different target annotations, outputs, evaluation methods, and levels of spatial detail. Selecting the right task is an important part of formulating an AI problem.

1. Three levels of visual understanding

Image classification assigns one or more category labels to an image. Object detection identifies objects and estimates their locations, usually with bounding boxes. Image segmentation assigns labels or object memberships to individual pixels.

TaskMain questionTypical model outputExample
ClassificationWhat category does this image belong to?Class scores or labels“This image contains a dog”
DetectionWhat objects are here, and where?Class, confidence, bounding box per detection“Dog at these coordinates”
Semantic segmentationWhat class does each pixel belong to?Per-pixel class map“These pixels are road; those are sidewalk”
Instance segmentationWhich pixels belong to each separate object?Per-object masks, classes, and often scores“These pixels belong to dog 1; those belong to dog 2”

A classification model cannot reliably provide object coordinates just because it predicts “dog.” Similarly, a bounding box does not describe the exact outline of an object.

Comparison of image classification, object detection, and instance segmentation on an illustration containing two objects
Three tasks can examine the same scene but describe it at different levels of spatial precision. This illustration is conceptual, not actual model output.

2. Image classification

An image classifier learns a mapping from an input image to a category or a set of categories. It typically produces numerical scores that are transformed into probabilities or used to rank candidate classes.

Single-label and multilabel classification

In single-label classification, each example belongs to one of several mutually exclusive categories, such as handwritten digits from 0 to 9. A model commonly uses a softmax output and a multiclass classification loss.

In multilabel classification, an image can have several simultaneously valid labels: for example, person, bicycle, and tree. Models commonly produce independent per-label scores using sigmoid outputs, with a suitable multilabel loss.

Do not confuse these with binary classification, where a single decision has two possible classes. A binary classifier may answer whether an X-ray contains a particular finding, though real clinical deployment needs additional validation and oversight.

Classification workflow

  1. Collect representative images and define a consistent label vocabulary.
  2. Divide data into training, validation, and test sets while avoiding overlap or near-duplicate leakage.
  3. Resize and normalize images according to the model’s required preprocessing.
  4. Train or fine-tune a classifier using labeled examples.
  5. Evaluate performance on data not used for training decisions.
  6. Check performance across relevant lighting, devices, backgrounds, and subgroups.

What a classifier actually learns

A convolutional network or vision transformer builds numerical representations of visual patterns. Its final prediction head maps those representations to scores for the selected classes. A network may exploit shapes and textures, but it may also learn accidental correlations, such as a background frequently appearing with one label.

A high confidence score is not proof that the prediction is correct. Calibration and error analysis are separate evaluation concerns.

3. Object detection

Object detection locates and classifies individual visible objects. A typical detection consists of a class label, a confidence score, and a bounding box.

A box may be represented as (xmin⁡,ymin⁡,xmax⁡,ymax⁡)(x_{\min}, y_{\min}, x_{\max}, y_{\max}), where coordinates specify opposite corners, or as (x,y,w,h)(x, y, w, h) for position, width, and height. Libraries and datasets differ in whether coordinates are absolute pixels or normalized values. Always verify the expected format.

How detection works conceptually

Many contemporary detectors use a shared image feature extractor followed by a detection head. The system predicts candidate object classes and locations, then produces a set of final detections. Some designs use anchors or region proposals; others use anchor-free predictions or learned object queries. The details vary substantially by architecture.

Detectors often need a way to handle multiple overlapping predictions. Non-maximum suppression (NMS) is one common method: it suppresses redundant overlapping boxes, often keeping a high-scoring candidate. Not every detector relies on NMS.

Intersection over Union

Intersection over Union (IoU) measures how much two regions overlap relative to the area they cover together. For bounding boxes AA and BB:

IoU⁡(A,B)=∣A∩B∣∣A∪B∣\operatorname{IoU}(A,B)=\frac{|A\cap B|}{|A\cup B|}

Suppose two boxes have an intersection area of 4040 pixels squared and a combined union area of 100100 pixels squared. Their IoU is 0.400.40.

An IoU threshold may be used when deciding whether a predicted detection adequately matches an annotated object. IoU alone does not tell you whether the predicted class is correct.

Detection challenges

Small objects may have few useful pixels. Occlusion can hide distinguishing features. Crowded scenes make it hard to separate adjacent objects. Motion blur, unusual viewpoints, and changing illumination can also reduce performance. Increasing input resolution sometimes helps small objects, but usually increases computation and memory use.

4. Image segmentation

Segmentation divides an image into pixel-level regions based on their meaning or object membership. Its output is more spatially detailed than an ordinary bounding box.

Semantic segmentation

A semantic segmentation system assigns each pixel a class. All pixels representing roads may receive the same label, even if separate road regions appear in the image. Pixels belonging to two different dogs typically share the label dog, without identifying which dog is which.

For an image of height HH and width WW, a semantic segmentation model may output a score tensor of shape C×H×WC\times H\times W, where CC is the number of semantic classes. A class can be selected for each pixel from those scores.

Instance segmentation

Instance segmentation distinguishes separate object instances and estimates a mask for each. Two dogs are not merged into a single undifferentiated dog region. The model typically outputs class labels, per-instance masks, and confidence scores.

Panoptic segmentation

Panoptic segmentation combines semantic segmentation with instance-aware identification. It assigns every pixel a semantic category and, when applicable, an instance identifier. Its distinction between countable objects (things, such as cars) and amorphous regions (stuff, such as sky) is useful in complex scene understanding.

Annotation costs

Classification usually needs image-level labels. Detection typically needs boxes around instances. Segmentation often needs manually drawn pixel masks or polygon annotations. More detailed annotation is often more expensive, and noisy boundaries can affect evaluation.

5. Comparing outputs and data requirements

ConsiderationClassificationDetectionSegmentation
AnnotationImage-level label(s)Object-level bounding boxes and classesPixel masks and classes; sometimes instance IDs
Spatial precisionNo explicit locationApproximate locationPixel-level region
Typical useProduct categoryCount and locate productsMeasure covered area or contours
Typical metricAccuracy, macro-F1Average precision and mAPMean IoU, Dice; task-specific instance AP
Common errorWrong categoryMissed, duplicate, or misplaced objectsIncorrect mask or boundary

Greater spatial detail does not automatically mean a better system. If the application only needs to classify a product image, collecting pixel masks may add cost without improving the required answer.

6. Evaluating classification, detection, and segmentation

A model needs evaluation metrics matched to its actual output and application.

Classification metrics

Accuracy is the proportion of correct predictions, but it may be misleading on imbalanced datasets. Precision, recall, and F1-score help describe different error costs. For multilabel tasks, decide whether metrics are averaged over labels or evaluated across individual label decisions.

Detection metrics

Detection evaluation matches predictions to ground-truth objects using category labels, IoU thresholds, and a matching procedure. Precision–recall curves describe how behavior changes with detection score thresholds. Average Precision (AP) summarizes precision–recall performance for a particular class and evaluation convention; mean Average Precision (mAP) averages AP values under a defined protocol. Always specify the protocol: for example, AP at IoU 0.500.50 differs from COCO-style AP averaged across multiple IoU thresholds.

Segmentation metrics

For two masks, IoU measures the proportion of overlapping area relative to their union. The Dice coefficient, a related overlap metric, is:

Dice⁡(A,B)=2∣A∩B∣∣A∣+∣B∣\operatorname{Dice}(A,B)=\frac{2|A\cap B|}{|A|+|B|}

Semantic segmentation commonly reports mean IoU across classes. Instance segmentation often uses detection-like average precision, but evaluates mask overlap rather than box overlap. Panoptic segmentation has specialized metrics, including panoptic quality.

An evaluation report should explain whether ignored pixels, empty classes, boundary uncertainty, and class imbalance were handled, rather than reporting one unexplained number.

7. Practical Python example: Classify images with a pretrained model

The following example shows inference, not training. It uses a pretrained ImageNet classifier from torchvision and its associated preprocessing transforms. It requires Python, PyTorch, torchvision, an image file, and an initial download of model weights.

pip install torch torchvision pillow
from pathlib import Path

import torch
from PIL import Image
from torchvision.models import ResNet18_Weights, resnet18

image_path = Path("example.jpg")
if not image_path.is_file():
    raise FileNotFoundError(image_path)

weights = ResNet18_Weights.DEFAULT
model = resnet18(weights=weights)
model.eval()

preprocess = weights.transforms()
image = Image.open(image_path).convert("RGB")
batch = preprocess(image).unsqueeze(0)

with torch.inference_mode():
    logits = model(batch)
    probabilities = torch.softmax(logits, dim=1)[0]
    scores, indices = torch.topk(probabilities, k=5)

categories = weights.meta["categories"]
for score, index in zip(scores.tolist(), indices.tolist()):
    print(f"{categories[index]}: {score:.3f}")

The code produces five ranked ImageNet class labels and their softmax scores. These scores reflect the model’s relative output distribution for its predefined classes. They are not guaranteed to be calibrated probabilities of correctness. If the image contains a class not represented in the model’s vocabulary, the classifier will still typically assign scores to its available categories.

From classification code to detection and segmentation

Detection and segmentation usually require a different model architecture, weight set, preprocessing, and output handling. A detection model might return a dictionary containing boxes, labels, and scores. An instance segmentation model may additionally return masks. Output structures depend on the library and model; do not assume the same interface works for every architecture.

For official implementations and current APIs, use the PyTorch torchvision object-detection and instance-segmentation tutorial.

8. Choosing the appropriate task

Consider a warehouse system that processes images of stored packages.

  • If the goal is to decide whether an image shows a damaged package, image classification may be sufficient.
  • If the goal is to find and count each package, object detection is more appropriate.
  • If the goal is to measure the exact visible damaged area, segmentation can provide the required region-level estimate.

A complete application might combine tasks, such as using detection to crop a package before a second model classifies its condition. This is a design decision, not a mandatory sequence.

Before deciding, define the required output, annotation budget, acceptable error rates, inference latency, and operational environment. Model evaluation should reflect those constraints.

9. Common implementation mistakes

Data leakage and misleading test sets

Near-duplicate images from the same video or object can make test performance look better than real-world generalization. Split related images by source, subject, location, or time when appropriate. See Data Splitting, Labeling, and Leakage.

Inconsistent preprocessing

A pretrained model may expect a particular color order, input size, channel normalization, and tensor shape. Incorrect preprocessing can degrade predictions without producing a software error.

Confusing localization with segmentation

A tight box is still not a pixel mask. A segmentation mask describes shape more precisely, but can be wrong at boundaries or for transparent and overlapping objects.

Ignoring deployment constraints

High-resolution detection and segmentation may be computationally expensive. Evaluate memory use, model size, and latency on the intended hardware, especially for edge and embedded deployment.

Assuming visual predictions are always reliable

Computer vision models may fail under distribution shift, such as new cameras, weather, lighting, or image compression. Sensitive applications need stronger dataset validation, uncertainty handling, monitoring, and appropriate human oversight.

10. Connections to other AI concepts

These tasks sit within Computer Vision Fundamentals, where images, pixels, preprocessing, and visual features are introduced. Many modern vision systems use Convolutional and Recurrent Neural Networks or attention-based architectures. Their training depends on Neural Network Fundamentals, Forward Propagation and Backpropagation, and Training Neural Networks.

For implementation practice, continue with Deep Learning with PyTorch. For understanding errors, review Evaluating Machine Learning Models.

11. Questions to test your understanding

  1. Why is an image classifier insufficient for counting multiple objects in a crowded scene?
  2. How does an instance segmentation mask differ from a semantic segmentation label map?
  3. Why must an object detection benchmark define an IoU threshold or matching protocol?
  4. What would you evaluate besides mean IoU in a safety-sensitive segmentation application?
  5. When might classification be preferable to segmentation even if segmentation is technically possible?

References and further reading

Related articles in

Image preview

Fit