opencv的svm加载自己训练图片的模型

上篇博客写了如何利用svm训练自己的模型,用于识别数字,这片博客就是加载模型,然后测试模型到底怎样,正确率高不高。
识别的结果就在这句话中,这句代码的意思是将检测的图片的标签返回回来,结果保存在response中,可以对response进行操作检测自己的模型准确率
int response = (int)svm->predict(p);

#include <stdio.h>  
#include <time.h>  
#include <math.h>  
#include <opencv2/opencv.hpp>  
#include <opencv/cv.h>  
#include <iostream> 
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>  
#include <opencv2/ml/ml.hpp>  
#include <io.h>

using namespace std;
using namespace cv;

void getFiles(string path, vector<string>& files);

int main()
{
    int result = 0; //
    char * filePath = "E:\\SVM_train_data\\positive\\test";
    vector<string> files;
    getFiles(filePath, files);
    int number = files.size();
    cout <<"共有测试图片 " <<number <<" 张\n"<< endl;

    Ptr<ml::SVM>svm = ml::SVM::load("svm.xml");

    for (int i = 0; i < number; i++)
    {
        Mat inMat = imread(files[i].c_str());
        Mat p = inMat.reshape(1, 1);
        p.convertTo(p, CV_32FC1);
        int response = (int)svm->predict(p);
        cout << "识别的数字为:" << response << endl;

        if (response > =1)
        {
            result++;
        }

    }
    cout << result << endl;

    getchar();
    return  0;
}
void getFiles(string path, vector<string>& files)
{
    intptr_t   hFile = 0;
    struct _finddata_t fileinfo;
    string p;
    if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
    {
        do
        {
            if ((fileinfo.attrib &  _A_SUBDIR))
            {
                if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
                    getFiles(p.assign(path).append("\\").append(fileinfo.name), files);
            }
            else
            {
                files.push_back(p.assign(path).append("\\").append(fileinfo.name));
            }
        } while (_findnext(hFile, &fileinfo) == 0);
        _findclose(hFile);
    }
}

检测效果,蛮好的
这里写图片描述

猜你喜欢

转载自blog.csdn.net/mao_hui_fei/article/details/80465011