코드 16-3 학습된 모델 파일을 이용한 필기체 숫자 인식 예제 [ch16/dnnmnist]
01 #include "opencv2/opencv.hpp" 02 #include <iostream> 03 04 using namespace cv; 05 using namespace cv::dnn; 06 using namespace std; 07 08 void on_mouse(int event, int x, int y, int flags, void* userdata); 09 10 int main() 11 { 12 Net net = readNet("mnist_cnn.pb"); 13 14 if (net.empty()) { 15 cerr << "Network load failed!" << endl; 16 return -1; 17 } 18 19 Mat img = Mat::zeros(400, 400, CV_8UC1); 20 21 imshow("img", img); 22 setMouseCallback("img", on_mouse, (void*)&img); 23 24 while (true) { 25 int c = waitKey(0); 26 27 if (c = = 27) { 28 break; 29 } else if (c = = ' ') { 30 Mat inputBlob = blobFromImage(img, 1/255.f, Size(28, 28)); 31 net.setInput(inputBlob); 32 Mat prob = net.forward(); 33 34 double maxVal; 35 Point maxLoc; 36 minMaxLoc(prob, NULL, &maxVal, NULL, &maxLoc); 37 int digit = maxLoc.x; 38 39 cout << digit << " (" << maxVal * 100 << "%)" << endl; 40 41 img.setTo(0); 42 imshow("img", img); 43 } 44 } 45 46 return 0; 47 } 48 49 Point ptPrev(-1, -1); 50 51 void on_mouse(int event, int x, int y, int flags, void* userdata) 52 { 53 Mat img = *(Mat*)userdata; 54 55 if (event = = EVENT_LBUTTONDOWN) { 56 ptPrev = Point(x, y); 57 } else if (event = = EVENT_LBUTTONUP) { 58 ptPrev = Point(-1, -1); 59 } else if (event = = EVENT_MOUSEMOVE && (flags & EVENT_FLAG_LBUTTON)) { 60 line(img, ptPrev, Point(x, y), Scalar::all(255), 40, LINE_AA, 0); 61 ptPrev = Point(x, y); 62 63 imshow("img", img); 64 } 65 }