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

Posted shuimuqingyang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 labels[4] = { 0, 0, 1, 1 }; //训练标签数据,前两个表示男生,后两个表示女生
Mat labelsMat(3, 1, CV_32FC1, labels);

float trainingData[4][2] = { { 186,80 },{ 185,81 },{ 160,50 },{ 161,48 } }; //训练数据,两个维度,表示身高和体重
Mat trainingDataMat(3, 2, CV_32FC1, trainingData);


CvSVMParams params; //SVM参数
params.svm_type = CvSVM::C_SVC; //SVM类型. 这里用C_SVC
params.kernel_type = CvSVM::LINEAR; //SVM 核类型
params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6); //终止条件,最大迭代次数和容许误差


CvSVM SVM;
SVM.train(trainingDataMat, labelsMat, Mat(), Mat(), params);//训练

Mat sampleMat = (Mat_<float>(1, 2) << 184, 79); //测试数据,为一男生
float response = SVM.predict(sampleMat);

if (response == 0)
cout << "Boy" << endl;
else if (response == 1)
cout << "Girl" << endl;

return 0;
}


OpenCV3中的SVM:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/ml/ml.hpp>
#include <iostream>

using namespace cv;
using namespace cv::ml;
using namespace std;

int main()
{
float labels[4] = { 0, 0, 1, 1 }; //训练标签数据
Mat labels_train(4, 1, CV_32F, labels);

float trainingData[4][2] = { { 186,80 },{ 185,81 },{ 160,50 },{ 161,48 } }; //训练数据,两个维度
Mat data_train(4, 2, CV_32F, trainingData);


Ptr<SVM> svm = SVM::create();
svm->setKernel(cv::ml::SVM::KernelTypes::LINEAR);
svm->setType(cv::ml::SVM::Types::C_SVC);
svm->setTermCriteria(TermCriteria( TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, FLT_EPSILON ));

svm->train(data_train, ROW_SAMPLE, labels_train);
//svm->save("SVMmodel"); //存储模型
//Ptr<SVM> svm = StatModel::load<SVM>("SVMmodel"); //读取模型

Mat testData(1,2,CV_32F);//测试数据
Mat responses; //预测结果
testData.at<float>(0,0) = 184;
testData.at<float>(0,1) = 79;
svm->predict(testData, responses);
responses.convertTo(responses,CV_32S);

if (response.at<int>(0,0) == 0)
cout << "Boy" << endl;
else if (response.at<int>(0,0) == 1)
cout << "Girl" << endl;

return 0;
}
---------------------
作者:纯洁可爱小昊昊
来源:CSDN
原文:https://blog.csdn.net/jhszh418762259/article/details/60143152
版权声明:本文为博主原创文章,转载请附上博文链接!


















































































以上是关于OpenCV3 Ref SVM : cv::ml::SVM Class Reference的主要内容,如果未能解决你的问题,请参考以下文章

为啥使用 SVM 线性内核的代码不能使用 RBF

[OpenCV随笔]-OpenCV3.x中SVM使用(代码篇)

如何为 openCV SVM 格式化数据

Opencv 3 SVM 训练

Opencv 3 SVM 训练

OpenCV3 SVM ANN Adaboost KNN 随机森林等机器学习方法对OCR分类