zoukankan      html  css  js  c++  java
  • 《Mastering Opencv ...读书笔记系列》车牌识别(II)

    http://blog.csdn.net/jinshengtao/article/details/17954427   《Mastering Opencv ...读书笔记系列》车牌识别(II)

    http://blog.csdn.net/jinshengtao/article/details/17883075/   《Mastering Opencv ...读书笔记系列》车牌识别(I)

    《Mastering Opencv ...读书笔记系列》车牌识别(II)

    标签: 车牌识别MLP西班牙
     9920人阅读 评论(5) 收藏 举报

       继上一篇文章后,现在要做的就是从车牌图像上使用optical character recognition算法将字符提取出来。对于每一块被检测的车牌,使用带监督的神经网络机器学习算法来识别字符。

    本文内容:

    1.字符分割 

    2.神经网络训练方法

    3.使用神经网络预测字符

     

    一、字符分割【OCR Segment】

    在使用神经网络对每个字符进行预测之前,我们必须从车牌图像中扣取改字符图片,因此有如下步骤:

    本文的输入图像为上一篇文章的车牌:


    a.二值化车牌


    b.求轮廓


    c.求最小外接矩形


    d.用纵横比及面积,筛选外接矩形


    e.调整统一矩形大小并保存每个字符的图片【注意:分割得到顺序和车牌字符顺序无关,可能不同】

     

    代码:

     

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. // car_plate_ann.cpp : 定义控制台应用程序的入口点。  
    2. //  
    3.   
    4. #include "stdafx.h"  
    5. #include <cv.h>  
    6. #include <highgui.h>  
    7. #include <cvaux.h>  
    8. #include <ml.h>  
    9. #define HORIZONTAL    1  
    10. #define VERTICAL    0  
    11. using namespace std;  
    12. using namespace cv;  
    13.   
    14. //typedef struct CharSegment{  
    15. //  Mat img;  
    16. //  Rect mr;  
    17. //  CharSegment(Mat a,Rect b){  
    18. //      img=a;  
    19. //      mr=b;  
    20. //  }  
    21. //};  
    22.   
    23. bool verifySizes(Mat r){  
    24.     //Char sizes 45x77  
    25.     float aspect=45.0f/77.0f;  
    26.     float charAspect= (float)r.cols/(float)r.rows;  
    27.     float error=0.35;  
    28.     float minHeight=15;  
    29.     float maxHeight=28;  
    30.     //We have a different aspect ratio for number 1, and it can be ~0.2  
    31.     float minAspect=0.2;  
    32.     float maxAspect=aspect+aspect*error;  
    33.     //area of pixels  
    34.     float area=countNonZero(r);  
    35.     //bb area  
    36.     float bbArea=r.cols*r.rows;  
    37.     //% of pixel in area  
    38.     float percPixels=area/bbArea;  
    39.   
    40.     /*if(DEBUG) 
    41.         cout << "Aspect: "<< aspect << " ["<< minAspect << "," << maxAspect << "] "  << "Area "<< percPixels <<" Char aspect " << charAspect  << " Height char "<< r.rows << " ";*/  
    42.     if(percPixels < 0.8 && charAspect > minAspect && charAspect < maxAspect && r.rows >= minHeight && r.rows < maxHeight)  
    43.         return true;  
    44.     else  
    45.         return false;  
    46.   
    47. }  
    48.   
    49. Mat preprocessChar(Mat in){  
    50.     //Remap image  
    51.     int h=in.rows;  
    52.     int w=in.cols;  
    53.     int charSize=20;    //统一每个字符的大小  
    54.     Mat transformMat=Mat::eye(2,3,CV_32F);  
    55.     int m=max(w,h);  
    56.     transformMat.at<float>(0,2)=m/2 - w/2;  
    57.     transformMat.at<float>(1,2)=m/2 - h/2;  
    58.   
    59.     Mat warpImage(m,m, in.type());  
    60.     warpAffine(in, warpImage, transformMat, warpImage.size(), INTER_LINEAR, BORDER_CONSTANT, Scalar(0) );  
    61.   
    62.     Mat out;  
    63.     resize(warpImage, out, Size(charSize, charSize) );   
    64.   
    65.     return out;  
    66. }  
    67.   
    68. //create the accumulation histograms,img is a binary image, t is 水平或垂直  
    69. Mat ProjectedHistogram(Mat img, int t)  
    70. {  
    71.     int sz=(t)?img.rows:img.cols;  
    72.     Mat mhist=Mat::zeros(1,sz,CV_32F);  
    73.   
    74.     for(int j=0; j<sz; j++){  
    75.         Mat data=(t)?img.row(j):img.col(j);  
    76.         mhist.at<float>(j)=countNonZero(data);    //统计这一行或一列中,非零元素的个数,并保存到mhist中  
    77.     }  
    78.   
    79.     //Normalize histogram  
    80.     double min, max;  
    81.     minMaxLoc(mhist, &min, &max);  
    82.   
    83.     if(max>0)  
    84.         mhist.convertTo(mhist,-1 , 1.0f/max, 0);//用mhist直方图中的最大值,归一化直方图  
    85.   
    86.     return mhist;  
    87. }  
    88.   
    89. Mat getVisualHistogram(Mat *hist, int type)  
    90. {  
    91.   
    92.     int size=100;  
    93.     Mat imHist;  
    94.   
    95.   
    96.     if(type==HORIZONTAL){  
    97.         imHist.create(Size(size,hist->cols), CV_8UC3);  
    98.     }else{  
    99.         imHist.create(Size(hist->cols, size), CV_8UC3);  
    100.     }  
    101.   
    102.     imHist=Scalar(55,55,55);  
    103.   
    104.     for(int i=0;i<hist->cols;i++){  
    105.         float value=hist->at<float>(i);  
    106.         int maxval=(int)(value*size);  
    107.   
    108.         Point pt1;  
    109.         Point pt2, pt3, pt4;  
    110.   
    111.         if(type==HORIZONTAL){  
    112.             pt1.x=pt3.x=0;  
    113.             pt2.x=pt4.x=maxval;  
    114.             pt1.y=pt2.y=i;  
    115.             pt3.y=pt4.y=i+1;  
    116.   
    117.             line(imHist, pt1, pt2, CV_RGB(220,220,220),1,8,0);  
    118.             line(imHist, pt3, pt4, CV_RGB(34,34,34),1,8,0);  
    119.   
    120.             pt3.y=pt4.y=i+2;  
    121.             line(imHist, pt3, pt4, CV_RGB(44,44,44),1,8,0);  
    122.             pt3.y=pt4.y=i+3;  
    123.             line(imHist, pt3, pt4, CV_RGB(50,50,50),1,8,0);  
    124.         }else{  
    125.   
    126.             pt1.x=pt2.x=i;  
    127.             pt3.x=pt4.x=i+1;  
    128.             pt1.y=pt3.y=100;  
    129.             pt2.y=pt4.y=100-maxval;  
    130.   
    131.   
    132.             line(imHist, pt1, pt2, CV_RGB(220,220,220),1,8,0);  
    133.             line(imHist, pt3, pt4, CV_RGB(34,34,34),1,8,0);  
    134.   
    135.             pt3.x=pt4.x=i+2;  
    136.             line(imHist, pt3, pt4, CV_RGB(44,44,44),1,8,0);  
    137.             pt3.x=pt4.x=i+3;  
    138.             line(imHist, pt3, pt4, CV_RGB(50,50,50),1,8,0);  
    139.   
    140.         }  
    141.   
    142.     }  
    143.   
    144.     return imHist ;  
    145. }  
    146.   
    147. void drawVisualFeatures(Mat character, Mat hhist, Mat vhist, Mat lowData,int count){  
    148.     Mat img(121, 121, CV_8UC3, Scalar(0,0,0));  
    149.     Mat ch;  
    150.     Mat ld;  
    151.     char res[20];  
    152.   
    153.     cvtColor(character, ch, CV_GRAY2RGB);  
    154.   
    155.     resize(lowData, ld, Size(100, 100), 0, 0, INTER_NEAREST );//将ld从15*15扩大到100*100  
    156.     cvtColor(ld,ld,CV_GRAY2RGB);  
    157.   
    158.     Mat hh=getVisualHistogram(&hhist, HORIZONTAL);  
    159.     Mat hv=getVisualHistogram(&vhist, VERTICAL);  
    160.   
    161.     //Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height)  
    162.     Mat subImg=img(Rect(0,101,20,20));//ch:20*20  
    163.     ch.copyTo(subImg);  
    164.   
    165.     subImg=img(Rect(21,101,100,20));//hh:100*hist.cols  
    166.     hh.copyTo(subImg);  
    167.   
    168.     subImg=img(Rect(0,0,20,100));//hv:hist.cols*100  
    169.     hv.copyTo(subImg);  
    170.   
    171.     subImg=img(Rect(21,0,100,100));//ld:100*100  
    172.     ld.copyTo(subImg);  
    173.   
    174.     line(img, Point(0,100), Point(121,100), Scalar(0,0,255));  
    175.     line(img, Point(20,0), Point(20,121), Scalar(0,0,255));  
    176.   
    177.     sprintf(res,"hist%d.jpg",count);  
    178.     imwrite(res,img);  
    179.     //imshow("Visual Features", img);  
    180.   
    181.     cvWaitKey(0);  
    182. }  
    183.   
    184.   
    185. Mat features(Mat in, int sizeData,int count){  
    186.     //Histogram features  
    187.     Mat vhist=ProjectedHistogram(in,VERTICAL);  
    188.     Mat hhist=ProjectedHistogram(in,HORIZONTAL);  
    189.   
    190.     //Low data feature  
    191.     Mat lowData;  
    192.     resize(in, lowData, Size(sizeData, sizeData) );  
    193.   
    194.     //画出直方图  
    195.     drawVisualFeatures(in, hhist, vhist, lowData,count);  
    196.   
    197.   
    198.   
    199.     //Last 10 is the number of moments components  
    200.     int numCols=vhist.cols+hhist.cols+lowData.cols*lowData.cols;  
    201.   
    202.     Mat out=Mat::zeros(1,numCols,CV_32F);  
    203.     //Asign values to feature,ANN的样本特征为水平、垂直直方图和低分辨率图像所组成的矢量  
    204.     int j=0;  
    205.     for(int i=0; i<vhist.cols; i++)  
    206.     {  
    207.         out.at<float>(j)=vhist.at<float>(i);  
    208.         j++;  
    209.     }  
    210.     for(int i=0; i<hhist.cols; i++)  
    211.     {  
    212.         out.at<float>(j)=hhist.at<float>(i);  
    213.         j++;  
    214.     }  
    215.     for(int x=0; x<lowData.cols; x++)  
    216.     {  
    217.         for(int y=0; y<lowData.rows; y++){  
    218.             out.at<float>(j)=(float)lowData.at<unsigned char>(x,y);  
    219.             j++;  
    220.         }  
    221.     }  
    222.     //if(DEBUG)  
    223.     //  cout << out << " =========================================== ";  
    224.     return out;  
    225. }  
    226.   
    227. int _tmain(int argc, _TCHAR* argv[])  
    228. {  
    229.     Mat input = imread("haha_1.jpg",CV_LOAD_IMAGE_GRAYSCALE);  
    230.     char res[20];  
    231.     int i = 0;  
    232.     //vector<CharSegment> output;  
    233.   
    234.     //Threshold input image  
    235.     Mat img_threshold;  
    236.     threshold(input, img_threshold, 60, 255, CV_THRESH_BINARY_INV);  
    237.   
    238.     Mat img_contours;  
    239.     img_threshold.copyTo(img_contours);  
    240.     //Find contours of possibles characters  
    241.     vector< vector< Point> > contours;  
    242.     findContours(img_contours,  
    243.         contours, // a vector of contours  
    244.         CV_RETR_EXTERNAL, // retrieve the external contours  
    245.         CV_CHAIN_APPROX_NONE); // all pixels of each contours  
    246.   
    247.     // Draw blue contours on a white image  
    248.     cv::Mat result;  
    249.     input.copyTo(result);  
    250.     cvtColor(result, result, CV_GRAY2RGB);  
    251.     //cv::drawContours(result,contours,  
    252.     //  -1, // draw all contours  
    253.     //  cv::Scalar(0,0,255), // in blue  
    254.     //  1); // with a thickness of 1  
    255.       
    256.     //Start to iterate to each contour founded  
    257.     vector<vector<Point> >::iterator itc= contours.begin();  
    258.   
    259.     //Remove patch that are no inside limits of aspect ratio and area.      
    260.     while (itc!=contours.end()) {  
    261.   
    262.         //Create bounding rect of object  
    263.         Rect mr= boundingRect(Mat(*itc));  
    264.         //rectangle(result, mr, Scalar(255,0,0),2);  
    265.         //Crop image  
    266.         Mat auxRoi(img_threshold, mr);  
    267.         if(verifySizes(auxRoi)){  
    268.             auxRoi=preprocessChar(auxRoi);  
    269.             //output.push_back(CharSegment(auxRoi, mr));  
    270.               
    271.             //保存每个字符图片  
    272.             sprintf(res,"train_data_%d.jpg",i);  
    273.             i++;  
    274.             imwrite(res,auxRoi);  
    275.             rectangle(result, mr, Scalar(0,0,255),2);  
    276.   
    277.   
    278.             //对每一个小方块,提取直方图特征  
    279.             Mat f=features(auxRoi,15,i);  
    280.         }  
    281.         ++itc;  
    282.     }  
    283.   
    284.     imwrite("result1.jpg",result);  
    285.     imshow("car_plate",result);  
    286.     waitKey(0);  
    287.     return 0;  
    288. }  

    图片显示可以自己边注释边显示,另外提前给出了第二部分的累计水平垂直直方图和低分辨率采样的方法,并把这种特征的图像保存下来了。

     

     

     

    二、神经网络训练

    1.多层感知机简介:

    多层感知机结构:【隐层数量为1层或多层,实际上自从引入了深度学习后,才有多层】

    其中,每个神经元结构如下:

    每个神经元都是相似的且每个神经元都有自己的判定边界,有多个输入和多个输出。不同权重的输入结合激励函数得到不同的输出。常见的激励函数有S型、高斯型、上图的hadrlim型。单层的单个神经元可以将输入向量分为两类,而一个有S个神经元的感知机,可以将输入向量分为2^S类

     

    2.获取训练数据

    和上一篇训练SVM所使用的特征不同,现在使用每个字符的累计直方图和低分辨率采样图像构成的高维向量作为训练神经网络的特征。训练的样本矩阵P为N*M,其中N(行)代表各个样本图片的融合特征,M(列)为类别。从书中给的已经训练好的orc.xml看,N有675行,M有30列,30列代表西班牙车牌有30种字符0-9和20个英文字母组成,675是这么来的,比如字符0有35张图片样本,对应产生35行高维向量,字符1有40张样本图片,对应产生40行高维向量,然后按照不同分辨率5*5、10*10、15*15、20*20采样【书中ocr.xml只有675,只采用5*5分辨率】。矩阵P实际上是对每一种高维向量的类别标注:

      在Opencv中使用多层感知机需要配置training data矩阵、classes矩阵、隐层神经元数量。其中,训练数据矩阵和列别标识矩阵均从ocr.xml文件获取【下文会介绍】,这里只采用单隐层,包含10个神经元,输入层为675行,输出层为30行。

      计算ocr.xml文件具体步骤:

    a.将上一步分割得到的每个字符进行人工分类【可放在不同目录下】,比如最终字符0有35张图片,字符a有30张图片并定义数组【这些数字之和为675】:

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. const int numFilesChars[]={35, 40, 42, 41, 42, 33, 30, 31, 49, 44, 30, 24, 21, 20, 34, 9, 10, 3, 11, 3, 15, 4, 9, 12, 10, 21, 18, 8, 15, 7};  
    b.读取某个字符目录下的一张图片,提取累计直方图特征和不同低分辨率图像,具体如下:
    (1)统计水平、垂直方向直方图,比如水平直方图,扫描图像每一行,统计每行非零元素的个数,这样就构成1*row矩阵,然后用该矩阵的最大值,规范化该矩阵。
    (2)使用resize函数,按照不同分辨率得到图像矩阵
    (3)将垂直直方图,水平直方图,低分辨率图像【按行读取】,都存进一个1*(vcol+hcol+h*w)的矩阵
    (4)将上述矩阵连同标记一起写入xml文件中
    累计直方图及低分辨率图像效果如下:【左下角为字符图像原始大小20*20,由上角为低分辨率采样后放大的图像100*100,右下角为水平直方图,左上角为垂直直方图】

     

     

    具体训练代码为:

     

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. // Main entry code OpenCV  
    2.   
    3. #include <cv.h>  
    4. #include <highgui.h>  
    5. #include <cvaux.h>  
    6.   
    7. #include <iostream>  
    8. #include <vector>  
    9. #define HORIZONTAL    1  
    10. #define VERTICAL    0  
    11. using namespace std;  
    12. using namespace cv;  
    13.   
    14. //西班牙车牌共30种字符,下面为每个字符的图片个数【没给,需人工挑选】  
    15. const int numFilesChars[]={35, 40, 42, 41, 42, 33, 30, 31, 49, 44, 30, 24, 21, 20, 34, 9, 10, 3, 11, 3, 15, 4, 9, 12, 10, 21, 18, 8, 15, 7};  
    16. const char strCharacters[] = {'0','1','2','3','4','5','6','7','8','9','B''C''D''F''G''H''J''K''L''M''N''P''R''S''T''V''W''X''Y''Z'};  
    17. const int numCharacters=30;  
    18.   
    19.   
    20. Mat features(Mat in, int sizeData,int count){  
    21.     //Histogram features  
    22.     Mat vhist=ProjectedHistogram(in,VERTICAL);  
    23.     Mat hhist=ProjectedHistogram(in,HORIZONTAL);  
    24.   
    25.     //Low data feature  
    26.     Mat lowData;  
    27.     resize(in, lowData, Size(sizeData, sizeData) );  
    28.   
    29.     //Last 10 is the number of moments components  
    30.     int numCols=vhist.cols+hhist.cols+lowData.cols*lowData.cols;  
    31.   
    32.     Mat out=Mat::zeros(1,numCols,CV_32F);  
    33.     //Asign values to feature,ANN的样本特征为水平、垂直直方图和低分辨率图像所组成的矢量  
    34.     int j=0;  
    35.     for(int i=0; i<vhist.cols; i++)  
    36.     {  
    37.         out.at<float>(j)=vhist.at<float>(i);  
    38.         j++;  
    39.     }  
    40.     for(int i=0; i<hhist.cols; i++)  
    41.     {  
    42.         out.at<float>(j)=hhist.at<float>(i);  
    43.         j++;  
    44.     }  
    45.     for(int x=0; x<lowData.cols; x++)  
    46.     {  
    47.         for(int y=0; y<lowData.rows; y++){  
    48.             out.at<float>(j)=(float)lowData.at<unsigned char>(x,y);  
    49.             j++;  
    50.         }  
    51.     }  
    52.     //if(DEBUG)  
    53.     //  cout << out << " =========================================== ";  
    54.     return out;  
    55. }  
    56.   
    57. int main ( int argc, char** argv )  
    58. {  
    59.     cout << "OpenCV Training OCR Automatic Number Plate Recognition ";  
    60.     cout << " ";  
    61.   
    62.     char* path;  
    63.       
    64.     //Check if user specify image to process  
    65.     if(argc >= 1 )  
    66.     {  
    67.         path= argv[1];  
    68.       
    69.     }else{  
    70.         cout << "Usage: " << argv[0] << " <path to chars folders files>  ";  
    71.         return 0;  
    72.     }          
    73.   
    74.   
    75.   
    76.   
    77.   
    78.   
    79.     Mat classes;  
    80.     Mat trainingDataf5;  
    81.     Mat trainingDataf10;  
    82.     Mat trainingDataf15;  
    83.     Mat trainingDataf20;  
    84.   
    85.     vector<int> trainingLabels;  
    86.     OCR ocr;  
    87.   
    88.     for(int i=0; i< numCharacters; i++)  
    89.     {  
    90.         int numFiles=numFilesChars[i];  
    91.         for(int j=0; j< numFiles; j++){  
    92.             cout << "Character "<< strCharacters[i] << " file: " << j << " ";  
    93.             stringstream ss(stringstream::in | stringstream::out);  
    94.             ss << path << strCharacters[i] << "/" << j << ".jpg";  
    95.             Mat img=imread(ss.str(), 0);  
    96.             Mat f5=features(img, 5);  
    97.             Mat f10=features(img, 10);  
    98.             Mat f15=features(img, 15);  
    99.             Mat f20=features(img, 20);  
    100.   
    101.             trainingDataf5.push_back(f5);  
    102.             trainingDataf10.push_back(f10);  
    103.             trainingDataf15.push_back(f15);  
    104.             trainingDataf20.push_back(f20);  
    105.             trainingLabels.push_back(i);            //每一幅字符图片所对应的字符类别索引下标  
    106.         }  
    107.     }  
    108.   
    109.       
    110.     trainingDataf5.convertTo(trainingDataf5, CV_32FC1);  
    111.     trainingDataf10.convertTo(trainingDataf10, CV_32FC1);  
    112.     trainingDataf15.convertTo(trainingDataf15, CV_32FC1);  
    113.     trainingDataf20.convertTo(trainingDataf20, CV_32FC1);  
    114.     Mat(trainingLabels).copyTo(classes);  
    115.   
    116.     FileStorage fs("OCR.xml", FileStorage::WRITE);  
    117.     fs << "TrainingDataF5" << trainingDataf5;  
    118.     fs << "TrainingDataF10" << trainingDataf10;  
    119.     fs << "TrainingDataF15" << trainingDataf15;  
    120.     fs << "TrainingDataF20" << trainingDataf20;  
    121.     fs << "classes" << classes;  
    122.     fs.release();  
    123.   
    124.     return 0;  
    125. }  

    三、使用神经网络检测字符
    a.读取一张车牌图像
    b.配置神经网络参数,并使用xml文件训练神经网络【参数配置上述已经说过了】
    c.提取该车牌图像的累计直方图和低分辨率图像特征矩阵
    d.将该特征矩阵作为神经网络输入,经网络计算,得到预测结果【字符索引】
    e.按照每个字符图像的相对位置,进行字符重新排序
    f.得到最终字符【和书中不同的是,我的输入图像是车牌而不是整幅图像,因此绝对坐标是不同的,但字符间的相对位置还是对的,只是不能在车牌照片上显示数字而已,我直接答应到控制台上】

     

     

    具体代码:

    又用到了车牌类,这里面有车牌字符相对位置调整的函数,都给出来吧:

    Plate.h:

     

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #ifndef Plate_h  
    2. #define Plate_h  
    3.   
    4. #include <string.h>  
    5. #include <vector>  
    6.   
    7. #include <cv.h>  
    8. #include <highgui.h>  
    9. #include <cvaux.h>  
    10.   
    11. using namespace std;  
    12. using namespace cv;  
    13.   
    14. class Plate{  
    15.     public:  
    16.         Plate();  
    17.         Plate(Mat img, Rect pos);  
    18.         string str();  
    19.         Rect position;  
    20.         Mat plateImg;  
    21.         vector<char> chars;  
    22.         vector<Rect> charsPos;          
    23. };  
    24.   
    25. #endif  

    Plate.cpp:

     

     

     

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. /***************************************************************************** 
    2. *   Number Plate Recognition using SVM and Neural Networks 
    3. ****************************************************************************** 
    4. *   by David Mill醤 Escriv? 5th Dec 2012 
    5. *   http://blog.damiles.com 
    6. ****************************************************************************** 
    7. *   Ch5 of the book "Mastering OpenCV with Practical Computer Vision Projects" 
    8. *   Copyright Packt Publishing 2012. 
    9. *   http://www.packtpub.com/cool-projects-with-opencv/book 
    10. *****************************************************************************/  
    11.   
    12. #include "Plate.h"  
    13.   
    14. Plate::Plate(){  
    15. }  
    16.   
    17. Plate::Plate(Mat img, Rect pos){  
    18.     plateImg=img;  
    19.     position=pos;  
    20. }  
    21.   
    22. string Plate::str(){  
    23.     string result="";  
    24.     //Order numbers  
    25.     vector<int> orderIndex;  
    26.     vector<int> xpositions;  
    27.     for(int i=0; i< charsPos.size(); i++){  
    28.         orderIndex.push_back(i);  
    29.         xpositions.push_back(charsPos[i].x);  
    30.     }  
    31.     float min=xpositions[0];  
    32.     int minIdx=0;  
    33.     for(int i=0; i< xpositions.size(); i++){  
    34.         min=xpositions[i];  
    35.         minIdx=i;  
    36.         for(int j=i; j<xpositions.size(); j++){  
    37.             if(xpositions[j]<min){  
    38.                 min=xpositions[j];  
    39.                 minIdx=j;  
    40.             }  
    41.         }  
    42.         int aux_i=orderIndex[i];  
    43.         int aux_min=orderIndex[minIdx];  
    44.         orderIndex[i]=aux_min;  
    45.         orderIndex[minIdx]=aux_i;  
    46.           
    47.         float aux_xi=xpositions[i];  
    48.         float aux_xmin=xpositions[minIdx];  
    49.         xpositions[i]=aux_xmin;  
    50.         xpositions[minIdx]=aux_xi;  
    51.     }  
    52.     for(int i=0; i<orderIndex.size(); i++){  
    53.         result=result+chars[orderIndex[i]];  
    54.     }  
    55.     return result;  
    56. }  

    主要处理的函数:

     

     

     

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. // car_plate_classify.cpp : 定义控制台应用程序的入口点。  
    2. //  
    3.   
    4. #include "stdafx.h"  
    5. #include <cv.h>  
    6. #include <highgui.h>  
    7. #include <cvaux.h>  
    8. #include <ml.h>  
    9.   
    10. #include <iostream>  
    11. #include <vector>  
    12. #include "Plate.h"  
    13. #define HORIZONTAL    1  
    14. #define VERTICAL    0  
    15. using namespace std;  
    16. using namespace cv;  
    17.   
    18. CvANN_MLP  ann;  
    19. const char strCharacters[] = {'0','1','2','3','4','5','6','7','8','9','B''C''D''F''G''H''J''K''L''M''N''P''R''S''T''V''W''X''Y''Z'};  
    20. const int numCharacters=30;  
    21.   
    22. bool verifySizes(Mat r){  
    23.     //Char sizes 45x77  
    24.     float aspect=45.0f/77.0f;  
    25.     float charAspect= (float)r.cols/(float)r.rows;  
    26.     float error=0.35;  
    27.     float minHeight=15;  
    28.     float maxHeight=28;  
    29.     //We have a different aspect ratio for number 1, and it can be ~0.2  
    30.     float minAspect=0.2;  
    31.     float maxAspect=aspect+aspect*error;  
    32.     //area of pixels  
    33.     float area=countNonZero(r);  
    34.     //bb area  
    35.     float bbArea=r.cols*r.rows;  
    36.     //% of pixel in area  
    37.     float percPixels=area/bbArea;  
    38.   
    39.     /*if(DEBUG) 
    40.     cout << "Aspect: "<< aspect << " ["<< minAspect << "," << maxAspect << "] "  << "Area "<< percPixels <<" Char aspect " << charAspect  << " Height char "<< r.rows << " ";*/  
    41.     if(percPixels < 0.8 && charAspect > minAspect && charAspect < maxAspect && r.rows >= minHeight && r.rows < maxHeight)  
    42.         return true;  
    43.     else  
    44.         return false;  
    45.   
    46. }  
    47.   
    48. Mat preprocessChar(Mat in){  
    49.     //Remap image  
    50.     int h=in.rows;  
    51.     int w=in.cols;  
    52.     int charSize=20;    //统一每个字符的大小  
    53.     Mat transformMat=Mat::eye(2,3,CV_32F);  
    54.     int m=max(w,h);  
    55.     transformMat.at<float>(0,2)=m/2 - w/2;  
    56.     transformMat.at<float>(1,2)=m/2 - h/2;  
    57.   
    58.     Mat warpImage(m,m, in.type());  
    59.     warpAffine(in, warpImage, transformMat, warpImage.size(), INTER_LINEAR, BORDER_CONSTANT, Scalar(0) );  
    60.   
    61.     Mat out;  
    62.     resize(warpImage, out, Size(charSize, charSize) );   
    63.   
    64.     return out;  
    65. }  
    66.   
    67. //create the accumulation histograms,img is a binary image, t is 水平或垂直  
    68. Mat ProjectedHistogram(Mat img, int t)  
    69. {  
    70.     int sz=(t)?img.rows:img.cols;  
    71.     Mat mhist=Mat::zeros(1,sz,CV_32F);  
    72.   
    73.     for(int j=0; j<sz; j++){  
    74.         Mat data=(t)?img.row(j):img.col(j);  
    75.         mhist.at<float>(j)=countNonZero(data);    //统计这一行或一列中,非零元素的个数,并保存到mhist中  
    76.     }  
    77.   
    78.     //Normalize histogram  
    79.     double min, max;  
    80.     minMaxLoc(mhist, &min, &max);  
    81.   
    82.     if(max>0)  
    83.         mhist.convertTo(mhist,-1 , 1.0f/max, 0);//用mhist直方图中的最大值,归一化直方图  
    84.   
    85.     return mhist;  
    86. }  
    87.   
    88. Mat features(Mat in, int sizeData){  
    89.     //Histogram features  
    90.     Mat vhist=ProjectedHistogram(in,VERTICAL);  
    91.     Mat hhist=ProjectedHistogram(in,HORIZONTAL);  
    92.   
    93.     //Low data feature  
    94.     Mat lowData;  
    95.     resize(in, lowData, Size(sizeData, sizeData) );  
    96.   
    97.     //Last 10 is the number of moments components  
    98.     int numCols=vhist.cols+hhist.cols+lowData.cols*lowData.cols;  
    99.   
    100.     Mat out=Mat::zeros(1,numCols,CV_32F);  
    101.     //Asign values to feature,ANN的样本特征为水平、垂直直方图和低分辨率图像所组成的矢量  
    102.     int j=0;  
    103.     for(int i=0; i<vhist.cols; i++)  
    104.     {  
    105.         out.at<float>(j)=vhist.at<float>(i);  
    106.         j++;  
    107.     }  
    108.     for(int i=0; i<hhist.cols; i++)  
    109.     {  
    110.         out.at<float>(j)=hhist.at<float>(i);  
    111.         j++;  
    112.     }  
    113.     for(int x=0; x<lowData.cols; x++)  
    114.     {  
    115.         for(int y=0; y<lowData.rows; y++){  
    116.             out.at<float>(j)=(float)lowData.at<unsigned char>(x,y);  
    117.             j++;  
    118.         }  
    119.     }  
    120.       
    121.     return out;  
    122. }  
    123.   
    124.   
    125. int classify(Mat f){  
    126.     int result=-1;  
    127.     Mat output(1, 30, CV_32FC1); //西班牙车牌只有30种字符  
    128.     ann.predict(f, output);  
    129.     Point maxLoc;  
    130.     double maxVal;  
    131.     minMaxLoc(output, 0, &maxVal, 0, &maxLoc);  
    132.     //We need know where in output is the max val, the x (cols) is the class.  
    133.   
    134.     return maxLoc.x;  
    135. }  
    136.   
    137. void train(Mat TrainData, Mat classes, int nlayers){  
    138.     Mat layers(1,3,CV_32SC1);  
    139.     layers.at<int>(0)= TrainData.cols;  
    140.     layers.at<int>(1)= nlayers;  
    141.     layers.at<int>(2)= 30;  
    142.     ann.create(layers, CvANN_MLP::SIGMOID_SYM, 1, 1);  
    143.   
    144.     //Prepare trainClases  
    145.     //Create a mat with n trained data by m classes  
    146.     Mat trainClasses;  
    147.     trainClasses.create( TrainData.rows, 30, CV_32FC1 );  
    148.     forint i = 0; i <  trainClasses.rows; i++ )  
    149.     {  
    150.         forint k = 0; k < trainClasses.cols; k++ )  
    151.         {  
    152.             //If class of data i is same than a k class  
    153.             if( k == classes.at<int>(i) )  
    154.                 trainClasses.at<float>(i,k) = 1;  
    155.             else  
    156.                 trainClasses.at<float>(i,k) = 0;  
    157.         }  
    158.     }  
    159.     Mat weights( 1, TrainData.rows, CV_32FC1, Scalar::all(1) );  
    160.   
    161.     //Learn classifier  
    162.     ann.train( TrainData, trainClasses, weights );  
    163. }  
    164.   
    165. int _tmain(int argc, _TCHAR* argv[])  
    166. {  
    167.     Mat input = imread("test.jpg",CV_LOAD_IMAGE_GRAYSCALE);  
    168.     Plate mplate;  
    169.     //Read file storage.  
    170.     FileStorage fs;  
    171.     fs.open("OCR.xml", FileStorage::READ);  
    172.     Mat TrainingData;  
    173.     Mat Classes;  
    174.     fs["TrainingDataF15"] >> TrainingData;  
    175.     fs["classes"] >> Classes;  
    176.     //训练神经网络  
    177.     train(TrainingData, Classes, 10);  
    178.   
    179. //dealing image and save each character image into vector<CharSegment>  
    180.     //Threshold input image  
    181.     Mat img_threshold;  
    182.     threshold(input, img_threshold, 60, 255, CV_THRESH_BINARY_INV);  
    183.   
    184.     Mat img_contours;  
    185.     img_threshold.copyTo(img_contours);  
    186.     //Find contours of possibles characters  
    187.     vector< vector< Point> > contours;  
    188.     findContours(img_contours,  
    189.         contours, // a vector of contours  
    190.         CV_RETR_EXTERNAL, // retrieve the external contours  
    191.         CV_CHAIN_APPROX_NONE); // all pixels of each contours  
    192.     //Start to iterate to each contour founded  
    193.     vector<vector<Point> >::iterator itc= contours.begin();  
    194.   
    195.     //Remove patch that are no inside limits of aspect ratio and area.      
    196.     while (itc!=contours.end()) {  
    197.   
    198.         //Create bounding rect of object  
    199.         Rect mr= boundingRect(Mat(*itc));  
    200.         //rectangle(result, mr, Scalar(255,0,0),2);  
    201.         //Crop image  
    202.         Mat auxRoi(img_threshold, mr);  
    203.         if(verifySizes(auxRoi)){  
    204.             auxRoi=preprocessChar(auxRoi);  
    205.   
    206.             //对每一个小方块,提取直方图特征  
    207.             Mat f=features(auxRoi,15);  
    208.             //For each segment feature Classify  
    209.             int character=classify(f);  
    210.             mplate.chars.push_back(strCharacters[character]);  
    211.             mplate.charsPos.push_back(mr);  
    212.             //printf("%c ",strCharacters[character]);  
    213.         }  
    214.         ++itc;  
    215.     }  
    216.     string licensePlate=mplate.str();  
    217.     cout<<licensePlate<<endl;  
    218.       
    219.     return 0;  
    220. }  

     


    这边运行时间略长,大概10s以下吧。这就是android不能做太多图像处理的原因,运行速度不给力啊。

    上上后面做的评估是对隐层神经元数量和不同分辨率的一种统计,没多大花头,以后要用再看吧。而且车牌识别已经做烂了,没什么动力了~~

     

    好吧,下一篇尝试将车牌检测与识别都移植到android上试试。

     
     

    《Mastering Opencv ...读书笔记系列》车牌识别(I)

    标签: 车牌分割svm西班牙
     18303人阅读 评论(23) 收藏 举报
     分类:
     

    一、ANPR简介:

      Automatic Number Plate Recognition (ANPR),,是一种使用Optical Character Recognition (OCR)和其他分割、检测方法来读取汽车注册牌照的算法。最好的ANPR算法结果是由红外线照相机拍摄图片得到的。因为车牌的特殊材质,夜间会有逆反射效果,看不清车牌。但是现在我们不使用IR图片,我们使用常规图片,这样就增加了我们检测错误和识别错误的等级,以显示我们的算法有多牛逼【老外的意思,有逆反射的图片我没试过】。下面给出,反射、散射、逆反射的示意图:

      每个国家的车牌规格都不一样,这里使用西班牙的车牌,左边4个为数字,右边2个为字母,车牌以白色为背景。具体字符间隔如下图所示:

    ANPR算法大体分为两个步骤:

    1.车牌检测:检测车牌在图像中的位置

    2.车牌识别:使用OCR算法检测车牌上的字母数字字符

    这篇博文今天只讲车牌检测【提取车牌、SVM如何训练】,车牌识别为下一篇博文,搬到android系统为下下篇博文

    二、车牌检测

      大体也分为两个步骤:

    1.图像分割:采用一系列不同的滤波器、形态学操作、轮廓算法和验证算法,提取图像中可能包含车牌的区域。

    2.图像分类:对每个图像块使用支持向量机SVM分类,并由代码自动创建正负样本【正:有车牌,负:无车牌】(车牌规格统一:800像素宽,拍摄位置大概离车2-4米远)

    整个车牌检测部分,会涉及以下内容:

     Sobel filter

     Threshold operation

     Close morphologic operation

     Mask of one filled area

     Possible detected plates marked in red (features images)

     Detected plates after the SVM classifier

       假设车牌图片没有旋转和变形,则车牌分割的一个重要特征是车牌中有大量的垂直边缘。这个特征可以通过在第一阶段剔除没有任何垂直边缘的区域来提取。车牌原图:

    具体算法步骤如下:

    1.将彩色图像转化为灰度图,并采用5*5模版对图像进行高斯模糊来退出由照相机或其他环境噪声(如果不这么做,我们会得到很多垂直边缘,导致错误检测。)

    2.使用Sobel滤波器求一阶水平方向导数,以此寻找垂直边缘

    3.使用Otsu自适应阈值算法获得图像二值化的阈值,并由此得到一副二值画图片

    4.采用闭操作,去除每个垂直边缘线之间的空白空格,并连接所有包含 大量边缘的区域(这步过后,我们将有许多包含车牌的候选区域)

    5.由于大多数区域并不包含车牌,我们使用轮廓外接矩形的纵横比和区域面积,对这些区域进行区分。

    a.首先使用findContours找到外部轮廓

    b.使用minAreaRect获得这些轮廓的最小外接矩形,存储在vector向量中

    c.使用面积和长宽比,作基本的验证【阈值:长宽比为4.727272,允许误差范围正负40%,面积范围15*15至125*125】

    经过判断后的轮廓图:

    6.由于每个车牌都包含白色背景属性。我们为了更精确的裁剪图像,可以使用floodfill算法【用指定颜色填充某一密闭区域,相当于油漆桶的功能】来提取那些旋转的矩形。

    不会翻译,不怎么明白,各位这步直接看代码吧

    第一步的原文:get several seeds near the last rotated rectangle center. Then get the minimum size of plate between the width and height, and use it to generate random seeds near the patch center.】总之,得到每个矩形的中心,然后求每个矩形各自长宽的较小值,再用随机数和这个较小值得到中心附近的种子点

    第二步的原文:for each seed, we use a floodFill function to draw a new mask image to store the new closest cropping region:

    第三部的翻译:对这些裁剪区域,再次用纵横比和区域面积进行验证,再去除图像的旋转,并裁剪图像到统一尺寸,均衡化图像的灰度

    下面,分别给出这三步的结果图:

    第一步的图像,绿色为矩形中心,黄色为种子点,不知道大家是否能看清楚:

    第二步的图片,上图有5处种子区域,故有5个模版mask图像【代表最近邻接区域】:

    第三步的结果图,注意:这里的结果就是训练SVM的正负样本,只要人工挑选一下:

         

    下面给出以上部分的完整代码【我讨厌一段段的写:)】

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. // Car_plate.cpp : 定义控制台应用程序的入口点。  
    2. //  
    3.   
    4. #include "stdafx.h"  
    5. #include<iostream>  
    6. #include <cv.h>  
    7. #include <highgui.h>  
    8. #include <cvaux.h>  
    9.   
    10. using namespace std;  
    11. using namespace cv;  
    12.   
    13. //对minAreaRect获得的最小外接矩形,用纵横比进行判断  
    14. bool verifySizes(RotatedRect mr)  
    15. {  
    16.     float error=0.4;  
    17.     //Spain car plate size: 52x11 aspect 4,7272  
    18.     float aspect=4.7272;  
    19.     //Set a min and max area. All other patchs are discarded  
    20.     int min= 15*aspect*15; // minimum area  
    21.     int max= 125*aspect*125; // maximum area  
    22.     //Get only patchs that match to a respect ratio.  
    23.     float rmin= aspect-aspect*error;  
    24.     float rmax= aspect+aspect*error;  
    25.   
    26.     int area= mr.size.height * mr.size.width;  
    27.     float r= (float)mr.size.width / (float)mr.size.height;  
    28.     if(r<1)  
    29.         r= (float)mr.size.height / (float)mr.size.width;  
    30.   
    31.     if(( area < min || area > max ) || ( r < rmin || r > rmax )){  
    32.         return false;  
    33.     }else{  
    34.         return true;  
    35.     }  
    36.   
    37. }  
    38.   
    39. //直方图均衡化  
    40. Mat histeq(Mat in)  
    41. {  
    42.     Mat out(in.size(), in.type());  
    43.     if(in.channels()==3){  
    44.         Mat hsv;  
    45.         vector<Mat> hsvSplit;  
    46.         cvtColor(in, hsv, CV_BGR2HSV);  
    47.         split(hsv, hsvSplit);  
    48.         equalizeHist(hsvSplit[2], hsvSplit[2]);  
    49.         merge(hsvSplit, hsv);  
    50.         cvtColor(hsv, out, CV_HSV2BGR);  
    51.     }else if(in.channels()==1){  
    52.         equalizeHist(in, out);  
    53.     }  
    54.   
    55.     return out;  
    56.   
    57. }  
    58.   
    59. int _tmain(int argc, _TCHAR* argv[])  
    60. {  
    61.     Mat img_gray = imread("test.jpg",CV_LOAD_IMAGE_GRAYSCALE);  
    62.     Mat input = imread("test.jpg");  
    63.     //char res[20];  
    64.   
    65.     //apply a Gaussian blur of 5 x 5 and remove noise  
    66.     blur(img_gray,img_gray,Size(5,5));  
    67.   
    68.     //Finde vertical edges. Car plates have high density of vertical lines  
    69.     Mat img_sobel;  
    70.     Sobel(img_gray, img_sobel, CV_8U, 1, 0, 3, 1, 0, BORDER_DEFAULT);//xorder=1,yorder=0,kernelsize=3  
    71.   
    72.     //apply a threshold filter to obtain a binary image through Otsu's method  
    73.     Mat img_threshold;  
    74.     threshold(img_sobel, img_threshold, 0, 255, CV_THRESH_OTSU+CV_THRESH_BINARY);  
    75.   
    76.     //Morphplogic operation close:remove blank spaces and connect all regions that have a high number of edges  
    77.     Mat element = getStructuringElement(MORPH_RECT, Size(17, 3) );  
    78.     morphologyEx(img_threshold, img_threshold, CV_MOP_CLOSE, element);  
    79.   
    80.      //Find 轮廓 of possibles plates  
    81.     vector< vector< Point> > contours;  
    82.     findContours(img_threshold,  
    83.         contours, // a vector of contours  
    84.         CV_RETR_EXTERNAL, // 提取外部轮廓  
    85.         CV_CHAIN_APPROX_NONE); // all pixels of each contours  
    86.   
    87.     //Start to iterate to each contour founded  
    88.     vector<vector<Point> >::iterator itc= contours.begin();  
    89.     vector<RotatedRect> rects;  
    90.   
    91.     //Remove patch that are no inside limits of aspect ratio and area.      
    92.     while (itc!=contours.end()) {  
    93.         //Create bounding rect of object  
    94.         RotatedRect mr= minAreaRect(Mat(*itc));  
    95.         if( !verifySizes(mr)){  
    96.             itc= contours.erase(itc);  
    97.         }else{  
    98.             ++itc;  
    99.             rects.push_back(mr);  
    100.         }  
    101.     }  
    102.   
    103.     // Draw blue contours on a white image  
    104.     cv::Mat result;  
    105.     //input.copyTo(result);  
    106.     //cv::drawContours(result,contours,  
    107.     //  -1, // draw all contours  
    108.     //  cv::Scalar(0,0,255), // in blue  
    109.     //  3); // with a thickness of 1  
    110.   
    111.   
    112.     for(int i=0; i< rects.size(); i++)  
    113.     {  
    114.         //For better rect cropping for each posible box  
    115.         //Make floodfill algorithm because the plate has white background  
    116.         //And then we can retrieve more clearly the contour box  
    117.         circle(result, rects[i].center, 3, Scalar(0,255,0), -1);  
    118.         //get the min size between width and height  
    119.         float minSize=(rects[i].size.width < rects[i].size.height)?rects[i].size.rects[i].size.height;  
    120.         minSize=minSize-minSize*0.5;  
    121.         //initialize rand and get 5 points around center for floodfill algorithm  
    122.         srand ( time(NULL) );  
    123.         //Initialize floodfill parameters and variables  
    124.         Mat mask;  
    125.         mask.create(input.rows + 2, input.cols + 2, CV_8UC1);  
    126.         mask= Scalar::all(0);  
    127.         int loDiff = 30;  
    128.         int upDiff = 30;  
    129.         int connectivity = 4;  
    130.         int newMaskVal = 255;  
    131.         int NumSeeds = 10;  
    132.         Rect ccomp;  
    133.         int flags = connectivity + (newMaskVal << 8 ) + CV_FLOODFILL_FIXED_RANGE + CV_FLOODFILL_MASK_ONLY;  
    134.         for(int j=0; j<NumSeeds; j++){  
    135.             Point seed;  
    136.             seed.x=rects[i].center.x+rand()%(int)minSize-(minSize/2);  
    137.             seed.y=rects[i].center.y+rand()%(int)minSize-(minSize/2);  
    138.             circle(result, seed, 1, Scalar(0,255,255), -1);  
    139.             int area = floodFill(input, mask, seed, Scalar(255,0,0), &ccomp, Scalar(loDiff, loDiff, loDiff), Scalar(upDiff, upDiff, upDiff), flags);  
    140.         }  
    141.         //sprintf(res,"result%d.jpg",i);  
    142.         //imwrite(res,mask);  
    143.   
    144.         //Check new floodfill mask match for a correct patch.  
    145.         //Get all points detected for get Minimal rotated Rect  
    146.         vector<Point> pointsInterest;  
    147.         Mat_<uchar>::iterator itMask= mask.begin<uchar>();  
    148.         Mat_<uchar>::iterator end= mask.end<uchar>();  
    149.         for( ; itMask!=end; ++itMask)  
    150.             if(*itMask==255)  
    151.                 pointsInterest.push_back(itMask.pos());  
    152.   
    153.         RotatedRect minRect = minAreaRect(pointsInterest);  
    154.   
    155.         if(verifySizes(minRect)){  
    156.             // rotated rectangle drawing   
    157.             Point2f rect_points[4]; minRect.points( rect_points );  
    158.             forint j = 0; j < 4; j++ )  
    159.                 line( result, rect_points[j], rect_points[(j+1)%4], Scalar(0,0,255), 1, 8 );      
    160.   
    161.             //Get rotation matrix  
    162.             float r= (float)minRect.size.width / (float)minRect.size.height;  
    163.             float angle=minRect.angle;      
    164.             if(r<1)  
    165.                 angle=90+angle;  
    166.             Mat rotmat= getRotationMatrix2D(minRect.center, angle,1);  
    167.   
    168.             //Create and rotate image  
    169.             Mat img_rotated;  
    170.             warpAffine(input, img_rotated, rotmat, input.size(), CV_INTER_CUBIC);  
    171.   
    172.             //Crop image  
    173.             Size rect_size=minRect.size;  
    174.             if(r < 1)  
    175.                 swap(rect_size.width, rect_size.height);  
    176.             Mat img_crop;  
    177.             getRectSubPix(img_rotated, rect_size, minRect.center, img_crop);  
    178.   
    179.             Mat resultResized;  
    180.             resultResized.create(33,144, CV_8UC3);  
    181.             resize(img_crop, resultResized, resultResized.size(), 0, 0, INTER_CUBIC);  
    182.             //Equalize croped image  
    183.             Mat grayResult;  
    184.             cvtColor(resultResized, grayResult, CV_BGR2GRAY);   
    185.             blur(grayResult, grayResult, Size(3,3));  
    186.             grayResult=histeq(grayResult);  
    187.         /*  if(1){  
    188.                 stringstream ss(stringstream::in | stringstream::out); 
    189.                 ss << "haha" << "_" << i << ".jpg"; 
    190.                 imwrite(ss.str(), grayResult); 
    191.             }*/  
    192.             //output.push_back(Plate(grayResult,minRect.boundingRect()));  
    193.         }  
    194.     }  
    195.     //imshow("car_plate",result);  
    196.     waitKey(0);  
    197.     return 0;  
    198. }  

    注意上述代码末尾的注释部分:
    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. <span style="white-space:pre">      </span>if(1){   
    2.                 stringstream ss(stringstream::in | stringstream::out);  
    3.                 ss << "haha" << "_" << i << ".jpg";  
    4.                 imwrite(ss.str(), grayResult);  
    5.             }  


    以上部分,就是自动生成正负样本的代码。比人工去QQ截图好多了:)

    在介绍SVM车牌分类之前,我介绍怎么训练SVM【注意:SVM的实现是个庞大的工程,我一直没有自己弄过,这里使用的还是opencv封装的SVM】

    如何训练:
      正样本75张包含车牌的图像和35张不包含车牌的144*33图像。【还有其他更好的特征来训练SVM,PCA,傅立叶变换,纹理分析等等】。
    如何获取样本及存放训练数据。
       通过上述图像分割步骤,我们可以得到车牌及非车牌图像,我们把二者都执行reshaple(1,1),再存放到trainImage的矩阵中,并修改对应trainLables矩阵的0-1值,然后把trainData改为32为浮点数系,再把trainData和trainLabel直接写进xml文件【也就是说xml中包含了样本图像的像素值和样本分类标记】

    具体代码:

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. Mat classes;//(numPlates+numNoPlates, 1, CV_32FC1);  
    2. Mat trainingData;//(numPlates+numNoPlates, imageWidth*imageHeight, CV_32FC1 );  
    3.   
    4. Mat trainingImages;  
    5. vector<int> trainingLabels;  
    6.   
    7. for(int i=0; i< numPlates; i++)  
    8. {  
    9.   
    10.     stringstream ss(stringstream::in | stringstream::out);  
    11.     ss << path_Plates << i << ".jpg";  
    12.     Mat img=imread(ss.str(), 0);  
    13.     img= img.reshape(1, 1);  
    14.     trainingImages.push_back(img);  
    15.     trainingLabels.push_back(1);  
    16. }  
    17.   
    18. for(int i=0; i< numNoPlates; i++)  
    19. {  
    20.     stringstream ss(stringstream::in | stringstream::out);  
    21.     ss << path_NoPlates << i << ".jpg";  
    22.     Mat img=imread(ss.str(), 0);  
    23.     img= img.reshape(1, 1);  
    24.     trainingImages.push_back(img);  
    25.     trainingLabels.push_back(0);  
    26.   
    27. }  
    28.   
    29. Mat(trainingImages).copyTo(trainingData);  
    30. //trainingData = trainingData.reshape(1,trainingData.rows);  
    31. trainingData.convertTo(trainingData, CV_32FC1);  
    32. Mat(trainingLabels).copyTo(classes);  
    33.   
    34. FileStorage fs("SVM.xml", FileStorage::WRITE);  
    35. fs << "TrainingData" << trainingData;  
    36. fs << "classes" << classes;  
    37. fs.release();  
    以上代码,可以自己另外建一个工程,认为设置一下正负样本的数量numPlates和numNoPlates,正负样本存储的路径path_Plates和path_NoPlates。这样我们就得到了存放正负样本的SVM.XML文件了。

    最后,给出使用Opencv提供的SVM分类器,对图像进行分了的完整代码【对一副图像判断其中是否含有西班牙车牌】:

    劳什子外国人搞了车牌类,好吧,我挑和本文有关的都贴出来吧

    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #ifndef Plate_h  
    2. #define Plate_h  
    3.   
    4. #include <string.h>  
    5. #include <vector>  
    6.   
    7. #include <cv.h>  
    8. #include <highgui.h>  
    9. #include <cvaux.h>  
    10.   
    11. using namespace std;  
    12. using namespace cv;  
    13.   
    14. class Plate{  
    15.     public:  
    16.         Plate();  
    17.         Plate(Mat img, Rect pos);  
    18.         string str();  
    19.         Rect position;  
    20.         Mat plateImg;  
    21.         vector<char> chars;  
    22.         vector<Rect> charsPos;          
    23. };  
    24.   
    25. #endif  

    这里,我们只要实现上述Plate类的构造函数就行了
    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. Plate::Plate(Mat img, Rect pos){  
    2.     plateImg=img;  
    3.     position=pos;  
    4. }  

    下面我再次给出完整代码,不过大家重点关注如何配置SVM就行了:
    [cpp] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. // car_plate_svm.cpp : 定义控制台应用程序的入口点。  
    2. //  
    3.   
    4. #include "stdafx.h"  
    5. #include<iostream>  
    6. #include <cv.h>  
    7. #include <highgui.h>  
    8. #include <cvaux.h>  
    9. #include "Plate.h"  
    10.   
    11. using namespace std;  
    12. using namespace cv;  
    13.   
    14.   
    15.   
    16.   
    17. //对minAreaRect获得的最小外接矩形,用纵横比进行判断  
    18. bool verifySizes(RotatedRect mr)  
    19. {  
    20.     float error=0.4;  
    21.     //Spain car plate size: 52x11 aspect 4,7272  
    22.     float aspect=4.7272;  
    23.     //Set a min and max area. All other patchs are discarded  
    24.     int min= 15*aspect*15; // minimum area  
    25.     int max= 125*aspect*125; // maximum area  
    26.     //Get only patchs that match to a respect ratio.  
    27.     float rmin= aspect-aspect*error;  
    28.     float rmax= aspect+aspect*error;  
    29.   
    30.     int area= mr.size.height * mr.size.width;  
    31.     float r= (float)mr.size.width / (float)mr.size.height;  
    32.     if(r<1)  
    33.         r= (float)mr.size.height / (float)mr.size.width;  
    34.   
    35.     if(( area < min || area > max ) || ( r < rmin || r > rmax )){  
    36.         return false;  
    37.     }else{  
    38.         return true;  
    39.     }  
    40.   
    41. }  
    42.   
    43. Mat histeq(Mat in)  
    44. {  
    45.     Mat out(in.size(), in.type());  
    46.     if(in.channels()==3){  
    47.         Mat hsv;  
    48.         vector<Mat> hsvSplit;  
    49.         cvtColor(in, hsv, CV_BGR2HSV);  
    50.         split(hsv, hsvSplit);  
    51.         equalizeHist(hsvSplit[2], hsvSplit[2]);  
    52.         merge(hsvSplit, hsv);  
    53.         cvtColor(hsv, out, CV_HSV2BGR);  
    54.     }else if(in.channels()==1){  
    55.         equalizeHist(in, out);  
    56.     }  
    57.   
    58.     return out;  
    59.   
    60. }  
    61.   
    62. vector<Plate> segment(Mat input){  
    63.     vector<Plate> output;  
    64.     //char res[20];  
    65.   
    66.     //apply a Gaussian blur of 5 x 5 and remove noise  
    67.     Mat img_gray;  
    68.     cvtColor(input, img_gray, CV_BGR2GRAY);  
    69.     blur(img_gray, img_gray, Size(5,5));      
    70.   
    71.     //Finde vertical edges. Car plates have high density of vertical lines  
    72.     Mat img_sobel;  
    73.     Sobel(img_gray, img_sobel, CV_8U, 1, 0, 3, 1, 0, BORDER_DEFAULT);//xorder=1,yorder=0,kernelsize=3  
    74.   
    75.     //apply a threshold filter to obtain a binary image through Otsu's method  
    76.     Mat img_threshold;  
    77.     threshold(img_sobel, img_threshold, 0, 255, CV_THRESH_OTSU+CV_THRESH_BINARY);  
    78.   
    79.     //Morphplogic operation close:remove blank spaces and connect all regions that have a high number of edges  
    80.     Mat element = getStructuringElement(MORPH_RECT, Size(17, 3) );  
    81.     morphologyEx(img_threshold, img_threshold, CV_MOP_CLOSE, element);  
    82.   
    83.     //Find 轮廓 of possibles plates  
    84.     vector< vector< Point> > contours;  
    85.     findContours(img_threshold,  
    86.         contours, // a vector of contours  
    87.         CV_RETR_EXTERNAL, // 提取外部轮廓  
    88.         CV_CHAIN_APPROX_NONE); // all pixels of each contours  
    89.   
    90.     //Start to iterate to each contour founded  
    91.     vector<vector<Point> >::iterator itc= contours.begin();  
    92.     vector<RotatedRect> rects;  
    93.   
    94.     //Remove patch that are no inside limits of aspect ratio and area.      
    95.     while (itc!=contours.end()) {  
    96.         //Create bounding rect of object  
    97.         RotatedRect mr= minAreaRect(Mat(*itc));  
    98.         if( !verifySizes(mr)){  
    99.             itc= contours.erase(itc);  
    100.         }else{  
    101.             ++itc;  
    102.             rects.push_back(mr);  
    103.         }  
    104.     }  
    105.   
    106.     //// Draw blue contours on a white image  
    107.     cv::Mat result;  
    108.     input.copyTo(result);  
    109.     //cv::drawContours(result,contours,  
    110.     //  -1, // draw all contours  
    111.     //  cv::Scalar(255,0,0), // in blue  
    112.     //  1); // with a thickness of 1  
    113.   
    114.   
    115.     for(int i=0; i< rects.size(); i++)  
    116.     {  
    117.         //For better rect cropping for each posible box  
    118.         //Make floodfill algorithm because the plate has white background  
    119.         //And then we can retrieve more clearly the contour box  
    120.         circle(result, rects[i].center, 3, Scalar(0,255,0), -1);  
    121.         //get the min size between width and height  
    122.         float minSize=(rects[i].size.width < rects[i].size.height)?rects[i].size.rects[i].size.height;  
    123.         minSize=minSize-minSize*0.5;  
    124.         //initialize rand and get 5 points around center for floodfill algorithm  
    125.         srand ( time(NULL) );  
    126.         //Initialize floodfill parameters and variables  
    127.         Mat mask;  
    128.         mask.create(input.rows + 2, input.cols + 2, CV_8UC1);  
    129.         mask= Scalar::all(0);  
    130.         int loDiff = 30;  
    131.         int upDiff = 30;  
    132.         int connectivity = 4;  
    133.         int newMaskVal = 255;  
    134.         int NumSeeds = 10;  
    135.         Rect ccomp;  
    136.         int flags = connectivity + (newMaskVal << 8 ) + CV_FLOODFILL_FIXED_RANGE + CV_FLOODFILL_MASK_ONLY;  
    137.         for(int j=0; j<NumSeeds; j++){  
    138.             Point seed;  
    139.             seed.x=rects[i].center.x+rand()%(int)minSize-(minSize/2);  
    140.             seed.y=rects[i].center.y+rand()%(int)minSize-(minSize/2);  
    141.             circle(result, seed, 1, Scalar(0,255,255), -1);  
    142.             int area = floodFill(input, mask, seed, Scalar(255,0,0), &ccomp, Scalar(loDiff, loDiff, loDiff), Scalar(upDiff, upDiff, upDiff), flags);  
    143.         }  
    144.         //sprintf(res,"result%d.jpg",i);  
    145.         //imwrite(res,mask);  
    146.   
    147.         //Check new floodfill mask match for a correct patch.  
    148.         //Get all points detected for get Minimal rotated Rect  
    149.         vector<Point> pointsInterest;  
    150.         Mat_<uchar>::iterator itMask= mask.begin<uchar>();  
    151.         Mat_<uchar>::iterator end= mask.end<uchar>();  
    152.         for( ; itMask!=end; ++itMask)  
    153.             if(*itMask==255)  
    154.                 pointsInterest.push_back(itMask.pos());  
    155.   
    156.         RotatedRect minRect = minAreaRect(pointsInterest);  
    157.   
    158.         if(verifySizes(minRect)){  
    159.             // rotated rectangle drawing   
    160.             Point2f rect_points[4]; minRect.points( rect_points );  
    161.             forint j = 0; j < 4; j++ )  
    162.                 line( result, rect_points[j], rect_points[(j+1)%4], Scalar(0,0,255), 1, 8 );      
    163.   
    164.             //Get rotation matrix  
    165.             float r= (float)minRect.size.width / (float)minRect.size.height;  
    166.             float angle=minRect.angle;      
    167.             if(r<1)  
    168.                 angle=90+angle;  
    169.             Mat rotmat= getRotationMatrix2D(minRect.center, angle,1);  
    170.   
    171.             //Create and rotate image  
    172.             Mat img_rotated;  
    173.             warpAffine(input, img_rotated, rotmat, input.size(), CV_INTER_CUBIC);  
    174.   
    175.             //Crop image  
    176.             Size rect_size=minRect.size;  
    177.             if(r < 1)  
    178.                 swap(rect_size.width, rect_size.height);  
    179.             Mat img_crop;  
    180.             getRectSubPix(img_rotated, rect_size, minRect.center, img_crop);  
    181.   
    182.             Mat resultResized;  
    183.             resultResized.create(33,144, CV_8UC3);  
    184.             resize(img_crop, resultResized, resultResized.size(), 0, 0, INTER_CUBIC);  
    185.             //Equalize croped image  
    186.             Mat grayResult;  
    187.             cvtColor(resultResized, grayResult, CV_BGR2GRAY);   
    188.             blur(grayResult, grayResult, Size(3,3));  
    189.             grayResult=histeq(grayResult);  
    190.             /*  if(1){  
    191.             stringstream ss(stringstream::in | stringstream::out); 
    192.             ss << "haha" << "_" << i << ".jpg"; 
    193.             imwrite(ss.str(), grayResult); 
    194.             }*/  
    195.             output.push_back(Plate(grayResult,minRect.boundingRect()));  
    196.         }  
    197.     }  
    198.     //imshow("car_plate",result);  
    199.     //waitKey(0);  
    200.     return output;  
    201. }  
    202.   
    203. int _tmain(int argc, _TCHAR* argv[])  
    204. {  
    205.     Mat input = imread("test.jpg");  
    206.     vector<Plate> posible_regions = segment(input);  
    207.       
    208.     //SVM for each plate region to get valid car plates  
    209.     //Read file storage.  
    210.     FileStorage fs;  
    211.     fs.open("SVM.xml", FileStorage::READ);  
    212.     Mat SVM_TrainingData;  
    213.     Mat SVM_Classes;  
    214.     fs["TrainingData"] >> SVM_TrainingData;  
    215.     fs["classes"] >> SVM_Classes;  
    216.     //Set SVM params  
    217.     CvSVMParams SVM_params;  
    218.     SVM_params.svm_type = CvSVM::C_SVC;  
    219.     SVM_params.kernel_type = CvSVM::LINEAR; //CvSVM::LINEAR;  
    220.     SVM_params.degree = 0;  
    221.     SVM_params.gamma = 1;  
    222.     SVM_params.coef0 = 0;  
    223.     SVM_params.C = 1;  
    224.     SVM_params.nu = 0;  
    225.     SVM_params.p = 0;  
    226.     SVM_params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 1000, 0.01);  
    227.     //Train SVM  
    228.     CvSVM svmClassifier(SVM_TrainingData, SVM_Classes, Mat(), Mat(), SVM_params);  
    229.   
    230.     //For each possible plate, classify with svm if it's a plate or no  
    231.     vector<Plate> plates;  
    232.     for(int i=0; i< posible_regions.size(); i++)  
    233.     {  
    234.         Mat img=posible_regions[i].plateImg;  
    235.         Mat p= img.reshape(1, 1);  
    236.         p.convertTo(p, CV_32FC1);  
    237.   
    238.         int response = (int)svmClassifier.predict( p );  
    239.         /*if(response==1) 
    240.             plates.push_back(posible_regions[i]);*/  
    241.         printf("%d.jpg分类结果:%d ",i,response);  
    242.     }  
    243.     return 0;  
    244. }  

    好吧,今天到此为止了。还是那张原图,由于图像分割后产生3个候选车牌,所以SVM分类结果为:

    这里关于OPENCV的各种函数配置,我一点没提,因为如果不懂原理,就不要用人家成熟的东西,否则永远被动,被opencv牵着走。

  • 相关阅读:
    BZOJ3282 Tree
    [NOI2004] 郁闷的出纳员
    [HNOI2004]宠物收养所
    [HNOI2002] 营业额统计
    图论 简单学习笔记
    POJ3321 Apple tree
    [国家集训队] 聪聪可可
    POJ2976 Dropping tests
    SCOI2005 最大子矩阵
    codeforces|CF13C Sequence
  • 原文地址:https://www.cnblogs.com/donaldlee2008/p/5215729.html
Copyright © 2011-2022 走看看