机器学习 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

相关推荐
水饺编程4 分钟前
第5章,[标签 Win32] :设备的尺寸(三)
c语言·c++·windows·visual studio
Cando学算法5 分钟前
中位数定理:到所有点的距离之和最小的点就是中位数
c++·算法·学习方法
HZY1618yzh15 分钟前
洛谷题解:P16304 [蓝桥杯 2026 省 Java C 组] 抽奖活动
java·c++·算法·蓝桥杯
智者知已应修善业28 分钟前
【51单片机从奇数始再转偶数逐一点亮并循环】2023-9-8
c++·经验分享·笔记·算法·51单片机
郝学胜-神的一滴36 分钟前
深入理解回归损失函数:MSE、L1 与 Smooth L1 的设计哲学
人工智能·python·程序人生·算法·机器学习·数据挖掘·回归
努力努力再努力wz36 分钟前
【MySQL进阶系列】拒绝冗余SQL:带你透彻理解视图的底层逻辑
android·c语言·数据结构·数据库·c++·sql·mysql
Godspeed Zhao1 小时前
具身智能中的传感器技术40.2——事件相机0.2
人工智能·科技·数码相机·机器学习·事件相机
Yupureki1 小时前
《Linux网络编程》4.应用层HTTP协议
linux·服务器·c语言·网络·c++·http
Brilliantwxx1 小时前
【C++】认识vector(概念+题目OJ)
开发语言·c++·笔记·算法
上弦月-编程1 小时前
C语言链表详解,新手也能看懂! ——从入门到精通的完整教程
java·c语言·c++