资源简介
在OpenCV3.4.1上使用hog+svm实现了数字识别,提供了检测与训练部分,训练已经训练,可以直接运行。
代码片段和文件信息
#include
#include
#include
#include “opencv2/objdetect.hpp“
#include
using namespace cv::ml;
using namespace cv;
using namespace std;
string pathName = “digits.png“;
int SZ = 20;
float affineFlags = WARP_INVERSE_MAP | INTER_LINEAR;
//倾斜矫正
Mat deskew(Mat& img) {
Moments m = moments(img);
if (abs(m.mu02) < 1e-2) {
return img.clone();
}
float skew = m.mu11 / m.mu02;
Mat warpMat = (Mat_(2 3) << 1 skew -0.5*SZ*skew 0 1 0); //2*3变换矩阵
Mat imgOut = Mat::zeros(img.rows img.cols img.type());
warpAffine(img imgOut warpMat imgOut.size() affineFlags);
return imgOut;
}
//加载训练测试数据集标签
void loadTrainTestLabel(string &pathName vector &trainCells vector &trainLabels) {
Mat img = imread(pathName CV_LOAD_IMAGE_GRAYSCALE);
int ImgCount = 0;
for (int i = 0; i < img.rows; i = i + SZ)
{
for (int j = 0; j < img.cols; j = j + SZ)
{
Mat digitImg = (img.colRange(j j + SZ).rowRange(i i + SZ)).clone();
trainCells.push_back(digitImg);
ImgCount++;
}
}
cout << “Image Count : “ << ImgCount << endl;
float digitClassNumber = 0;
for (int z = 0; z {
if (z % 500 == 0 && z != 0)
{
digitClassNumber = digitClassNumber + 1;
}
trainLabels.push_back(digitClassNumber);
}
}
// 创建倾斜矫正后的训练集测试集
void CreateDeskewedTrainTest(vector &deskewedTrainCells vector &trainCells) {
for (int i = 0; i
Mat deskewedImg = deskew(trainCells[i]);
deskewedTrainCells.push_back(deskewedImg);
}
}
//HOG特征描述子
HOGDescriptor hog(
Size(20 20) //winSize
Size(10 10) //blocksize
Size(5 5) //blockStride
Size(10 10) //cellSize
9 //nbins
1 //derivAper
-1 //winSigma
0 //histogramNormType
0.2 //L2HysThresh
0//gammal correction
64//nlevels=64
1);
//创建训练测试HOG特征,并将计算结果保存至
void CreateTrainTestHOG(vector > &trainHOG vector &deskewedtrainCells) {
//train hog大小为num*hogsize
for (int y = 0; y vector descriptors;
hog.compute(deskewedtrainCells[y] descriptors Size(2 2) Size(0 0));
trainHOG.push_back(descriptors);
}
}
void ConvertVectortoMatrix(vector > &trainHOG Mat &trainMat)
{
int descriptor_size = trainHOG[0].size();//第一个样本的特征大小
for (int i = 0; i for (int j = 0; jriptor_size; j++) {
trainMat.at(i j) = trainHOG[i][j];
}
}
}
void getSVMParams(SVM *svm)
{
cout << “Kernel type : “ << svm->getKernelType() << endl;
cout << “Type : “ << svm->getType() << endl;
cout << “C : “ << svm->getC() << endl;
cout << “Degree : “ << svm->getDegree() << endl;
cout << “Nu : “ << svm->getNu() << endl;
cout << “Gamma : “ << svm->getGamma() << endl;
}
void SVMtrain(M
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 721129 2017-01-30 07:04 digits.png
文件 5031 2018-04-30 19:05 main.cpp
文件 1783266 2018-04-30 17:10 model4.yml
评论
共有 条评论