Basic OCR in OpenCV

原文地址:http://blog.damiles.com/2008/11/basic-ocr-in-opencv/

代码下载:https://github.com/damiles/basicOCR

In this tutorial we go to create a basic number OCR. It consist to classify a handwrite number into his class.

To do it, we go to use all we learn in before tutorials, we go to use a simple basic painter and the basic pattern recognition and classification with openCV tutorial.

In a typical pattern recognition classifier consist in three modules:

Preprocessing: in this module we go to process our input image, for example size normalize, convert color to BN…

Feature extraction: in this module we convert our image processed to a characteristic vector of features to classify, it can be the pixels matrix convert to vector or get contour chain codes data representation

Classification module get the feature vectors and train our system or classify an input feature vector with a classify method as knn.

In this basic OCR we go to use this graph:

Where we get a train set and test set of image to train and test our classifier method (knn)

We have a 1000 handwrite images, 100 images of each number. We get 50 images of each number (class) to train and other 50 to test our system.

Then the first work we do is pre-process all train image, to do it we create a preprocessing function. In this function we get a image and a new width and height we want as result of preprocessing, then the function return a normalized size with bounding box image. You can see more clear the process in this graph:

Pre-processing code:

01 void findX(IplImage* imgSrc,int* min, int* max){
02 int i;
03 int minFound=0;
04 CvMat data;
05 CvScalar maxVal=cvRealScalar(imgSrc->width * 255);
06 CvScalar val=cvRealScalar(0);
07 //For each col sum, if sum < width*255 then we find the min
08 //then continue to end to search the max, if sum< width*255 then is new max
09 for (i=0; i< imgSrc->width; i++){
10 cvGetCol(imgSrc, &data, i);
11 val= cvSum(&data);
12 if(val.val[0] < maxVal.val[0]){
13 *max= i;
14 if(!minFound){
15 *min= i;
16 minFound= 1;
17 }
18 }
19 }
20 }
21  
22 void findY(IplImage* imgSrc,int* min, int* max){
23 int i;
24 int minFound=0;
25 CvMat data;
26 CvScalar maxVal=cvRealScalar(imgSrc->width * 255);
27 CvScalar val=cvRealScalar(0);
28 //For each col sum, if sum < width*255 then we find the min
29 //then continue to end to search the max, if sum< width*255 then is new max
30 for (i=0; i< imgSrc->height; i++){
31 cvGetRow(imgSrc, &data, i);
32 val= cvSum(&data);
33 if(val.val[0] < maxVal.val[0]){
34 *max=i;
35 if(!minFound){
36 *min= i;
37 minFound= 1;
38 }
39 }
40 }
41 }
42 CvRect findBB(IplImage* imgSrc){
43 CvRect aux;
44 int xmin, xmax, ymin, ymax;
45 xmin=xmax=ymin=ymax=0;
46  
47 findX(imgSrc, &xmin, &xmax);
48 findY(imgSrc, &ymin, &ymax);
49  
50 aux=cvRect(xmin, ymin, xmax-xmin, ymax-ymin);
51  
52 //printf("BB: %d,%d - %d,%d\n", aux.x, aux.y, aux.width, aux.height);
53  
54 return aux;
55  
56 }
57  
58 IplImage preprocessing(IplImage* imgSrc,int new_width, int new_height){
59 IplImage* result;
60 IplImage* scaledResult;
61  
62 CvMat data;
63 CvMat dataA;
64 CvRect bb;//bounding box
65 CvRect bba;//boundinb box maintain aspect ratio
66  
67 //Find bounding box
68 bb=findBB(imgSrc);
69  
70 //Get bounding box data and no with aspect ratio, the x and y can be corrupted
71 cvGetSubRect(imgSrc, &data, cvRect(bb.x, bb.y, bb.width, bb.height));
72 //Create image with this data with width and height with aspect ratio 1
73 //then we get highest size betwen width and height of our bounding box
74 int size=(bb.width>bb.height)?bb.width:bb.height;
75 result=cvCreateImage( cvSize( size, size ), 8, 1 );
76 cvSet(result,CV_RGB(255,255,255),NULL);
77 //Copy de data in center of image
78 int x=(int)floor((float)(size-bb.width)/2.0f);
79 int y=(int)floor((float)(size-bb.height)/2.0f);
80 cvGetSubRect(result, &dataA, cvRect(x,y,bb.width, bb.height));
81 cvCopy(&data, &dataA, NULL);
82 //Scale result
83 scaledResult=cvCreateImage( cvSize( new_width, new_height ), 8, 1 );
84 cvResize(result, scaledResult, CV_INTER_NN);
85  
86 //Return processed data
87 return *scaledResult;
88  
89 }

We use the function getData of basicOCR class to create the train data and train classes, this function get all images under OCR folder to create this train data, the OCR forlder is structured with 1 folder to each class and each file have are pbm files with this name cnn.pbm where c is the class {0..9} and nn is the number of image {00..99}

Each image we get is pre-processed and then convert the data in a feature vector we use.

basicOCR.cpp getData code:

01 void basicOCR::getData()
02 {
03 IplImage* src_image;
04 IplImage prs_image;
05 CvMat row,data;
06 char file[255];
07 int i,j;
08 for(i =0; i<classes; i++){
09 for( j = 0; j< train_samples; j++){
10  
11 //Load file
12 if(j<10)
13 sprintf(file,"%s%d/%d0%d.pbm",file_path, i, i , j);
14 else
15 sprintf(file,"%s%d/%d%d.pbm",file_path, i, i , j);
16 src_image = cvLoadImage(file,0);
17 if(!src_image){
18 printf("Error: Cant load image %s\n", file);
19 //exit(-1);
20 }
21 //process file
22 prs_image = preprocessing(src_image, size, size);
23  
24 //Set class label
25 cvGetRow(trainClasses, &row, i*train_samples + j);
26 cvSet(&row, cvRealScalar(i));
27 //Set data
28 cvGetRow(trainData, &row, i*train_samples + j);
29  
30 IplImage* img = cvCreateImage( cvSize( size, size ), IPL_DEPTH_32F, 1 );
31 //convert 8 bits image to 32 float image
32 cvConvertScale(&prs_image, img, 0.0039215, 0);
33  
34 cvGetSubRect(img, &data, cvRect(0,0, size,size));
35  
36 CvMat row_header, *row1;
37 //convert data matrix sizexsize to vecor
38 row1 = cvReshape( &data, &row_header, 0, 1 );
39 cvCopy(row1, &row, NULL);
40 }
41 }
42 }

After processed and get train data and classes whe then train our model with this data, in our sample we use knn method then:

1 knn=new CvKNearest( trainData, trainClasses, 0, false, K );

Then we now can test our model, and we can use the test result to compare to another methods we can use, or if we reduce the image scale or similar. There are a function to create the test in our basicOCR class, test function.

This function get the other 500 samples and classify this in our selected method and check the obtained result.

01 void basicOCR::test(){
02 IplImage* src_image;
03 IplImage prs_image;
04 CvMat row,data;
05 char file[255];
06 int i,j;
07 int error=0;
08 int testCount=0;
09 for(i =0; i<classes; i++){
10 for( j = 50; j< 50+train_samples; j++){
11  
12 sprintf(file,"%s%d/%d%d.pbm",file_path, i, i , j);
13 src_image = cvLoadImage(file,0);
14 if(!src_image){
15 printf("Error: Cant load image %s\n", file);
16 //exit(-1);
17 }
18 //process file
19 prs_image = preprocessing(src_image, size, size);
20 float r=classify(&prs_image,0);
21 if((int)r!=i)
22 error++;
23  
24 testCount++;
25 }
26 }
27 float totalerror=100*(float)error/(float)testCount;
28 printf("System Error: %.2f%%\n", totalerror);
29  
30 }

Test use the classify function that get image to classify, process image, get feature vector and classify it with a find_nearest of knn class. This function we use to classify the input user images:

01 float basicOCR::classify(IplImage* img, int showResult)
02 {
03 IplImage prs_image;
04 CvMat data;
05 CvMat* nearest=cvCreateMat(1,K,CV_32FC1);
06 float result;
07 //process file
08 prs_image = preprocessing(img, size, size);
09  
10 //Set data
11 IplImage* img32 = cvCreateImage( cvSize( size, size ), IPL_DEPTH_32F, 1 );
12 cvConvertScale(&prs_image, img32, 0.0039215, 0);
13 cvGetSubRect(img32, &data, cvRect(0,0, size,size));
14 CvMat row_header, *row1;
15 row1 = cvReshape( &data, &row_header, 0, 1 );
16  
17 result=knn->find_nearest(row1,K,0,0,nearest,0);
18  
19 int accuracy=0;
20 for(int i=0;i<K;i++){
21 if( nearest->data.fl[i] == result)
22 accuracy++;
23 }
24 float pre=100*((float)accuracy/(float)K);
25 if(showResult==1){
26 printf("|\t%.0f\t| \t%.2f%%  \t| \t%d of %d \t| \n",result,pre,accuracy,K);
27 printf(" ---------------------------------------------------------------\n");
28 }
29  
30 return result;
31  
32 }

All work or training and test is in basicOCR class, when we create a basicOCR instance then only we need call to classify function to classify our input image. Then we go to use basic Painter we create before in other tutorial to user interactivity to draw a image and classify it.

你可能感兴趣的:(opencv)