...

YOLOv8 Tutorial: Build a Car Image Classifier

YOLOv8 image classification

Last Updated on 14/10/2025 by Eran Feit

Understanding YOLOv8 — The Next Generation of Object and Image Classification

YOLOv8, developed by Ultralytics, represents the latest evolution of the renowned “You Only Look Once” family of deep learning models for object detection, segmentation, and classification.
It’s a highly efficient, real-time architecture that balances speed, accuracy, and ease of use, making it one of the most powerful computer vision frameworks available today — and the focus of this YOLOv8 tutorial.

Unlike older versions such as YOLOv5 or YOLOv7, YOLOv8 introduces a redesigned architecture, improved training stability, and support for multiple tasks including detection, segmentation, and classification—all under one unified interface.
With just a few lines of Python code, developers can load pre-trained models or fine-tune them on custom datasets using either the command line or the Python API, exactly as demonstrated in this YOLOv8 tutorial.

One of the standout features of YOLOv8 is its auto-anchor generation and dynamic input shapes, allowing it to adapt to varying image sizes without manual configuration.
It also includes advanced loss functions, model pruning, and export options to formats like ONNX, TensorRT, and CoreML—making it production-ready for deployment across devices.

For image classification tasks, YOLOv8 offers “-cls” models that specialize in classifying entire images instead of detecting bounding boxes.
This makes it perfect for use cases like car make and model recognition, animal species identification, or quality inspection in manufacturing, as covered step-by-step in this YOLOv8 tutorial.

In short, YOLOv8 is not just an update—it’s a complete rethinking of YOLO, designed for both researchers and industry developers who want state-of-the-art performance with minimal effort.
If you’re looking to master computer vision workflows efficiently, this YOLOv8 tutorial will guide you through everything from installation to training and inference.

image 1
YOLOv8 Tutorial: Build a Car Image Classifier 5

YOLOv8 Image classification tutorial

This post will walk you through YOLOv8 image classification from ground up — installing dependencies, training on a 196-class car dataset, doing inference with Python, and showing results with OpenCV.
You’ll get code broken into parts with explanations, internal link suggestions, and Q&A + FAQ schema.
By the end, you’ll clearly understand how the code works and how to adapt it for your use case — whether cars or any custom dataset.

Getting Started: What This YOLOv8 Car Classifier Code Does

Let’s begin with an overview: the code is aimed at training a YOLOv8 model (via the Ultralytics library) to classify images of cars into 196 categories (e.g. car makes/models).
Then it runs inference on a sample image, prints predicted probabilities and class names, and displays the result with OpenCV.

At a high level:

  • You set up a Python environment with pytorch, CUDA, ultralytics, and OpenCV.
  • You organize the dataset in a folder structure of train/, val/ with subfolders for each class.
  • You call model.train(...) on your dataset.
  • Then reload the best weights and run prediction on a test image.
  • You extract class probabilities, find the highest, annotate, and show the image.

This covers the full flow: install → train → infer → visualize.
It’s a complete pipeline for YOLOv8 classification use case.

You can find more tutorials in my blog : https://eranfeit.net/blog/

You can download the dataset here : https://www.kaggle.com/datasets/jutrera/stanford-car-dataset-by-classes-folder


Installation & Environment Setup (Dependencies & CUDA)

This part ensures your environment is ready with the right versions of Python, CUDA, PyTorch, Ultralytics, and OpenCV.

# Create and activate a conda environment   conda create --name YoloV8 python=3.8   conda activate YoloV8    nvcc --version    # Install PyTorch + CUDA support   conda install pytorch==2.1.1 torchvision==0.16.1 torchaudio==2.1.1 pytorch-cuda=11.8 -c pytorch -c nvidia    # Install YOLOv8 (Ultralytics)   pip install ultralytics==8.1.0    # Fix OpenCV installation   pip uninstall opencv-python-headless -y   pip install opencv-python>=4.6.0   

Summary: We’re pinning versions (Python 3.8, PyTorch 2.1.1, CUDA 11.8, Ultralytics 8.1.0) to ensure compatibility.
The OpenCV step ensures we have GUI support to show images.

Dataset Folder Structure for YOLOv8 Classification

Make sure your dataset follows this structure before training — each category should be a separate folder containing its images under both train and val directories.

📁 data/  ├── 📁 train/ │   ├── 📁 category1/ │   │   ├── image1.jpg │   │   ├── image2.jpg │   │   └── ... │   │ │   ├── 📁 category2/ │   │   ├── image1.jpg │   │   ├── image2.jpg │   │   └── ... │   │ │   ├── 📁 category3/ │   └── 📁 category4/  └── 📁 val/     ├── 📁 category1/     ├── 📁 category2/     ├── 📁 category3/     └── 📁 category4/ 

Tip:
In YOLOv8 classification, the folder names (e.g., category1, category2, etc.) automatically become your class labels.
This structure is essential for model.train() to correctly load and map your classes.


Training Setup: Main Function & Training Call

This part is where you define the training routine and invoke YOLOv8’s .train method.

from ultralytics import YOLO  def main():     model = YOLO('e:/models/yolov8l-cls.pt')  # load the Yolo Large pre-trained model      datasetPath = "C:/Data-sets/Stanford Car Dataset/car_data/car_data"      batch_size = 16     project = "C:/Data-sets/Stanford Car Dataset/car_data"     experiment = "My-model"      results = model.train(         data = datasetPath,         epochs = 30,         project = project,         name = experiment,         batch = batch_size,         device = 0,         imgsz = 640,         patience = 5,         verbose = True,         val = True     )  if __name__ == "__main__":     main() 

Here’s what’s happening:

Explanation:

  • model = YOLO('...-cls.pt'): loads a classification variant of YOLOv8 (the “-cls” suffix) as a starting pre-trained model.
  • model.train(...): starts training on your dataset. You configure epochs, batch size, image size, etc.
  • device = 0 picks GPU number 0.
  • patience = 5 gives early stopping tolerance if validation loss doesn’t improve.
  • val = True tells it to use validation during training.

Summary: this part defines the training configuration and triggers YOLOv8 training on your dataset of 196 classes.


Inference & Prediction with YOLOv8

After training, you move to inferencing a single image using the saved model.

The test image :

Test Image for classification
YOLOv8 Tutorial: Build a Car Image Classifier 6
from ultralytics import YOLO import numpy as np import cv2  # load the model model = YOLO("C:/Data-sets/Stanford Car Dataset/car_data/My-model/weights/best.pt") imgPth = "Best-image-classification-models/YoloV8-196-cars-classification/chevrolet-cobalt-ss-supercharged.jpg"  # predict results = model(imgPth)  names_dict = results[0].names print("Categories : ") print(names_dict) print("*************************************************")  probs = results[0].probs.data.tolist() print("All predictions :") print(probs) print("*************************************************")  print("The predicted class is : ") text = "Predicted category :" + names_dict[np.argmax(probs)]  print(text) 

Explanation

  • model = YOLO(...best.pt): loads your trained weights.
  • results = model(imgPth): runs inference on the image path (returns a list of result objects).
  • results[0].names: dictionary mapping class indices to names.
  • results[0].probs.data.tolist(): gets probability scores for each class.
  • np.argmax(probs): finds the class index with highest probability.

Summary: given a model and an image, this block prints class names, probabilities, and the final predicted class.


Visualization: Annotating & Displaying the Result

This part overlays the predicted class text on the image and displays it using OpenCV.

# continuing from above # display the image  imgDisplay = cv2.imread(imgPth) cv2.putText(     imgDisplay,     text,     (10, 30),     cv2.FONT_HERSHEY_SIMPLEX,     0.5,     (0, 255, 0),     1 )  cv2.imshow("img", imgDisplay) cv2.waitKey(0) cv2.destroyAllWindows() 

Explanation

  • cv2.imread(imgPth): reads the image into an OpenCV array.
  • cv2.putText(...): overlays the predicted text in green at position (10,30).
  • cv2.imshow(...): shows the window with the image.
  • cv2.waitKey(0): waits until a key press.
  • cv2.destroyAllWindows(): closes the window.

Summary: you visually see the prediction on the image in a GUI window—great for local testing.


FAQ Section

What dataset format must I use for YOLOv8 classification?

Use a folder structure with train/ and val/ subfolders, each containing one folder per class of images.

Why load a “-cls.pt” model?

The -cls version is built for classification (no bounding boxes), optimized for class prediction.

What does patience=5 do in training?

It enables early stopping if validation loss doesn’t improve for 5 epochs.

How do I pick imgsz (image size)?

Choose a square dimension (e.g. 640) — YOLO will pad or resize images accordingly.

How do I interpret results[0].probs?

It’s a list of probabilities (floats) for each class for the input image.

What if inference fails or outputs all zeros?

Likely mismatched class count or wrong weights; verify model class count and weights.

Can I use CPU instead of GPU?

Yes, set device='cpu', but inference/training will be much slower.

How to save more than best.pt (e.g. every epoch)?

You can configure the save or save_freq parameters in model.train.

Can I fine-tune the model instead of full training?

Yes, load a pre-trained -cls model and train additional epochs to adapt to your dataset.

How to batch inference for multiple images?

Pass a list of image paths (or folder) to model([...]); YOLOv8 handles batching internally.


Conclusion & Best Practices

Summary of the Full Pipeline

  • Installation: set up the right Python / CUDA / library versions.
  • Training setup: choose pre-trained model, dataset path, and train configurations.
  • Inference logic: load trained model, run prediction, extract probabilities and class.
  • Visualization: overlay predicted label onto image and display it to the user.

You now have a functioning YOLOv8 classification pipeline for your 196-class car dataset.

Here are a few extra tips to maximize success:

  • Always verify the number of classes in your dataset matches what the model expects.
  • Monitor validation loss and accuracy, and use patience to avoid overfitting.
  • Use data augmentation (e.g. flips, color jitter) to increase training robustness.
  • To speed up inference, consider converting the model to ONNX, TensorRT, or use quantization.
  • For production deployment, embed this into a web or mobile app, not via OpenCV GUI.

Have fun experimenting with other datasets (animals, plants, etc.) — the same pipeline works broadly for YOLOv8 image classification.


Connect :

☕ Buy me a coffee — https://ko-fi.com/eranfeit

🖥️ Email : feitgemel@gmail.com

🌐 https://eranfeit.net

🤝 Fiverr : https://www.fiverr.com/s/mB3Pbb

Enjoy,

Eran

Leave a Comment

Your email address will not be published. Required fields are marked *

error: Content is protected !!
Eran Feit