本文為大家分享了Opencv輕松檢測出圖片中條形碼的步驟,供大家參考,具體內容如下
1. 原圖像大小調整,提高運算效率
2. 轉化為灰度圖
3. 高斯平滑濾波
4.求得水平和垂直方向灰度圖像的梯度差,使用Sobel算子
5.均值濾波,消除高頻噪聲
6.二值化
7.閉運算,填充條形碼間隙
8. 腐蝕,去除孤立的點
9. 膨脹,填充條形碼間空隙,根據核的大小,有可能需要2~3次膨脹操作
10.通過findContours找到條形碼區域的矩形邊界
實現:
#include "core/core.hpp" #include "highgui/highgui.hpp" #include "imgproc/imgproc.hpp" using namespace cv; int main(int argc,char *argv[]) { Mat image,imageGray,imageGuussian; Mat imageSobelX,imageSobelY,imageSobelOut; image=imread(argv[1]); //1. 原圖像大小調整,提高運算效率 resize(image,image,Size(500,300)); imshow("1.原圖像",image); //2. 轉化為灰度圖 cvtColor(image,imageGray,CV_RGB2GRAY); imshow("2.灰度圖",imageGray); //3. 高斯平滑濾波 GaussianBlur(imageGray,imageGuussian,Size(3,3),0); imshow("3.高斯平衡濾波",imageGuussian); //4.求得水平和垂直方向灰度圖像的梯度差,使用Sobel算子 Mat imageX16S,imageY16S; Sobel(imageGuussian,imageX16S,CV_16S,1,0,3,1,0,4); Sobel(imageGuussian,imageY16S,CV_16S,0,1,3,1,0,4); convertScaleAbs(imageX16S,imageSobelX,1,0); convertScaleAbs(imageY16S,imageSobelY,1,0); imageSobelOut=imageSobelX-imageSobelY; imshow("4.X方向梯度",imageSobelX); imshow("4.Y方向梯度",imageSobelY); imshow("4.XY方向梯度差",imageSobelOut); //5.均值濾波,消除高頻噪聲 blur(imageSobelOut,imageSobelOut,Size(3,3)); imshow("5.均值濾波",imageSobelOut); //6.二值化 Mat imageSobleOutThreshold; threshold(imageSobelOut,imageSobleOutThreshold,180,255,CV_THRESH_BINARY); imshow("6.二值化",imageSobleOutThreshold); //7.閉運算,填充條形碼間隙 Mat element=getStructuringElement(0,Size(7,7)); morphologyEx(imageSobleOutThreshold,imageSobleOutThreshold,MORPH_CLOSE,element); imshow("7.閉運算",imageSobleOutThreshold); //8. 腐蝕,去除孤立的點 erode(imageSobleOutThreshold,imageSobleOutThreshold,element); imshow("8.腐蝕",imageSobleOutThreshold); //9. 膨脹,填充條形碼間空隙,根據核的大小,有可能需要2~3次膨脹操作 dilate(imageSobleOutThreshold,imageSobleOutThreshold,element); dilate(imageSobleOutThreshold,imageSobleOutThreshold,element); dilate(imageSobleOutThreshold,imageSobleOutThreshold,element); imshow("9.膨脹",imageSobleOutThreshold); vector<vector<Point>> contours; vector<Vec4i> hiera; //10.通過findContours找到條形碼區域的矩形邊界 findContours(imageSobleOutThreshold,contours,hiera,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE); for(int i=0;i<contours.size();i++) { Rect rect=boundingRect((Mat)contours[i]); rectangle(image,rect,Scalar(255),2); } imshow("10.找出二維碼矩形區域",image); waitKey(); }
使用另一幅圖片的效果如下:
底部的二維碼左側邊界定位錯位,檢測發現在二值化的時候左側第二個條碼部分被歸零了,導致在之后的腐蝕操作中被腐蝕掉了。調整閾值分界值180到160,重新運行正確:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。