Opencv+Zbar二維碼識別(標準條形碼/二維碼識別)

http://blog.csdn.net/dcrmg/article/details/52132313


使用OpenCV+Zbar組合可以很容易的識別圖片中的二維碼,特別是標準的二維碼,這裏標準指的是二維碼成像清晰,圖片中二維碼的空間佔比在40%~100%之間,這樣標準的圖片,Zbar識別起來很容易,不需要Opencv額外的處理。


下邊這個例程演示兩者配合對條形碼和二維碼的識別:

  1. #include "zbar.h"      
  2. #include "cv.h"      
  3. #include "highgui.h"      
  4. #include <iostream>      
  5.   
  6. using namespace std;      
  7. using namespace zbar;  //添加zbar名稱空間    
  8. using namespace cv;      
  9.   
  10. int main(int argc,char*argv[])    
  11. {      
  12.     ImageScanner scanner;      
  13.     scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);    
  14.     Mat image = imread(argv[1]);      
  15.     Mat imageGray;      
  16.     cvtColor(image,imageGray,CV_RGB2GRAY);      
  17.     int width = imageGray.cols;      
  18.     int height = imageGray.rows;      
  19.     uchar *raw = (uchar *)imageGray.data;         
  20.     Image imageZbar(width, height, "Y800", raw, width * height);        
  21.     scanner.scan(imageZbar); //掃描條碼    
  22.     Image::SymbolIterator symbol = imageZbar.symbol_begin();  
  23.     if(imageZbar.symbol_begin()==imageZbar.symbol_end())  
  24.     {  
  25.         cout<<"查詢條碼失敗,請檢查圖片!"<<endl;  
  26.     }  
  27.     for(;symbol != imageZbar.symbol_end();++symbol)    
  28.     {      
  29.         cout<<"類型:"<<endl<<symbol->get_type_name()<<endl<<endl;    
  30.         cout<<"條碼:"<<endl<<symbol->get_data()<<endl<<endl;       
  31.     }      
  32.     imshow("Source Image",image);        
  33.     waitKey();    
  34.     imageZbar.set_data(NULL,0);  
  35.     return 0;  
  36. }      


條形碼:



二維碼:



這樣“標準的”二維碼是Zbar非常拿手的,能準確快速的檢測出來,包括在條形碼外有部分其他信息的,也是小菜一碟:



Zbar很省心,我們還是可以爲它做點什麼的,比如在一些情況下,需要把條形碼裁剪出來,這就涉及到條形碼位置的定位,這篇文章準備記錄一下如何定位條形碼,在定位之後再把裁剪出來的條形碼區域丟給Zbar識別讀碼。


方法一. 水平、垂直方向投影


  1. #include "zbar.h"      
  2. #include "cv.h"      
  3. #include "highgui.h"      
  4. #include <iostream>      
  5.   
  6. using namespace std;      
  7. using namespace zbar;  //添加zbar名稱空間    
  8. using namespace cv;      
  9. //***********************************************  
  10. // 函數通過水平和垂直方向投影,找到兩個方向上投影的交叉矩形,定位到條形碼/二維碼  
  11. // int threshodValue 投影的最少像素單位  
  12. // int binaryzationValue  原圖像閾值分割值  
  13. //***********************************************  
  14. Rect DrawXYProjection(const Mat image,Mat &imageOut,const int threshodValue,const int binaryzationValue);  
  15.   
  16. int main(int argc,char*argv[])    
  17. {     
  18.     Mat image = imread(argv[1]);    
  19.     Mat imageCopy=image.clone();  
  20.     Mat imageGray,imagOut;      
  21.     cvtColor(image,imageGray,CV_RGB2GRAY);  
  22.     Rect rect(0,0,0,0);  
  23.     rect=   DrawXYProjection(image,imagOut,image.rows/10,100);  
  24.     Mat roi=image(rect);  
  25.     //畫出條形碼的矩形框  
  26.     rectangle(imageCopy,Point(rect.x,rect.y),Point(rect.x+rect.width,rect.y+rect.height),Scalar(0,0,255),2);  
  27.     imshow("Source Image",image);  
  28.     imshow("水平垂直投影",imagOut);  
  29.     imshow("Output Image",roi);  
  30.     imshow("Source Image Rect",imageCopy);  
  31.     waitKey();        
  32.     return 0;  
  33. }    
  34.   
  35. Rect DrawXYProjection(const Mat image,Mat &imageOut,const int threshodValue,const int binaryzationValue)  
  36. {  
  37.     Mat img=image.clone();  
  38.     if(img.channels()>1)  
  39.     {  
  40.         cvtColor(img,img,CV_RGB2GRAY);  
  41.     }  
  42.     Mat out(img.size(),img.type(),Scalar(255));  
  43.     imageOut=out;  
  44.     //對每一個傳入的圖片做灰度歸一化,以便使用同一套閾值參數  
  45.     normalize(img,img,0,255,NORM_MINMAX);  
  46.     vector<int> vectorVertical(img.cols,0);  
  47.     for(int i=0;i<img.cols;i++)  
  48.     {  
  49.         for(int j=0;j<img.rows;j++)  
  50.         {  
  51.             if(img.at<uchar>(j,i)<binaryzationValue)  
  52.             {  
  53.                 vectorVertical[i]++;  
  54.             }  
  55.         }  
  56.     }  
  57.     //列值歸一化  
  58.     int high=img.rows/6;  
  59.     normalize(vectorVertical,vectorVertical,0,high,NORM_MINMAX);  
  60.     for(int i=0;i<img.cols;i++)  
  61.     {  
  62.         for(int j=0;j<img.rows;j++)  
  63.         {  
  64.             if(vectorVertical[i]>threshodValue)  
  65.             {  
  66.                 line(imageOut,Point(i,img.rows),Point(i,img.rows-vectorVertical[i]),Scalar(0));  
  67.             }  
  68.         }  
  69.     }  
  70.     //水平投影  
  71.     vector<int> vectorHorizontal(img.rows,0);  
  72.     for(int i=0;i<img.rows;i++)  
  73.     {  
  74.         for(int j=0;j<img.cols;j++)  
  75.         {  
  76.             if(img.at<uchar>(i,j)<binaryzationValue)  
  77.             {  
  78.                 vectorHorizontal[i]++;  
  79.             }  
  80.         }  
  81.     }     
  82.     normalize(vectorHorizontal,vectorHorizontal,0,high,NORM_MINMAX);  
  83.     for(int i=0;i<img.rows;i++)  
  84.     {  
  85.         for(int j=0;j<img.cols;j++)  
  86.         {  
  87.             if(vectorHorizontal[i]>threshodValue)  
  88.             {  
  89.                 line(imageOut,Point(img.cols-vectorHorizontal[i],i),Point(img.cols,i),Scalar(0));  
  90.             }  
  91.         }  
  92.     }  
  93.     //找到投影四個角點座標  
  94.     vector<int>::iterator beginV=vectorVertical.begin();  
  95.     vector<int>::iterator beginH=vectorHorizontal.begin();  
  96.     vector<int>::iterator endV=vectorVertical.end()-1;  
  97.     vector<int>::iterator endH=vectorHorizontal.end()-1;  
  98.     int widthV=0;  
  99.     int widthH=0;  
  100.     int highV=0;  
  101.     int highH=0;  
  102.     while(*beginV<threshodValue)  
  103.     {  
  104.         beginV++;  
  105.         widthV++;  
  106.     }  
  107.     while(*endV<threshodValue)  
  108.     {  
  109.         endV--;  
  110.         widthH++;  
  111.     }  
  112.     while(*beginH<threshodValue)  
  113.     {  
  114.         beginH++;  
  115.         highV++;  
  116.     }  
  117.     while(*endH<threshodValue)  
  118.     {  
  119.         endH--;  
  120.         highH++;  
  121.     }  
  122.     //投影矩形  
  123.     Rect rect(widthV,highV,img.cols-widthH-widthV,img.rows-highH-highV);  
  124.     return rect;  
  125. }  

通過圖像在水平和垂直方向上的投影,按照一定的閾值,找到二維碼所在位置,剪切出來用於下一步Zbar條碼識別。當然這個方法只能識別出背景簡單的圖片中的二維碼。

條形碼效果:



水平、垂直投影



檢出條形碼區域



二維碼效果:

          



方法二.梯度運算


  1. #include "core/core.hpp"    
  2. #include "highgui/highgui.hpp"    
  3. #include "imgproc/imgproc.hpp"    
  4.     
  5. using namespace cv;    
  6.     
  7. int main(int argc,char *argv[])    
  8. {    
  9.     Mat image,imageGray,imageGuussian;    
  10.     Mat imageSobelX,imageSobelY,imageSobelOut;    
  11.     image=imread(argv[1]);    
  12.     
  13.     //1. 原圖像大小調整,提高運算效率    
  14.     resize(image,image,Size(500,300));    
  15.     imshow("1.原圖像",image);    
  16.     
  17.     //2. 轉化爲灰度圖    
  18.     cvtColor(image,imageGray,CV_RGB2GRAY);    
  19.     imshow("2.灰度圖",imageGray);    
  20.     
  21.     //3. 高斯平滑濾波    
  22.     GaussianBlur(imageGray,imageGuussian,Size(3,3),0);    
  23.     imshow("3.高斯平衡濾波",imageGuussian);    
  24.     
  25.     //4.求得水平和垂直方向灰度圖像的梯度差,使用Sobel算子    
  26.     Mat imageX16S,imageY16S;    
  27.     Sobel(imageGuussian,imageX16S,CV_16S,1,0,3,1,0,4);    
  28.     Sobel(imageGuussian,imageY16S,CV_16S,0,1,3,1,0,4);    
  29.     convertScaleAbs(imageX16S,imageSobelX,1,0);    
  30.     convertScaleAbs(imageY16S,imageSobelY,1,0);    
  31.     imageSobelOut=imageSobelX-imageSobelY;    
  32.     imshow("4.X方向梯度",imageSobelX);    
  33.     imshow("4.Y方向梯度",imageSobelY);    
  34.     imshow("4.XY方向梯度差",imageSobelOut);      
  35.     
  36.     //5.均值濾波,消除高頻噪聲    
  37.     blur(imageSobelOut,imageSobelOut,Size(3,3));    
  38.     imshow("5.均值濾波",imageSobelOut);     
  39.     
  40.     //6.二值化    
  41.     Mat imageSobleOutThreshold;    
  42.     threshold(imageSobelOut,imageSobleOutThreshold,180,255,CV_THRESH_BINARY);       
  43.     imshow("6.二值化",imageSobleOutThreshold);    
  44.     
  45.     //7.閉運算,填充條形碼間隙    
  46.     Mat  element=getStructuringElement(0,Size(7,7));    
  47.     morphologyEx(imageSobleOutThreshold,imageSobleOutThreshold,MORPH_CLOSE,element);        
  48.     imshow("7.閉運算",imageSobleOutThreshold);    
  49.     
  50.     //8. 腐蝕,去除孤立的點    
  51.     erode(imageSobleOutThreshold,imageSobleOutThreshold,element);    
  52.     imshow("8.腐蝕",imageSobleOutThreshold);    
  53.     
  54.     //9. 膨脹,填充條形碼間空隙,根據核的大小,有可能需要2~3次膨脹操作    
  55.     dilate(imageSobleOutThreshold,imageSobleOutThreshold,element);    
  56.     dilate(imageSobleOutThreshold,imageSobleOutThreshold,element);    
  57.     dilate(imageSobleOutThreshold,imageSobleOutThreshold,element);    
  58.     imshow("9.膨脹",imageSobleOutThreshold);          
  59.     vector<vector<Point>> contours;    
  60.     vector<Vec4i> hiera;    
  61.     
  62.     //10.通過findContours找到條形碼區域的矩形邊界    
  63.     findContours(imageSobleOutThreshold,contours,hiera,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);    
  64.     for(int i=0;i<contours.size();i++)    
  65.     {    
  66.         Rect rect=boundingRect((Mat)contours[i]);    
  67.         rectangle(image,rect,Scalar(255),2);        
  68.     }       
  69.     imshow("10.找出二維碼矩形區域",image);    
  70.     
  71.     waitKey();    
  72. }    

原圖像



平滑濾波



水平和垂直方向灰度圖像的梯度差



閉運算、腐蝕、膨脹後通過findContours找到條形碼區域的矩形邊界


二維碼:

原圖:



平衡濾波



梯度和



閉運算、腐蝕、膨脹後通過findContours找到條形碼區域的矩形邊界







二維碼校正:

二維碼和車牌識別基本都會涉及到圖像的校正,主要是形變和傾斜角度的校正,一種二維碼的畸變如下圖:


這個碼用微信掃了一下,識別不出來,但是用Zbar還是可以準確識別的~~。

這裏介紹一種二維碼校正方法,通過定位二維碼的4個頂點,利用仿射變換校正。基本思路:濾波->二值化->膨脹(腐蝕)操作->形態學邊界->尋找直線->定位交點->仿射變換校正->Zbar識別。


濾波、二值化:


腐蝕操作:



形態學邊界:



尋找直線:



角點定位:



仿射變換校正:



Zbar識別:



Code實現:

  1. #include "zbar.h"        
  2. #include "cv.h"        
  3. #include "highgui.h"        
  4. #include <iostream>        
  5.   
  6. using namespace std;        
  7. using namespace zbar;  //添加zbar名稱空間      
  8. using namespace cv;        
  9.   
  10. int main(int argc,char*argv[])      
  11. {    
  12.     Mat imageSource=imread(argv[1],0);    
  13.     Mat image;  
  14.     imageSource.copyTo(image);  
  15.     GaussianBlur(image,image,Size(3,3),0);  //濾波  
  16.     threshold(image,image,100,255,CV_THRESH_BINARY);  //二值化  
  17.     imshow("二值化",image);      
  18.     Mat element=getStructuringElement(2,Size(7,7));  //膨脹腐蝕核  
  19.     //morphologyEx(image,image,MORPH_OPEN,element);   
  20.     for(int i=0;i<10;i++)  
  21.     {  
  22.         erode(image,image,element);  
  23.         i++;  
  24.     }     
  25.     imshow("腐蝕s",image);  
  26.     Mat image1;  
  27.     erode(image,image1,element);  
  28.     image1=image-image1;  
  29.     imshow("邊界",image1);  
  30.     //尋找直線 邊界定位也可以用findContours實現  
  31.     vector<Vec2f>lines;  
  32.     HoughLines(image1,lines,1,CV_PI/150,250,0,0);  
  33.     Mat DrawLine=Mat::zeros(image1.size(),CV_8UC1);  
  34.     for(int i=0;i<lines.size();i++)  
  35.     {  
  36.         float rho=lines[i][0];  
  37.         float theta=lines[i][1];  
  38.         Point pt1,pt2;  
  39.         double a=cos(theta),b=sin(theta);  
  40.         double x0=a*rho,y0=b*rho;  
  41.         pt1.x=cvRound(x0+1000*(-b));  
  42.         pt1.y=cvRound(y0+1000*a);  
  43.         pt2.x=cvRound(x0-1000*(-b));  
  44.         pt2.y=cvRound(y0-1000*a);  
  45.         line(DrawLine,pt1,pt2,Scalar(255),1,CV_AA);  
  46.     }  
  47.     imshow("直線",DrawLine);  
  48.     Point2f P1[4];  
  49.     Point2f P2[4];  
  50.     vector<Point2f>corners;  
  51.     goodFeaturesToTrack(DrawLine,corners,4,0.1,10,Mat()); //角點檢測  
  52.     for(int i=0;i<corners.size();i++)  
  53.     {  
  54.         circle(DrawLine,corners[i],3,Scalar(255),3);  
  55.         P1[i]=corners[i];         
  56.     }  
  57.     imshow("交點",DrawLine);  
  58.     int width=P1[1].x-P1[0].x;  
  59.     int hight=P1[2].y-P1[0].y;  
  60.     P2[0]=P1[0];  
  61.     P2[1]=Point2f(P2[0].x+width,P2[0].y);  
  62.     P2[2]=Point2f(P2[0].x,P2[1].y+hight);  
  63.     P2[3]=Point2f(P2[1].x,P2[2].y);  
  64.     Mat elementTransf;  
  65.     elementTransf=  getAffineTransform(P1,P2);  
  66.     warpAffine(imageSource,imageSource,elementTransf,imageSource.size(),1,0,Scalar(255));  
  67.     imshow("校正",imageSource);     
  68.     //Zbar二維碼識別  
  69.     ImageScanner scanner;        
  70.     scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);   
  71.     int width1 = imageSource.cols;        
  72.     int height1 = imageSource.rows;        
  73.     uchar *raw = (uchar *)imageSource.data;           
  74.     Image imageZbar(width1, height1, "Y800", raw, width * height1);          
  75.     scanner.scan(imageZbar); //掃描條碼      
  76.     Image::SymbolIterator symbol = imageZbar.symbol_begin();    
  77.     if(imageZbar.symbol_begin()==imageZbar.symbol_end())    
  78.     {    
  79.         cout<<"查詢條碼失敗,請檢查圖片!"<<endl;    
  80.     }    
  81.     for(;symbol != imageZbar.symbol_end();++symbol)      
  82.     {        
  83.         cout<<"類型:"<<endl<<symbol->get_type_name()<<endl<<endl;      
  84.         cout<<"條碼:"<<endl<<symbol->get_data()<<endl<<endl;         
  85.     }        
  86.     namedWindow("Source Window",0);  
  87.     imshow("Source Window",imageSource);          
  88.     waitKey();      
  89.     imageZbar.set_data(NULL,0);    
  90.     return 0;    
  91. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章