继承自本人博客:
http://blog.csdn.net/qq_15947787/article/details/51385861
原文只是识别数字0-9,简单修改后可以识别24个字母(除了I,O)与数字。
把0与O看成一类,1与I看成一类
附件从原文下载即可。
//opencv2.4.9 + vs2012 + 64位
#include
#include
#include
#include
using namespace cv;
using namespace std;
char* WcharToChar(const wchar_t* wp)
{
char *m_char;
int len= WideCharToMultiByte(CP_ACP,0,wp,wcslen(wp),NULL,0,NULL,NULL);
m_char=new char[len+1];
WideCharToMultiByte(CP_ACP,0,wp,wcslen(wp),m_char,len,NULL,NULL);
m_char[len]='\0';
return m_char;
}
wchar_t* CharToWchar(const char* c)
{
wchar_t *m_wchar;
int len = MultiByteToWideChar(CP_ACP,0,c,strlen(c),NULL,0);
m_wchar=new wchar_t[len+1];
MultiByteToWideChar(CP_ACP,0,c,strlen(c),m_wchar,len);
m_wchar[len]='\0';
return m_wchar;
}
wchar_t* StringToWchar(const string& s)
{
const char* p=s.c_str();
return CharToWchar(p);
}
int main()
{
const string fileform = "*.png";
const string perfileReadPath = "charSamples";
const int sample_mun_perclass = 20;//训练字符每类数量
const int class_mun = 10+26;//训练字符类数 0-9 A-Z 除了I、O
const int image_cols = 8;
const int image_rows = 16;
string fileReadName,
fileReadPath;
char temp[256];
float trainingData[class_mun*sample_mun_perclass][image_rows*image_cols] = {{0}};//每一行一个训练样本
float labels[class_mun*sample_mun_perclass][class_mun]={{0}};//训练样本标签
for(int i = 0; i <= class_mun - 1; i++)//不同类
{
//读取每个类文件夹下所有图像
int j = 0;//每一类读取图像个数计数
if (i <= 9)//0-9
{
sprintf(temp, "%d", i);
//printf("%d\n", i);
}
else//A-Z
{
sprintf(temp, "%c", i + 55);
//printf("%c\n", i+55);
}
fileReadPath = perfileReadPath + "/" + temp + "/" + fileform;
cout<<"文件夹"<((int)k/8,(int)k%8);//(float)train_image.data[k];
//cout<(k/8,k%8)<(1,5) << image_rows*image_cols,128,128,128,class_mun);
bp.create(layerSizes,CvANN_MLP::SIGMOID_SYM,1.0,1.0);//CvANN_MLP::SIGMOID_SYM
//CvANN_MLP::GAUSSIAN
//CvANN_MLP::IDENTITY
cout<<"training...."<sampleMat(1,image_rows*image_cols);
for(int i = 0; i(0,i) = (float)test_temp.at(i/8,i%8);
}
Mat responseMat;
bp.predict(sampleMat,responseMat);
Point maxLoc;
double maxVal = 0;
minMaxLoc(responseMat,NULL,&maxVal,NULL,&maxLoc);
if (maxLoc.x <= 9)//0-9
{
sprintf(temp, "%d", maxLoc.x);
//printf("%d\n", i);
}
else//A-Z
{
sprintf(temp, "%c", maxLoc.x + 55);
//printf("%c\n", i+55);
}
cout<<"识别结果:"<