Opencv+Zbar二维码识别(标准条形码/二维码识别)

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


使用OpenCV+Zbar组合可以很容易的识别图片中的二维码,特别是标准的二维码,这里标准指的是二维码成像清晰,图片中二维码的空间占比在40%~100%之间,这样标准的图片,Zbar识别起来很容易,不需要Opencv额外的处理。


下边这个例程演示两者配合对条形码和二维码的识别:

[cpp]  view plain  copy
 print ? 在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.     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识别读码。


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


[cpp]  view plain  copy
 print ? 在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. // 函数通过水平和垂直方向投影,找到两个方向上投影的交叉矩形,定位到条形码/二维码  
  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条码识别。当然这个方法只能识别出背景简单的图片中的二维码。

条形码效果:



水平、垂直投影



检出条形码区域



二维码效果:

          



方法二.梯度运算


[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  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实现:

[cpp]  view plain  copy
 print ? 在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. }  

  • 4
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值