OPENCV Barcode Detection and identification

Source: Internet
Author: User

Bar code is the current supermarket and some factories use more common items, product identification technology, using the camera to detect a picture bar code contains two steps, the first is to locate the location of the barcode, after positioning the barcode, and identify the bar code corresponding string, then you can call the network, Database and other means of rapid follow-up processing.

Barcode recognition to take into account the characteristics of the barcode, this article is aimed at the position of the bar code in the picture is relatively vertical, there is no kind of inclined bar code, as shown in

To locate the first to examine the characteristics of this barcode, the image in the x direction of the gradient is certainly very obvious, and the y direction of the gradient is not so obvious, so the first step, we should be the image of the gray image of the gradient, the X-direction gradient minus the y-direction gradient, This preserves the X-directional feature and removes interference in the Y-direction, and the image looks like this after processing

Can be seen, two-dimensional code on the positioning of one-dimensional code to form a disturbance, but the two-dimensional code of space vulnerability relative to one-dimensional code more understand, so we consider a fuzzy and binary, see if it can be effective, as follows (remember to adjust the corresponding fuzzy parameters and threshold parameters, to obtain the relatively best results)

There is a certain effect, but at this time there is a problem bar code appeared black gap, not conducive to positioning the whole area, this time to do some morphological operation, remove the black gap, we choose closed operation, operator according to the situation of the gap, the width is greater than the height, rectangular gap. Process the results later.

Effect can, and problems, two-dimensional code area attached, or area is very large, on the back we calculate the area is still affected, but we observe the two-dimensional code of the connection area is clearly more than one-dimensional code connection area to be much thinner, that is, we can quickly corrode the connection of two-dimensional code, while also maintaining a one-dimensional code Then in the expansion back, the two-dimensional code of the connection should not have this large area attached, note that the number of expansion and corrosion should be consistent, to ensure the accuracy of the area of the results. I choose expansion corrosion four times, first expansion break two-dimensional code connection, the final result is shown as follows

At this point, the effect of the two-dimensional code is basically no, now we just need to look up the contour, and then calculate the area of each contour in the image, select the largest area of the contour, calculate the outline of the smallest bounding rectangle, you can find the corresponding image area. The results of this operation and the segmented barcode are as follows

So far, we have completed the location of the barcode positioning, and cut out the bar code of the group, next to the pattern to identify, identify before, summed up

    1. Morphological gradient operation, ignoring y-direction gradient, focusing on X-direction gradient
    2. Image blur, in order to facilitate the later image connection
    3. Image seeking threshold, accelerating algorithm processing, and rational use of the effect of fuzziness
    4. Morphological removal of black holes, closed operations
    5. Expansion corrosion, disconnection of the two-dimensional code connection
    6. Find contour, calculate contour maximum area, fit contour rectangle, get final result

Next bar code recognition, you can use the Zbar recognition library, the introduction of the library does not say, you can go to the official website to download, installation time Remember to choose the third option, otherwise there is no header file.

After the installation is complete, go to the installation directory, add the bin directory to the environment variable, add the header file address, the Lib address in the include in the VC + + directory in VS, and add the Lib name (connector-input-additional dependencies), then you can use, the specific use to view the following code, the results are as follows

The code is as follows

#include <opencv2/opencv.hpp>#include<iostream>#include<zbar.h>using namespaceCV;using namespacestd;using namespaceZbar;intMainintargcChar*argv[]) {    Charfilenamestring[ -]; Charwindownamestring[ -]; Charresultfilenamesring[ -];    Mat Srcimage,grayimage,blurimage,thresholdimage,gradientximage,gradientyimage,gradientimage,morphimage;  for(intFileCount =1; FileCount <8; filecount++) {sprintf (filenamestring,"f:\\opencv\\ barcode Detection and identification \\barcode_0%d.jpg", FileCount); sprintf (windownamestring,"result 0%d", FileCount); sprintf (resultfilenamesring,"f:\\opencv\\ barcode Detection and identification \\barcodeResult_0%d.jpg", FileCount); //reading ImagesSrcimage =Imread (filenamestring); if(Srcimage.empty ()) {cout<<"image file read error"<<Endl; return-1; }        //convert image to grayscale image        if(Srcimage.channels () = =3) {cvtcolor (Srcimage,grayimage,cv_rgb2gray); }        Else{grayimage=Srcimage.clone (); }        //setting the gradient amplitude of the imageScHARR (grayimage,gradientximage,cv_32f,1,0); ScHARR (grayimage,gradientyimage,cv_32f,0,1); //because the barcode we need is in the X-direction, we are more concerned with the magnitude of the gradient in the X direction and omit the gradient amplitude in the y direction .subtract (gradientximage,gradientyimage,gradientimage); //normalized to a eight-bit imageConvertscaleabs (gradientimage,gradientimage); //See what the gradient image looks like.//imshow (windownamestring,gradientimage); //blur the image so that some noise is eliminated .Blur (Gradientimage,blurimage,size (9,9)); //after the fuzziness of the threshold, the corresponding black and white two value of the image, the value of the binary threshold can be adjusted according to the actual situationThreshold (Blurimage,thresholdimage, About,255, thresh_binary); //look at the binary image//imshow (windownamestring,thresholdimage); //two after the value of the image, the bar code between the black and white is not connected, it is necessary to perform morphological operations, eliminate the gap, the equivalent of a small black hole, the choice of closed operation//because it is a gap between the bars, you need to choose a width greater than the lengthMat kernel = getstructuringelement (Morph_rect,size ( +,7));        Morphologyex (Thresholdimage,morphimage,morph_close,kernel); //look at the image after the morphology operation.//imshow (windownamestring,morphimage); //The bar code area is now connected so that the expansion corrosion is selected, and the same number of expansion corrosion should be used in order to keep the size of the graph unchanged.//first corrosion, so that other areas of the bright place less best is to eliminate, and then swell back, eliminate interference, the number of iterations according to the actual situation of choiceErode (Morphimage, Morphimage, Getstructuringelement (Morph_rect, Size (3,3), point (-1,-1),4); Dilate (Morphimage, Morphimage, Getstructuringelement (Morph_rect, Size (3,3), point (-1,-1),4); //look at the image after the morphology operation.//imshow (windownamestring,morphimage);Vector<vector<point2i>>contours; Vector<float>Contourarea; //The target contour is then searched for the purpose of calculating the image areafindcontours (morphimage,contours,retr_external,chain_approx_simple); //calculate the area of the contour and store it         for(inti =0; I < contours.size (); i++) {contourarea.push_back (Cv::contourarea (contours[i)); }        //find the most area of the contour        DoubleMaxValue;        Point Maxloc; Minmaxloc (Contourarea, NULL,&maxValue,NULL,&Maxloc); //The smallest bounding rectangle that calculates the largest contour of the areaRotatedrect Minrect =Minarearect (contours[maxloc.x]); //To prevent errors, check that the deflection angle of the rectangle cannot exceed the//if it's over, it's not found.        if(minrect.angle<2.0)        {            //The angle of the rectangle is found, but this is a rotating rectangle, so you have to regain an outsourced minimum rectangleRect Myrect =Boundingrect (contours[maxloc.x]); //Draw this rectangle in the source image.//Rectangle (srcimage,myrect,scalar (0,255,255), 3,LINE_AA); //look at the display, look for the right//imshow (windownamestring,srcimage); //The scanned image is cropped down and saved as the corresponding result, preserving some x-direction boundaries, so the rect is expanded to a certain extentmyrect.x= Myrect.x-(myrect.width/ -); Myrect.width= myrect.width*1.1; Mat Resultimage=Mat (Srcimage,myrect); if(!Imwrite (resultfilenamesring,resultimage)) {cout<<"File Save error!"<<Endl; return-2; }        }    }    //barcode recognition After detectionFilestorage file ("f:\\opencv\\ barcode Detection and identification \\result.xml", Filestorage::write);  for(intFileCount =1; FileCount <8; filecount++) {sprintf (resultfilenamesring,"f:\\opencv\\ barcode Detection and identification \\barcodeResult_0%d.jpg", FileCount); sprintf (windownamestring,"result 0%d", FileCount); Mat result=Imread (resultfilenamesring); if(!Result.empty ()) {            //now start identifyingCvtcolor (Result,grayimage,cv_rgb2gray); intwidth = grayimage.cols;//Extract Dimensions            intHeight =grayimage.rows; Image Image (Width,height,"Y800", grayimage.data,width*height);            Imagescanner scanner; Scanner.set_config (zbar_none,zbar_cfg_enable,1); intn =Scanner.scan (image);  for(Image::symboliterator symbol = Image.symbol_begin (); Symbol! = Image.symbol_end (); + +symbol) {cout<<"pic Name:\t"<<resultFileNameSring<<endl<<"Code type:\t"<<symbol->get_type_name () <<endl<<                    "Decode String:\t"<<symbol->get_data () <<Endl; Image.set_data (NULL,0); //XML File Write}}} waitkey (0); return 1;}

Resources are as follows

http://download.csdn.net/detail/dengrengong/9461797

OPENCV Barcode Detection and identification

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.