图像用的是opencv目录中的:digits.png。每20*20像素为一个数字,图像的大小是2000*1000,一共是5000个数字,用300个作为”训练“数字,2000作为测试数字,KNN算法识别率就是高,作弊测试可以达到95%,盲测可以达到92%。
全部的程序:
#include<opencv2/opencv.hpp>
#include<opencv2/ml/ml.hpp>
#include<fstream>
#include<time.h>
#include<iostream>
#include<stdio.h>
using namespace cv;
using namespace std;
using namespace cv::ml;
#define maxCol 100
#define maxRow 50
#define b 20
ofstream fout;
int main()
{
Mat src, gray;
Mat dataMat;
Mat labelMat;
fout.open("D:/test.txt");
src = imread("D:/picture/digits.png");
if (src.empty())
{
cout << "could not load the image" << endl;
return -1;
}
cvtColor(src, gray, COLOR_BGR2GRAY);
//得到所有的测试数据,检测数据以及对应的标签数据。
for (int col = 0; col < maxCol; col++)
{
for (int row = 0; row < maxRow; row++)
{
Mat temp;
gray(Range(row*b, (row + 1)*b), Range(col*b, (col + 1)*b)).copyTo(temp);
dataMat.push_back(temp.reshape(0, 1));
labelMat.push_back((int)(row / 5));
}
}
dataMat.convertTo(dataMat, CV_32F);
//knn算法实现
int traingNum = 3000;
Mat traingDataMat = dataMat(Range(0, traingNum), Range::all());
Mat trainglabelMat = labelMat(Range(0, traingNum), Range::all());
KNearest::Params params;
params.defaultK = 5;
params.isclassifier = true;
Ptr<TrainData> knn;
knn = TrainData::create(traingDataMat, ROW_SAMPLE, trainglabelMat);
Ptr<KNearest> model;
model = StatModel::train<KNearest>(knn, params);
double train = 0;
double test = 0;
int samplesNum = 3000;
for (int i = 0; i < dataMat.rows; i++)
{
Mat sample = dataMat.row(i);
float r = model->predict(sample); //输出预测的 结果
float r1 = abs(r - labelMat.at<int>(i)) <= FLT_EPSILON ? 1.f : 0.f;
if (i < traingNum)
train += r1;
else
test += r1;
}
test /= dataMat.rows - traingNum;
train /= traingNum;
printf("accuracy: train = %.1f%%, test = %.1f%%\n",
train*100., test*100.);
waitKey(0);
getchar();
return 0;
}