Skip to main content

Deep Learning with OpenCV DNN Module

Learn how to use OpenCV’s DNN (Deep Neural Networks) module to load and run pre-trained models for object detection, classification, and more.

Introduction to OpenCV DNN

OpenCV’s DNN module allows you to:
  • Load models from TensorFlow, PyTorch, Caffe, ONNX, and Darknet
  • Run inference without installing deep learning frameworks
  • Deploy on CPU, GPU (CUDA), or OpenVINO backends
  • Use pre-trained models for various tasks

Supported Frameworks

  • ONNX (.onnx) - Universal format, recommended
  • TensorFlow (.pb, .pbtxt)
  • PyTorch (via ONNX export)
  • Caffe (.caffemodel, .prototxt)
  • Darknet (.weights, .cfg) - YOLO models
  • TensorFlow Lite (.tflite)

Loading and Running Models

Basic Model Loading

YOLO Object Detection

YOLO (You Only Look Once) is a popular real-time object detection system.

YOLOv3/YOLOv4 Detection

YOLOv8 with ONNX

Modern YOLO versions export to ONNX format:

SSD Object Detection

SSD (Single Shot MultiBox Detector) for faster detection:

Image Classification

Face Detection with DNN

Deep learning-based face detection (more accurate than Haar cascades):

Video Processing with DNN

Performance Optimization

Backend and target options:
  • DNN_BACKEND_OPENCV + DNN_TARGET_CPU: Default, works everywhere
  • DNN_BACKEND_CUDA + DNN_TARGET_CUDA: NVIDIA GPU acceleration
  • DNN_BACKEND_INFERENCE_ENGINE + DNN_TARGET_CPU: Intel OpenVINO
  • DNN_TARGET_OPENCL: OpenCL acceleration
  • DNN_TARGET_CUDA_FP16: Half-precision for faster inference
Common issues:
  • Model input size must match the size used during training
  • Check if the model expects RGB or BGR input (use swapRB parameter)
  • Normalize input values correctly (typically 0-1 or mean subtraction)
  • Ensure OpenCV is built with the desired backend support

Downloading Pre-trained Models

OpenCV provides scripts to download common models:
Common model sources:

Next Steps