1 #include <windows.h> 2 #include <iostream> 3 #include <opencv2/opencv.hpp> 4 5 using namespace cv; 6 using namespace std; 7 8 char* WcharToChar(const wchar_t* wp) 9 { 10 char *m_char; 11 int len = WideCharToMultiByte(CP_ACP, 0, wp, wcslen(wp), NULL, 0, NULL, NULL); 12 m_char = new char[len + 1]; 13 WideCharToMultiByte(CP_ACP, 0, wp, wcslen(wp), m_char, len, NULL, NULL); 14 m_char[len] = '\0'; 15 return m_char; 16 } 17 18 wchar_t* CharToWchar(const char* c) 19 { 20 wchar_t *m_wchar; 21 int len = MultiByteToWideChar(CP_ACP, 0, c, strlen(c), NULL, 0); 22 m_wchar = new wchar_t[len + 1]; 23 MultiByteToWideChar(CP_ACP, 0, c, strlen(c), m_wchar, len); 24 m_wchar[len] = '\0'; 25 return m_wchar; 26 } 27 28 wchar_t* StringToWchar(const string& s) 29 { 30 const char* p = s.c_str(); 31 return CharToWchar(p); 32 } 33 34 int main() 35 { 36 const string fileform = "*.png"; 37 const string perfileReadPath = "charSamples"; 38 39 const int sample_mun_perclass = 20;//训练字符每类数量 40 const int class_mun = 10;//训练字符类数 41 42 const int image_cols = 8; 43 const int image_rows = 16; 44 string fileReadName, 45 fileReadPath; 46 char temp[256]; 47 48 CvANN_MLP bp; 49 bp.load("bpcharModel.yml"); 50 51 //测试神经网络 52 cout << "测试:" << endl; 53 Mat test_image = imread("2.png", CV_LOAD_IMAGE_GRAYSCALE); 54 Mat test_temp; 55 //使用象素关系重采样。当图像缩小时候,该方法可以避免波纹出现 56 resize(test_image, test_temp, Size(image_cols, image_rows), (0, 0), (0, 0), CV_INTER_AREA); 57 threshold(test_temp, test_temp, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU); 58 Mat_<float>sampleMat(1, image_rows*image_cols); 59 for (int i = 0; i<image_rows*image_cols; ++i) 60 { 61 sampleMat.at<float>(0, i) = (float)test_temp.at<uchar>(i / 8, i % 8); 62 } 63 64 Mat responseMat; 65 bp.predict(sampleMat, responseMat); 66 Point maxLoc; 67 double maxVal = 0; 68 minMaxLoc(responseMat, NULL, &maxVal, NULL, &maxLoc); 69 cout << "识别结果:" << maxLoc.x << " 相似度:" << maxVal * 100 << "%" << endl; 70 imshow("test_image", test_image); 71 waitKey(0); 72 73 return 0; 74 }