• 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
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    和阿文一起学H5-文字云制作
    uml与数据库设计
    设计模式——面向对象设计原则
    koajs框架解决的问题
    mongodb
    javascript 获取select选中text,2种方法
    带参数跳转
    express表单提交和参数接收4种方式
    ejs模版的4种输出方式
    nodejs事件
  • 原文地址:https://www.cnblogs.com/shuimuqingyang/p/9863511.html
Copyright © 2020-2023  润新知