X
    Categories: C++ OpenCV Tutorials

Simple Digit Recognition aka Optical Character Recognition(OCR) in OpenCV-C++

Hello,

As an extension to my previous tutorial of “Simple Digit Recognition aka Optical Character Recognition(OCR) in OpenCV-Python” , in this tutorial, we’ll cover the C++ part of the code.

The procedure will remain same for both languages.

Here is the Code for creating sample and Label data:


#Make sure to provide correct includes
//Process image to extract contour
Mat thr,gray,con;
Mat src=imread("digit.png",1);
cvtColor(src,gray,CV_BGR2GRAY);
threshold(gray,thr,200,255,THRESH_BINARY_INV); //Threshold to find contour
thr.copyTo(con);

// Create sample and label data
vector > contours; // Vector for storing contour
vector hierarchy;
Mat sample;
Mat response_array;  
findContours( con, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); //Find contour

for( int i = 0; i

Code for training and testing

Mat thr,gray,con;
Mat thr,gray,con;
Mat src=imread("dig.png",1);
cvtColor(src,gray,CV_BGR2GRAY);
threshold(gray,thr,200,255,THRESH_BINARY_INV); // Threshold to create input
thr.copyTo(con);


// Read stored sample and label for training
Mat sample;
Mat response,tmp;
FileStorage Data("TrainingData.yml",FileStorage::READ); // Read traing data to a Mat
Data["data"] >> sample;
Data.release();

FileStorage Label("LabelData.yml",FileStorage::READ); // Read label data to a Mat
Label["label"] >> response;
Label.release();


KNearest knn;
knn.train(sample,response); // Train with sample and responses
cout > contours; // Vector for storing contour
vector hierarchy;

//Create input sample by contour finding and cropping
findContours( con, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
Mat dst(src.rows,src.cols,CV_8UC3,Scalar::all(0));

for( int i = 0; i

RESULT:
In the result the dot in the first line is detected as 8 because we haven’t trained our program for dot.
Also I am considering every contour in first hierarchy level as the sample input, user can avoid it by computing the area.

Recognizing day to day objects using Object Recognition in OpenCV (C++)
Simple Hand/Finger Tracking & Gesture Recognition
Editor :