首页 > 其他 > 详细

opencv SVM分类器简单使用

时间:2020-08-24 11:07:34      阅读:113      评论:0      收藏:0      [点我收藏+]

煤矸石分类项目,提取的煤矸石灰度均值和灰度方差作为特征进行分类,代码如下,使用的二次封装的opencv库,在其他机器上运行将头文件和条件编译宏替换成opencv自己的就可以了

#include "sv.h"
#ifdef _DEBUG
#pragma comment(lib,"BoxCV100d.lib")
#pragma comment(lib,"SvRunTimed.lib")
#else
#pragma comment(lib,"BoxCV100.lib")
#pragma comment(lib,"SvRunTime.lib")
#endif

using namespace cv;
using namespace cv::ml;

int main(int argc, char** argv)
{
    int width = 720, height = 720;

    //三通道可视化窗口
    Mat image = Mat::zeros(height, width, CV_8UC3);
    
    int labels[11] = { 1,1,1,1,1,1,
                    -1,-1,-1,-1,-1 };
    Mat LabelsMat(10, 1, CV_32SC1, labels);

    float TrainingData[11][2]=
    {
        {291.4,252},{115.3,185},{277.7,695},{367.562},{352.4,645},{117.2,203},
        {117.2,129},{122.8,112},{116.4,175},{132.5,78},{106.3,125}
    };
    Mat TrainMat(10, 2, CV_32FC1, TrainingData);

    //创建分类器设置参数
    Ptr<SVM> model = SVM::create();
    model->setType(SVM::C_SVC);
    model->setKernel(SVM::LINEAR);

    //设置训练参数
    Ptr<TrainData> tData = TrainData::create(TrainMat, ROW_SAMPLE, LabelsMat);

    //训练分类器
    model->train(tData);

    Vec3b ColorGreen(0, 255, 0), ColorBlue(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);

            //predict
            float response = model->predict(SampleMat);

            if (1 == response)
                image.at<Vec3b>(i, j) = ColorGreen;
            else
                if (-1 == response)
                    image.at<Vec3b>(i, j) = ColorBlue;
        }

    //绘图
    //显示结果
    int thickness = -1;
    int lineType = 8;

    //两类结果一个黑色一个白色
    Scalar c1 = Scalar::all(0);
    Scalar c2 = Scalar::all(255);

    for (int i = 0; i < LabelsMat.rows; ++i)
    {
        //取出每行指针
        const float* v = TrainMat.ptr<float>(i);
        Point pt = Point((int)v[0], (int)v[1]);
        if (1 == labels[i])
            circle(image, pt, 5, c1, thickness, lineType);
        else
            circle(image, pt, 5, c2, thickness, lineType);
    }

    imshow("SVM Simple Example", image);
    waitKey();
}

结果图

技术分享图片

 

opencv SVM分类器简单使用

原文:https://www.cnblogs.com/wangtianning1223/p/13552438.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!