机器学习 C++ 的opencv实现SVM图像二分类的测试 (三)【附源码】

机器学习 C++ 的opencv实现SVM图像二分类的测试 (三)

数据集合下载地址:https://download.csdn.net/download/hgaohr1021/89506900

根据上节得到的svm.xml,测试结果为:

cpp 复制代码
#include <stdio.h>  
#include <time.h>  
#include <opencv2/opencv.hpp>  

#include <iostream> 
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "opencv2/imgcodecs.hpp"
#include <opencv2/core/utils/logger.hpp>
#include <opencv2/ml/ml.hpp>  
#include <io.h>

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

void getFiles(string path, vector<string>& files);
int main()
{
	int result = 0;
	string filePath = "data\\test_image\\0";
	vector<string> files;
	getFiles(filePath, files);
	int number = files.size();
	cout << number << endl;
	string modelpath = "svm.xml";
	cv::Ptr<cv::ml::SVM> svm;
	svm = cv::Algorithm::load<cv::ml::SVM>(modelpath);


	/*CvSVM svm;
	svm.clear();
	string modelpath = "svm.xml";
	FileStorage svm_fs(modelpath, FileStorage::READ);
	if (svm_fs.isOpened())
	{
		svm.load(modelpath.c_str());
	}*/

	FileStorage svm_fs(modelpath, FileStorage::READ);
	if (svm_fs.isOpened())
	{
		svm->load(modelpath.c_str());
	}

	for (int i = 0; i < number; i++)
	{
		Mat inMat = imread(files[i].c_str());
		resize(inMat, inMat, cv::Size(60, 256), (0, 0), (0, 0), cv::INTER_LINEAR);  //将图片调整为相同的大小
		Mat p = inMat.reshape(1, 1);
		p.convertTo(p, CV_32FC1);
		int response = (int)svm->predict(p);
		if (response == 1)
		{
			result++;
		}
	}


	cout << "识别个数:" << result << endl;
	cout << "识别率:" << setprecision(2) << fixed << double(result) / (double)(number) << endl;
	getchar();
	return  0;
}
void getFiles(string path, vector<string>& files)
{
	long long   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);
	}
}

数据集合下载地址:https://download.csdn.net/download/hgaohr1021/89506900

相关推荐
无限进步_1 天前
C语言字符串与内存操作函数完全指南
c语言·c++·算法
victory04311 天前
TODO 分类任务指标计算和展示 准确率 F1 Recall
人工智能·机器学习·分类
rengang661 天前
07-逻辑回归:分析用于分类问题的逻辑回归模型及其数学原理
人工智能·算法·机器学习·分类·逻辑回归
闻缺陷则喜何志丹1 天前
【C++贪心】P10537 [APIO2024] 九月|普及+
c++·算法·贪心·洛谷
QiZhang | UESTC1 天前
JAVA算法练习题day27
java·开发语言·c++·算法·leetcode·hot100
Stanford_11061 天前
关于嵌入式硬件需要了解的基础知识
开发语言·c++·嵌入式硬件·微信小程序·微信公众平台·twitter·微信开放平台
极客BIM工作室1 天前
机器学习之规则学习(Rule Learning)
人工智能·机器学习
是那盏灯塔1 天前
16.C++三大重要特性之多态
开发语言·c++
我是华为OD~HR~栗栗呀1 天前
24届-Python面经(华为OD)
java·前端·c++·python·华为od·华为·面试
胖咕噜的稞达鸭1 天前
缝合怪deque如何综合list和vector实现及仿函数模板如何优化priority_queue实现
数据结构·c++·算法·链表·list