欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

OpenCV实现Support Vector Machine(SVM)

程序员文章站 2022-05-21 20:29:31
...
#include "stdafx.h"
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\core\core.hpp>
#include <opencv2\ml\ml.hpp>

using namespace cv;
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{

    //要呈现的数据
    int width = 1920, height = 1080;
    Mat image = Mat::zeros(height, width, CV_8UC3);
    //标签
    float labels[4] = { 1.0, -1.0, -1.0, -1.0 };
    Mat labelsMat(4, 1, CV_32FC1, labels);
    cout << labelsMat << endl;
    //设置训练数据
    float trainingData[4][2] = { { 501, 10 }, { 255, 10 }, { 501, 255 }, { 10, 501 } };
    Mat trainingDataMat(4, 2, CV_32FC1, trainingData);
    //设置SVM参数
    CvSVMParams params;
    params.svm_type = CvSVM::C_SVC;
    params.kernel_type = CvSVM::LINEAR;
    params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6);
    //训练SVM
    CvSVM SVM;
    SVM.train(trainingDataMat, labelsMat, Mat(), Mat(), params);
    Vec3b green(0, 255, 0), blue(255, 0, 0);
    //显示SVM的决定区
    for (int i = 0; i < image.rows; i++)
    {
        for (int j = 0; j < image.cols; j++)
        {
            Mat sampleMat = (Mat_<float>(1, 2) << j, i);
            float response = SVM.predict(sampleMat);
            if (response == 1)
                image.at<Vec3b>(i, j) = green;
            else if (response == -1)
                image.at<Vec3b>(i, j) = blue;
        }
    }
    //显示训练数据
    int thickness = -1;
    int lineType = 8;
    circle(image, Point(501, 10), 5, Scalar(0, 0, 0), thickness, lineType);
    circle(image, Point(255, 10), 5, Scalar(255, 255, 255), thickness, lineType);
    circle(image, Point(501, 255), 5, Scalar(255, 255, 255), thickness, lineType);
    circle(image, Point(10, 501), 5, Scalar(255, 255, 255), thickness, lineType);

    //显示支持向量机
    thickness = 2;
    lineType = 8;
    int c = SVM.get_support_vector_count();
    for (int i = 0; i < c; i++)
    {
        const float *v = SVM.get_support_vector(i);
        circle(image, Point((int)v[0], (int)v[1]), 6, Scalar(128, 128, 128), thickness, lineType);
    }

    //显示结果
    imshow("SVM Simple Example", image);
    waitKey(0);
    system("pause");

    return 0;
}

OpenCV实现Support Vector Machine(SVM)

相关标签: OpenCV SVM