Skip to main content
Image classification is the task of assigning a label or category to an entire image. OpenCV’s DNN module provides support for running pre-trained classification models from various frameworks.

Supported Models

The following classification models are commonly used:
  • ResNet - Deep residual networks with skip connections
  • MobileNet - Lightweight models optimized for mobile devices
  • GoogLeNet - Inception architecture from Google
  • SqueezeNet - Compact model with high accuracy
  • VGG - Very deep convolutional networks

Python Implementation

1

Import Libraries

2

Load the Model

You can use DNN_BACKEND_CUDA and DNN_TARGET_CUDA for GPU acceleration if available.
3

Load Class Names

4

Prepare Input Image

The blobFromImage function performs:
  • Mean subtraction
  • Scaling
  • Optional channel swapping (BGR to RGB)
  • Resizing to target dimensions
5

Run Inference

6

Visualize Results

C++ Implementation

Model Download and Configuration

GoogLeNet (Caffe)

Download: http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel

SqueezeNet (Caffe)

Download: https://github.com/DeepScale/SqueezeNet (SqueezeNet v1.1)

Preprocessing Parameters

Different models require different preprocessing parameters:
ModelInput SizeMeanScaleRGB Order
GoogLeNet224x224[104, 117, 123]1.0BGR
SqueezeNet227x227[0, 0, 0]1.0BGR
ResNet224x224[103.94, 116.78, 123.68]1.0BGR
MobileNet224x224[127.5, 127.5, 127.5]0.007843RGB

Backend and Target Options

Available Backends

Available Targets

When using CUDA backend, ensure you have compiled OpenCV with CUDA support and the appropriate CUDA toolkit installed.

Complete Example

Here’s a complete classification example that processes video frames:

Source Code

The complete source code for classification examples can be found in the OpenCV repository:
  • Python: samples/dnn/classification.py
  • C++: samples/dnn/classification.cpp