HOG特征SVM识别字符

算法思想介绍请自行百度学习。

训练函数:

#include "opencv\cv.h"
#include "opencv\highgui.h"
#include "opencv2\opencv.hpp"
#include 
#include 

using namespace std;
using namespace cv;

//SVM训练
void svmHogTrain()
{
	int i, j;
	int testCount = 1016, testType = 10, featureLen = 324;
	char buffer[100];

	Mat src;
	Mat data = Mat::zeros(testCount * testType, featureLen, CV_32FC1);
	Mat res = Mat::zeros(testCount * testType, 1, CV_32SC1);

	for (i = 0; i < testType; i++)
	{
		for (j = 1; j < testCount; j++)
		{
			sprintf_s(buffer, "C:/Users/admin/Desktop/Industry check/EnglishFnt/English/Fnt_3/Sample%03d/%05d.png", i+1, j);
			//sprintf_s(buffer, "C:/Users/admin/Desktop/Industry check/dataset/train_n/%05d/%05d.png", i, j);
			//sprintf_s(buffer, "C:/Users/admin/Desktop/Industry check/EnglishFnt/English/Fnt_3/Sample%03d/%05d.png", i+11, j);
			//sprintf_s(buffer, "C:/Users/admin/Desktop/Industry check/dataset/train_1_n/%05d/%05d.jpg", i, j);

			src = imread(buffer, CV_LOAD_IMAGE_GRAYSCALE);

			threshold(src, src, 0, 255, CV_THRESH_OTSU);
			
			HOGDescriptor *hog = new HOGDescriptor(cvSize(64, 64), cvSize(32, 32), cvSize(16, 16), cvSize(16, 16), 9);
			vectordescriptors;//结果数组       
			hog->compute(src, descriptors, Size(1, 1), Size(0, 0)); //调用计算函数开始计算       

			int n = 0;
			for (vector::iterator iter = descriptors.begin(); iter != descriptors.end(); iter++)
			{
				data.at(i * testCount + j - 1, n) = *iter;
				n++;
			}

			res.at(i * testCount + j - 1, 0) = i;
		}
		cout << i << "  " << "completed" << endl;
	}
	Ptr svm = cv::ml::SVM::create();
	svm->setType(cv::ml::SVM::Types::C_SVC);
	svm->setKernel(cv::ml::SVM::KernelTypes::LINEAR);
	svm->setTermCriteria(cv::TermCriteria(cv::TermCriteria::MAX_ITER, 100, 1e-6));

	svm->train(data, cv::ml::SampleTypes::ROW_SAMPLE, res);

	svm->save("SVM_HOG_DATA.xml");
}

预测函数:

#include "opencv\cv.h"
#include "opencv\highgui.h"
#include "opencv2\opencv.hpp"
#include 
#include 

using namespace std;
using namespace cv;

//SVM预测
int svmHogPredict(Mat SrcImg)
{
	cv::Ptr svm;

	svm = cv::ml::SVM::load("SVM_HOG_DATA.xml");

	HOGDescriptor *hog = new HOGDescriptor(cvSize(64, 64), cvSize(32, 32), cvSize(16, 16), cvSize(16, 16), 9);
	vectordescriptors;//结果数组       
	hog->compute(SrcImg, descriptors, Size(1, 1), Size(0, 0)); //调用计算函数开始计算
	Mat SVMtrainMat = Mat::zeros(1, descriptors.size(), CV_32FC1);
	int n = 0;
	for (vector::iterator iter = descriptors.begin(); iter != descriptors.end(); iter++)
	{
		SVMtrainMat.at(0, n) = *iter;//把HOG存储下来    
		n++;
	}
	int ret = svm->predict(SVMtrainMat);//检测结果
	return ret;
}

识别函数:

程序简单自行编写,先调用训练函数,再调用识别函数。
注意:保证待识别图片大小与上述函数中要求一致。

你可能感兴趣的:(工作学习收获,Hog,SVM)