OPENCV 3.4.1获取经过定制训练的线性SVM HOG DETECTMULTISCALE的原始形式



我在OpenCV 3.4.1中训练了线性SVM。现在,我想将我的自定义SVM与OpenCV 3的Hog DentectMultiscale功能一起使用。使用自定义SVM原始矢量设置猪检测器的旧方法不再起作用。

对于OpenCV 2,将从OPENCV 2的自定义训练的SVM获得原始矢量:

#include "linearsvm.h"
LinearSVM::LinearSVM() {
    qDebug() << "Creating SVM and loading trained data...";
    load("/home/pi/trainedSVM.xml");
    qDebug() << "Done loading data...";
}
std::vector<float> LinearSVM::getPrimalForm() const
{
  std::vector<float> support_vector;
  int sv_count = get_support_vector_count();
  const CvSVMDecisionFunc* df = getDecisionFunction();
  if ( !df ) {
      return support_vector;
  }
  const double* alphas = df[0].alpha;
  double rho = df[0].rho;
  int var_count = get_var_count();
  support_vector.resize(var_count, 0);
  for (unsigned int r = 0; r < (unsigned)sv_count; r++)
  {
    float myalpha = alphas[r];
    const float* v = get_support_vector(r);
    for (int j = 0; j < var_count; j++,v++)
    {
      support_vector[j] += (-myalpha) * (*v);
    }
  }
  support_vector.push_back(rho);
  return support_vector;
}

一旦根据训练有素的SVM数据创建了原始矢量,就会将HOG检测器SVM设置为这样:

    // Primal for of cvsvm descriptor
    vector<float> primalVector = m_CvSVM.getPrimalForm();
    qDebug() << "Got primal form of detection vector...";
    qDebug() << "Setting SVM detector...";
    // Set the SVM Detector - custom trained HoG Detector
    m_HoG.setSVMDetector(primalVector);

在OpenCV 3.4.1中,这不再起作用,因为CVSVM不再存在,并且SVM API的大部分都发生了变化。

我如何在OpenCV 3.4.1中获得我的自定义SVM的原始矢量:

// Set up SVM's parameters
    cv::Ptr<cv::ml::SVM> svm = cv::ml::SVM::create();
    svm->setType(cv::ml::SVM::C_SVC);
    svm->setKernel(cv::ml::SVM::LINEAR);
    svm->setTermCriteria(cv::TermCriteria(cv::TermCriteria::MAX_ITER, 10, 1e-6));
    // Train the SVM with given parameters
    cv::Ptr<cv::ml::TrainData> td = cv::ml::TrainData::create(trainingDataMat, cv::ml::ROW_SAMPLE, trainingLabelsMat);
    // Or auto train
    qDebug() << "Training dataset...";
    QElapsedTimer trainingTimer;
    trainingTimer.restart();
    svm->trainAuto(td);
    qDebug() << "Done training dataset in: " << (float)trainingTimer.elapsed() / 1000.0f;

谢谢。

事实证明,答案是在github上的openCV测试/示例train_hog.cpp中。

看起来像这样:

/// Get the SVM Detector in HoG Format
vector<float> getSVMDetector(const Ptr<SVM>& svm)
{
    // get the support vectors
    Mat sv = svm->getSupportVectors();
    const int sv_total = sv.rows;
    // get the decision function
    Mat alpha, svidx;
    double rho = svm->getDecisionFunction( 0, alpha, svidx );
    CV_Assert( alpha.total() == 1 && svidx.total() == 1 && sv_total == 1 );
    CV_Assert( (alpha.type() == CV_64F && alpha.at<double>(0) == 1.) ||
               (alpha.type() == CV_32F && alpha.at<float>(0) == 1.f) );
    CV_Assert( sv.type() == CV_32F );
    vector< float > hog_detector( sv.cols + 1 );
    memcpy( &hog_detector[0], sv.ptr(), sv.cols*sizeof( hog_detector[0] ) );
    hog_detector[sv.cols] = (float)-rho;
    return hog_detector;
}

最新更新