Building Image Recognition Systems: A Practical Guide
Pick classification, detection or segmentation, start from pretrained or zero-shot models, fine-tune YOLO, label in CVAT, measure mAP and export to OpenVINO.
Most image recognition projects do not need a new architecture. They need the right task definition, a pretrained model, a few hundred well-labelled images, honest evaluation and an export path to the hardware that will run it. This guide walks through each step with the official tools: torchvision and Hugging Face Transformers for pretrained models, CLIP for zero-shot labels, Ultralytics YOLO for detector fine-tuning, CVAT for labelling, and ONNX or OpenVINO for deployment. Code comes from each project’s own documentation.
Choose the task before the model
The output you need decides everything downstream: the labelling effort, the model family and the metric.
| Task | What the model returns | Labels you need | Typical metric |
|---|---|---|---|
| Classification | One label (or a ranked list) for the whole image | One class per image | Accuracy, precision, recall |
| Object detection | A box, class and score for every object | Boxes around each object | mAP50, mAP50-95 |
| Instance segmentation | A pixel mask for each separate object | Polygons or masks per object | Box and mask mAP |
| Semantic segmentation | A class for every pixel, with no split between objects of the same class | Dense masks | Per-class IoU |
If the question is “is there a defect in this photo?”, classification is enough. If it is “where are the defects and how many?”, you need detection. Pick segmentation only when the exact outline matters; masks take more work to label than boxes. Ultralytics’ task overview also covers pose keypoints and rotated boxes (OBB), useful for aerial images where objects sit at an angle.
Start with a pretrained classifier
The torchvision.models package ships architectures for classification, semantic segmentation, detection, instance segmentation and keypoints, each with pretrained weights that download to a local cache on first use. The example below is the documented ResNet-50 classifier, trimmed slightly:
from torchvision.io import decode_image
from torchvision.models import resnet50, ResNet50_Weights
img = decode_image("photo.jpg")
weights = ResNet50_Weights.DEFAULT
model = resnet50(weights=weights)
model.eval()
preprocess = weights.transforms()
batch = preprocess(img).unsqueeze(0)
prediction = model(batch).squeeze(0).softmax(0)
class_id = prediction.argmax().item()
score = prediction[class_id].item()
print(weights.meta["categories"][class_id], score)
Two details matter. First, each weight object bundles its own inference transforms. The docs warn that preprocessing differs between model families and even between weight versions, and getting it wrong can quietly degrade results, so always use weights.transforms() instead of writing your own resize and normalise step. Second, call model.eval(), since layers like batch normalisation behave differently in training mode.
Hugging Face Transformers offers the same idea through pipeline("image-classification", model=...), which the docs present as the simplest way to run a classification checkpoint from the Hub, including one you fine-tuned yourself. Its image classification guide also shows how to fine-tune a ViT on a subset of Food-101.
Pretrained ImageNet labels rarely match a business problem. To adapt the model to your own classes, keep the backbone and retrain the head; the transfer learning guide covers feature extraction versus full fine-tuning, which layers to freeze and how to set learning rates.
One caution from torchvision itself: pretrained weights can carry licence terms inherited from their training data, and it is up to you to confirm you may use them.
Zero-shot labels with CLIP
Sometimes you have no labelled data at all. CLIP, introduced by Radford and colleagues in Learning Transferable Visual Models From Natural Language Supervision, was pretrained to match images with their captions using 400 million image and text pairs. Because it learns a shared space for pictures and text, you can describe new categories in plain words at inference time. The authors report that it matched the original ResNet-50’s ImageNet accuracy zero-shot, without using any of ImageNet’s labelled training images.
In Transformers this is the zero-shot-image-classification pipeline: pass an image and a list of candidate labels, and it returns a score per label. The fashion trend forecasting walkthrough shows that pipeline tagging garment attributes, so it is not repeated here. Treat zero-shot output as a baseline or a pre-labelling aid, and check it against a small hand-labelled sample before trusting it.
Fine-tune a detector with Ultralytics YOLO
For detection, Ultralytics YOLO is the shortest path from labelled boxes to a trained model. Its docs recommend starting from pretrained weights rather than building from a YAML config. The documented training call is three lines:
from ultralytics import YOLO
model = YOLO("yolo26n.pt") # pretrained detection weights
results = model.train(data="coco8.yaml", epochs=100, imgsz=640)
coco8.yaml is a tiny sample dataset that downloads on first use, handy for checking your setup. For your own data, write a dataset YAML listing the train and validation image paths, the class names and the class count, and point data= at it. Training picks GPU 0 when one exists and falls back to CPU otherwise; on Windows, wrap the script in an if __name__ == "__main__": block to avoid a multiprocessing error.
Check the licence before you build a product on it. The repository is licensed AGPL-3.0, and Ultralytics offers a paid Enterprise License for commercial use that is not bound by the AGPL’s open-source terms. If neither suits you, torchvision’s detection models (Faster R-CNN, FCOS, RetinaNet, SSD) are an alternative, though torchvision marks its detection module as Beta with no backward-compatibility guarantee.
Label your data
CVAT is an open-source annotation tool whose community edition is MIT-licensed and self-hosted with Docker Compose, so images stay on your own infrastructure. It handles image, video, audio and 3D annotation, supports roles and review workflows for teams, and lets you plug in your own detection or segmentation models to pre-label frames. Exports cover more than 20 formats, including COCO JSON and Ultralytics YOLO, so labels go straight into the training step above. Note the README’s caveat that some assets in its serverless folder use third-party licences, some non-commercial.
Hold back a validation set before training starts and never tune against it casually; it is the only honest estimate of how the model will behave on new images.
Measure the right thing
For classification, scikit-learn’s metrics module provides the standard definitions. Accuracy is the fraction of predictions that are correct. Precision measures how rarely the model calls a negative sample positive; recall measures how many of the real positives it finds. On imbalanced data, plain accuracy flatters a model that always predicts the common class, so look at balanced_accuracy_score, which averages recall across classes.
Detection adds localisation. Intersection over union (IoU) measures how much a predicted box overlaps the true one. Average precision (AP) is the area under the precision-recall curve for one class, and mAP averages it over classes. Ultralytics’ model.val() reports precision, recall, mAP50 and mAP50-95 per class, and writes precision-recall curves and a confusion matrix to runs/detect/val. Its metrics guide suggests reading them against your use case: favour precision when false alarms are costly, recall when missing an object is worse, and IoU when exact position matters.
Per-class numbers are where problems show up. A healthy overall mAP can hide one class the model barely detects, usually because it has too few or inconsistent labels.
Export for deployment
A PyTorch checkpoint is rarely what runs in production. Ultralytics’ export mode converts a trained model with one call, model.export(format="onnx") or format="openvino", among many other targets including TensorRT, CoreML and LiteRT. The exported model can still be loaded by YOLO(...) for prediction and validation, so you can confirm accuracy survived the conversion. Arguments such as quantize and dynamic control precision and input shapes.
OpenVINO is Intel’s toolkit for optimising and serving inference on Intel CPUs, GPUs and NPUs. It reads PyTorch, ONNX, TensorFlow, TensorFlow Lite and PaddlePaddle models. Its docs recommend converting explicitly to OpenVINO IR (an .xml and .bin pair) for production rather than relying on automatic conversion at load time. For a torchvision model the documented route is:
import openvino as ov
import torch
from torchvision.models import resnet50
model = resnet50(weights="DEFAULT")
ov_model = ov.convert_model(model, example_input=torch.rand(1, 3, 224, 224))
ov.save_model(ov_model, "model.xml")
PyTorch models can only be converted through the Python API; for other source formats the ovc command-line tool is an alternative. Whatever you export, rerun your validation set on the converted model, especially after quantising.
Where projects usually go wrong
- Preprocessing drift: the serving code resizes or normalises differently from training. Reuse the model’s own transforms everywhere.
- Leaky splits: near-duplicate frames from the same video end up in both train and validation sets, inflating every metric.
- Licence surprises: pretrained weights, YOLO’s AGPL terms and third-party labelling assets each carry their own conditions.
- One headline number: report per-class precision and recall alongside mAP or accuracy, and test on images from the real camera and lighting.
Written by AI Agents Directory
Editorial team
Facts in this guide are checked against official documentation and repositories, which are linked in the article.