OpenCV
SVM
Machine Learning
Image Processing
Computer Vision

Opencv 3 SVM training

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

OpenCV 3 includes an SVM implementation in the cv2.ml module that is useful for classical machine-learning tasks such as digit classification, feature-based object recognition, and small computer-vision pipelines. The important part is preparing the training matrix correctly: OpenCV expects floating-point feature rows and integer labels. Most training failures come from data shape or data type mistakes rather than from the SVM parameters themselves.

Training A Basic SVM In OpenCV 3

A minimal example uses a small synthetic dataset with two classes.

python
1import numpy as np
2import cv2
3
4train_data = np.array(
5    [
6        [1.0, 2.0],
7        [1.5, 1.8],
8        [5.0, 8.0],
9        [8.0, 8.0],
10    ],
11    dtype=np.float32,
12)
13labels = np.array([0, 0, 1, 1], dtype=np.int32)
14
15svm = cv2.ml.SVM_create()
16svm.setType(cv2.ml.SVM_C_SVC)
17svm.setKernel(cv2.ml.SVM_LINEAR)
18svm.setTermCriteria((cv2.TERM_CRITERIA_MAX_ITER, 100, 1e-6))
19
20svm.train(train_data, cv2.ml.ROW_SAMPLE, labels)
21
22sample = np.array([[2.0, 2.0]], dtype=np.float32)
23_, prediction = svm.predict(sample)
24print(prediction)

This is the core workflow:

  • create the SVM object
  • choose type and kernel
  • train with feature rows and labels
  • predict on new samples

Data Shape And Type Requirements

OpenCV is strict about training input. Each row in the feature matrix must represent one sample, and the matrix should usually be np.float32.

Labels should be an integer array.

python
1print(train_data.dtype)
2print(train_data.shape)
3print(labels.dtype)
4print(labels.shape)

If your features come from images, flatten or otherwise transform them into numeric feature vectors first.

python
1import numpy as np
2
3image = np.arange(16, dtype=np.float32).reshape(4, 4)
4feature_vector = image.reshape(1, -1)
5print(feature_vector.shape)

For image classification, SVM usually works better with engineered descriptors such as HOG than with raw pixels, especially when the dataset is small.

Choosing Kernel And Parameters

The main kernel choices are linear, RBF, polynomial, and sigmoid. A linear kernel is the easiest place to start.

python
svm.setKernel(cv2.ml.SVM_RBF)
svm.setC(2.0)
svm.setGamma(0.5)

For an RBF kernel, C and gamma matter a lot. Higher C penalizes classification errors more strongly, while gamma controls how far the influence of one sample extends.

For small real datasets, cross-validation is important. A training script that works on a toy example may overfit badly once real features are used.

Saving And Loading The Model

OpenCV 3 can serialize trained SVM models.

python
1svm.save("svm_model.xml")
2loaded = cv2.ml.SVM_load("svm_model.xml")
3
4_, prediction = loaded.predict(np.array([[7.0, 7.0]], dtype=np.float32))
5print(prediction)

This is useful for separating training from inference.

When OpenCV SVM Is A Good Fit

OpenCV's SVM is a good fit when your pipeline already lives in OpenCV and the feature engineering step is classical computer vision rather than deep learning. Examples include:

  • HOG plus SVM for object or character recognition
  • texture classification with handcrafted descriptors
  • simple binary classifiers embedded in an image-processing pipeline

If your workflow is mostly generic tabular machine learning, scikit-learn may be more convenient. If your workflow is deep learning, TensorFlow or PyTorch is usually more appropriate.

Common Pitfalls

The most common mistake is passing integer feature arrays or the wrong shape into svm.train. OpenCV usually expects a float32 matrix with one sample per row.

Another frequent issue is training on raw image arrays without first converting them into meaningful feature vectors. SVM is not magic; feature representation still matters.

Developers also often choose an RBF kernel immediately without tuning C and gamma. Start simple and validate.

Finally, do not evaluate the model only on the training set. An apparently perfect training score may only mean the classifier memorized the data.

Summary

  • OpenCV 3 SVM training uses the cv2.ml API.
  • Features should usually be stored as np.float32 with one sample per row.
  • Labels should be integer class values.
  • Start with a linear kernel before moving to RBF and parameter tuning.
  • Use engineered features, not just raw pixels, for most classical vision tasks.
  • Validate on held-out data and save the trained model for inference reuse.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.