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

相关推荐
有Li6 小时前
EEG脑电图数据处理基础
人工智能·算法·机器学习·语言模型·医学生
明志数科6 小时前
机器人训练数据获取困境:互联网数据为何无法直接复用
人工智能·深度学习·microsoft·机器学习·机器人
I Am a robert girl6 小时前
VideoLoop:用循环工作记忆对抗长视频 Agent 的语义抖动
大数据·人工智能·机器学习·多模态agent·长视频理解·工作记忆·语义抖动
loulanyue_7 小时前
我们正从规模化时代迈向研究时代:破除预训练幻象与通用泛化困境——读Ilya Sutskever重磅专访全景解析
人工智能·深度学习·机器学习·大模型·通用人工智能
hetao17338377 小时前
校内场-提高组 ZYZSC-S-Round 2
c++·算法
萌萌的提莫队长7 小时前
Unity相机捕捉,图像识别,抠像+合成
opencv·unity
hetao17338377 小时前
2026-10-14 hetao1733837 的刷题记录
c++·算法
Zzj_tju7 小时前
蒸馏推理过程,传递的是能力还是表达习惯?
人工智能·机器学习·自然语言处理
浅念-8 小时前
动态规划:线性DP——多状态DP与子数组专题笔记
c++·笔记·算法·leetcode·职场和发展·动态规划·力扣
Data analyse4568 小时前
rrweb回放事件资源加载顺序重放校验
前端·人工智能·算法·机器学习·数据分析