[code segments] OpenCV3.0 SVM with C++ interface

talk is cheap, show you the code:

/************************************************************************/
/* Name   : OpenCV SVM test                                             */
/* Date   : 2015/11/7                                                   */
/* Author : aban                                                        */
/************************************************************************/
// note : the code is modified from internet. 

#include <iostream>
#include <cmath>
#include <string>
using namespace std;

#include <opencv2/opencv.hpp>
#include <opencv2/ml.hpp>
using namespace cv;

bool plotSupportVectors = true;
int numTrainingPoints = 200;
int numTestPoints = 2000;
int size = 200;
int eq = 0;

// accuracy
float evaluate(cv::Mat& predicted, cv::Mat& actual) {
  assert(predicted.rows == actual.rows);
  int t = 0;
  int f = 0;
  for (int i = 0; i < actual.rows; i++) {
    float p = predicted.at<float>(i, 0);
    float a = actual.at<float>(i, 0);
    if ((p >= 0.0 && a >= 0.0) || (p <= 0.0 &&  a <= 0.0)) {
      t++;
    }
    else {
      f++;
    }
  }
  return (t * 1.0) / (t + f);
}

// plot data and class
void plot_binary(cv::Mat& data, cv::Mat& classes, string name) {
  cv::Mat plot(size, size, CV_8UC3);
  plot.setTo(cv::Scalar(255.0, 255.0, 255.0));
  for (int i = 0; i < data.rows; i++) {

    float x = data.at<float>(i, 0) * size;
    float y = data.at<float>(i, 1) * size;

    if (classes.at<float>(i, 0) > 0) {
      cv::circle(plot, Point(x, y), 2, CV_RGB(255, 0, 0), 1);
    }
    else {
      cv::circle(plot, Point(x, y), 2, CV_RGB(0, 255, 0), 1);
    }
  }
  cv::namedWindow(name, CV_WINDOW_KEEPRATIO);
  cv::imshow(name, plot);
}

// function to learn
int f(float x, float y, int equation) {
  switch (equation) {
  case 0:
    return y > sin(x * 10) ?

-1 : 1;
    break;
  case 1:
    return y > cos(x * 10) ? -1 : 1;
    break;
  case 2:
    return y > 2 * x ?

-1 : 1;
    break;
  case 3:
    return y > tan(x * 10) ?

-1 : 1;
    break;
  default:
    return y > cos(x * 10) ?

-1 : 1;
  }
}

// label data with equation
cv::Mat labelData(cv::Mat points, int equation) {
  cv::Mat labels(points.rows, 1, CV_32FC1);
  for (int i = 0; i < points.rows; i++) {
    float x = points.at<float>(i, 0);
    float y = points.at<float>(i, 1);
    labels.at<float>(i, 0) = f(x, y, equation);
  }
  return labels;
}

void svm(cv::Mat& trainingData, cv::Mat& trainingClasses, cv::Mat& testData, cv::Mat& testClasses) {

  Mat traning_label(trainingClasses.rows, 1, CV_32SC1);
  for (int i = 0; i < trainingClasses.rows; i++){
    traning_label.at<int>(i, 0) = trainingClasses.at<float>(i, 0);
  }

  cv::Ptr<cv::ml::SVM> svm = ml::SVM::create();
  svm->setType(ml::SVM::Types::C_SVC);
  svm->setKernel(ml::SVM::KernelTypes::RBF);
  //svm->setDegree(0);  // for poly
  svm->setGamma(20);  // for poly/rbf/sigmoid
  //svm->setCoef0(0);   // for poly/sigmoid
  svm->setC(7);       // for CV_SVM_C_SVC, CV_SVM_EPS_SVR and CV_SVM_NU_SVR
  //svm->setNu(0);      // for CV_SVM_NU_SVC, CV_SVM_ONE_CLASS, and CV_SVM_NU_SVR
  //svm->setP(0);       // for CV_SVM_EPS_SVR

  svm->setTermCriteria(TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 1000, 1E-6));

  svm->train(trainingData, ml::SampleTypes::ROW_SAMPLE, traning_label);

  cv::Mat predicted(testClasses.rows, 1, CV_32F);

  svm->predict(testData, predicted);

  cout << "Accuracy_{SVM} = " << evaluate(predicted, testClasses) << endl;
  plot_binary(testData, predicted, "Predictions SVM");

  // plot support vectors
  if (plotSupportVectors) {
    cv::Mat plot_sv(size, size, CV_8UC3);
    plot_sv.setTo(cv::Scalar(255.0, 255.0, 255.0));

    Mat support_vectors = svm->getSupportVectors();
    for (int vecNum = 0; vecNum < support_vectors.rows; vecNum++){
      cv::circle(plot_sv, Point(support_vectors.row(vecNum).at<float>(0)*size, support_vectors.row(vecNum).at<float>(1)*size), 3, CV_RGB(0, 0, 0));
    }

    namedWindow("Support Vectors", CV_WINDOW_KEEPRATIO);
    cv::imshow("Support Vectors", plot_sv);
  }
}

int main(){

  cv::Mat trainingData(numTrainingPoints, 2, CV_32FC1);
  cv::Mat testData(numTestPoints, 2, CV_32FC1);

  cv::randu(trainingData, 0, 1);
  cv::randu(testData, 0, 1);

  cv::Mat trainingClasses = labelData(trainingData, eq);
  cv::Mat testClasses = labelData(testData, eq);

  plot_binary(trainingData, trainingClasses, "Training Data");
  plot_binary(testData, testClasses, "Test Data");

  svm(trainingData, trainingClasses, testData, testClasses);
  waitKey(0);
  return 0;
}
时间: 2024-11-09 01:45:37

[code segments] OpenCV3.0 SVM with C++ interface的相关文章

【OpenCV】opencv3.0中的SVM训练 mnist 手写字体识别

前言: SVM(支持向量机)一种训练分类器的学习方法 mnist 是一个手写字体图像数据库,训练样本有60000个,测试样本有10000个 LibSVM 一个常用的SVM框架 OpenCV3.0 中的ml包含了很多的ML框架接口,就试试了. 详细的OpenCV文档:http://docs.opencv.org/3.0-beta/doc/tutorials/ml/introduction_to_svm/introduction_to_svm.html mnist数据下载:http://yann.l

ubuntu14.04下安装cudnn5.1.3,opencv3.0,编译caffe及matlab和python接口过程记录

已有条件: ubuntu14.04+cuda7.5+anaconda2(即python2.7)+matlabR2014a 上述已经装好了,开始搭建caffe环境. 1. 装cudnn5.1.3,参照:2015.08.17 Ubuntu 14.04+cuda 7.5+caffe安装配置 详情:先下载好cudnn-7.5-linux-x64-v5.1-rc.tgz安装包(貌似需要官网申请) 解压: tar -zxvf cudnn-7.5-linux-x64-v5.1-rc.tgz cd cuda s

Windows环境中编译opencv3.0同时加入OPENCV_contrib库及解决遇到相关问题

因为opencv3.0默认安装中没有加入SIFT.SURF等点特征检测,一百度下一跳,原来这玩意还弄了个其他的库,还只能在GitHub上才能弄到,这两天弄opencv3的contrib库,遇到了一些问题,为了让大家更好.更快用上contrib库,根据谷歌百度的几个问题,现分享给大家完整流程,也欢迎大家与我讨论其他opencv方面的问题. 一.下载安装准备 github  desktop 下载      windows 7or Later : https://desktop.github.com

VS2013 Community配置OpenCV3.0.0

配置环境:32位win7系统+VS2013 Community版本 1.首先从OpenCV官网上下载最新版本的OpenCV for Windows. 2.直接双击打开下载得到的opencv-3.0.0.exe,将OpenCV解压到指定目录(我这里是"D:\OpenCV\"). 3.解压完毕,文件目录如下,OpenCV编译好的文件保存在build文件夹里,sources文件夹里是OpenCV的源码. 4.打开build文件夹,其中,include文件夹包含opencv的头文件(.h),X

OpenCV3 Ref SVM : cv::ml::SVM Class Reference

OpenCV3  Ref SVM : cv::ml::SVM Class Reference OpenCV2: #include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <opencv2/ml/ml.hpp>#include <iostream> using namespace cv;using namespace std; int main(){ float

MongoDB { code: 18, ok: 0.0, errmsg: "auth fails" } 原因

MongoDB出现 { code: 18, ok: 0.0, errmsg: "auth fails" }  错误的原因: 1.账号密码错误 2.账号不属于该数据库 MongoDB { code: 18, ok: 0.0, errmsg: "auth fails" } 原因,布布扣,bubuko.com

QT - OpenCV的安装与配置 (win7 64 bit + OpenCV3.0 + minGW32)

QT - OpenCV的安装与配置 想在QT中使用OpenCV来实现连续图片转成视频的功能,于是打上了OpenCV的主意 安装OpenCV的过程也是充满了曲折,但是最终还是安装成功了,现记录安装过程,以防系统重装后傻眼. 感谢以下前辈的分享: https://zahidhasan.wordpress.com/2014/08/19/qt-5-3-1-64-bit-mingw-windows/ http://www.tagwith.com/question_113329_opencv-3-0-vid

windows下配置caffe(环境:win7+vs2013+opencv3.0)

说明:大部分转载于initialneil的大作Caffe + vs2013 + OpenCV in Windows Tutorial (I) – Setup 准备工作: 1.下载CUDA7.5: https://developer.nvidia.com/cuda-downloads,安装完成后会自动创建变量CUDA_PATH_V7_5 2.下载boost1.56:http://sourceforge.net/projects/boost/files/boost-binaries/1.56.0/,

Ubuntu14.04下安装OpenCV3.0经验

Jeremy Lin 不得不说OpenCV的安装是个坑,我差不多花了2天时间才搞定.第1遍我是在VMware的虚拟机上面安装的,结果很无奈的失败了.后来我用EasyBCD装了Win8.1和Ubuntu14.04的双系统来安装OpenCV3.0,不过一开始也是相当不顺利. 现在谈一下正确的安装方法: 前提:系统更新 sudo apt-get update sudo apt-get upgrade 我主要就是栽在这个坑上面,我是一安装完 Ubuntu 14.04.2 就开始安装 OpenCV3.0