Real time QR Code / Bar code detection with webcam using OpenCV and ZBar

Categories Computer Vision, Uncategorized

Tutorial: Real time QR Code / Bar code detection using webcam video feed / stream using OpenCV and ZBar

Pre-requisites:

You will need to have installed OpenCV and ZBar (see previous tutorials) for this to work.

Source on Github:  https://github.com/ayoungprogrammer/WebcamCodeScanner

Code:

 #include <opencv2/highgui/highgui.hpp>  
 #include <opencv2/imgproc/imgproc.hpp>  
 #include <zbar.h>  
 #include <iostream>  
 using namespace cv;  
 using namespace std;  
 using namespace zbar;  
 //g++ main.cpp /usr/local/include/ /usr/local/lib/ -lopencv_highgui.2.4.8 -lopencv_core.2.4.8  
 int main(int argc, char* argv[])  
 {  
   VideoCapture cap(0); // open the video camera no. 0  
   // cap.set(CV_CAP_PROP_FRAME_WIDTH,800);  
   // cap.set(CV_CAP_PROP_FRAME_HEIGHT,640);  
   if (!cap.isOpened()) // if not success, exit program  
   {  
     cout << "Cannot open the video cam" << endl;  
     return -1;  
   }  
   ImageScanner scanner;   
    scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);   
   double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video  
   double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video  
   cout << "Frame size : " << dWidth << " x " << dHeight << endl;  
   namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"  
   while (1)  
   {  
     Mat frame;  
     bool bSuccess = cap.read(frame); // read a new frame from video  
      if (!bSuccess) //if not success, break loop  
     {  
        cout << "Cannot read a frame from video stream" << endl;  
        break;  
     }  
     Mat grey;  
     cvtColor(frame,grey,CV_BGR2GRAY);  
     int width = frame.cols;   
     int height = frame.rows;   
     uchar *raw = (uchar *)grey.data;   
     // wrap image data   
     Image image(width, height, "Y800", raw, width * height);   
     // scan the image for barcodes   
     int n = scanner.scan(image);   
     // extract results   
     for(Image::SymbolIterator symbol = image.symbol_begin();   
     symbol != image.symbol_end();   
     ++symbol) {   
         vector<Point> vp;   
     // do something useful with results   
     cout << "decoded " << symbol->get_type_name() << " symbol "" << symbol->get_data() << '"' <<" "<< endl;   
       int n = symbol->get_location_size();   
       for(int i=0;i<n;i++){   
         vp.push_back(Point(symbol->get_location_x(i),symbol->get_location_y(i)));   
       }   
       RotatedRect r = minAreaRect(vp);   
       Point2f pts[4];   
       r.points(pts);   
       for(int i=0;i<4;i++){   
         line(frame,pts[i],pts[(i+1)%4],Scalar(255,0,0),3);   
       }   
       //cout<<"Angle: "<<r.angle<<endl;   
     }   
     imshow("MyVideo", frame); //show the frame in "MyVideo" window  
     if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop  
     {  
       cout << "esc key is pressed by user" << endl;  
       break;   
     }  
   }  
   return 0;  
 }  

To Test

Find any QR code or bar code and hold it close to your webcam and it should pick up.

36 Comments

  • navya
    June 6, 2014

    this is really nice…..

    But how can we apply the same thing to a Kinect?

    • ayoungprogrammer
      June 7, 2014

      Use the kinect to get a screen capture and then put it into zbar. I'm not really sure how kinect works though

  • Gleisson Gomes
    June 12, 2014

    hello, first like to apologize for my typos.
    I'm having a little trouble installing the version 3.2.02 on windows 7 x86, and import the library in microsoft visual stuidio 2013.
    it could be possible to make a tutorial.

  • navya
    June 18, 2014

    I have one doubt. The thing to be decoded has always to be in alignment with the web cam…. if the QR tag is not in parallel it is not getting decoded… Infact it takes a lot of time to hold the QR tag and adjust it for aligning with the webcam… how to fix it?

    • ayoungprogrammer
      June 18, 2014

      This was not a problem when I tried it. Your webcam may be poor quality or your qr code may be too small

  • navya
    June 19, 2014

    Ok. got it.. Thanks…. 🙂
    Just one thing more… The code tells us only one angle wrt only one axis… What modification can we make in the code so that it tells us all d three angles wrt all the 3 axis?

    • ayoungprogrammer
      June 19, 2014

      You currently have a 2d image for input and it is very difficult to recover 3d information.

  • navya
    July 3, 2014

    Hey can u plz explain the significance and role dat OpenCv and Zbar play in the project?

  • ayoungprogrammer
    July 3, 2014

    Opencv is a library for image processing and zbar is the library for scanning codes. We use Zbar to help us find the qr code and we use opencv to display the data

  • iskandar salama
    July 11, 2014

    hello i'm getting a linker error LNK2001: unresolved external symbol zbar_image_scanner_create and 24 more similar errors when building project and i'm sure i add libzbar-0.lib In additional dependencies, can you help me ?

  • chammem
    July 29, 2014

    how to install ZBAR library in c++

  • furkan üzmez
    November 18, 2014

    before tutorial qr code reading from image it works but when ı tested real time qr code reading ,Cam not open !!!
    what can be my problem ?

    • ayoungprogrammer
      November 18, 2014

      What kind of error are you getting?

    • furkan üzmez
      November 22, 2014

      I solved problem. my cam open slowly so that program close quickly.I add unused code blocks after video capture line .It works .thanks for your interest 🙂

  • Lahiru S Ranasinghe
    November 21, 2014

    can we get the QR code position? if can what is the code which gets the position of it?? plz reply soon as possible. thnx

    • ayoungprogrammer
      November 21, 2014

      symbol->get_location_x(0),symbol->get_location_y(0))
      symbol->get_location_x(1),symbol->get_location_y(1))
      symbol->get_location_x(2),symbol->get_location_y(2))
      symbol->get_location_x(3),symbol->get_location_y(3))

      These will be the coordinates of the 4 corners of the qr code

  • Jack May
    November 26, 2014

    Has anyone scanned barcodes through a webcam attached to the Galileo? I attempted to use the zbar library, building it on my kubuntu machine just to try it out, but it seems that the stable release has deprecated (and unsupported) dependencies, while the latest github version has its own issues (can't find installed packages). I have never used opencv or v4l, so I am unaware how much effort it would be to write my own program to read barcodes. Has anyone completed a project similar to this one? Is there something obvious I am missing?

    Labels: OpenCV ZBar Webcam Barcode/QR Code Rdlc

  • Jose Wemerson Farias Lima
    October 6, 2015

    Hi, do you hava email ? I need help, 'cause I don't know to do this. My email is: [email protected]

  • Jose Wemerson Farias Lima
    October 6, 2015

    Which program can I use ?

  • Rey Jericko Enumerables
    January 11, 2016

    nice tutorials. helped me a lot. from installing visual c++ to opencv to zbar to qr scanning. thanks 🙂

    i have 1 problem tho. the program can decode the qr code but gives an error after. same thing with the other tutorial you made about manual qr scanning.

    heres the pic. https://imageshack.com/a/img633/1917/1KsItG.png

    • ayoungprogrammer
      January 28, 2016

      Which OpenCV version are you using?

  • Rey Jericko Enumerables
    January 11, 2016

    thanks by the way 🙂

  • Salman Naseem
    February 14, 2016

    please tell me how can i add open CV in Dev C++

  • Unknown
    June 4, 2016

    hello i am getting binary not found when i am running you code in eclipcse cdt could any one help

  • 김유진
    June 9, 2016

    The camera I can not recognize the bar code in the work. What should I do?

  • WT801
    January 18, 2017

    Great tutorial dude!
    I did have some problems, – In-case anyone else had difficulties here are my finds:
    The Camera doesn’t open or the program just stops immediately: because your webcam is assigned at a different number even try “VideoCapture cap(-1); // open 1st available”
    error “Cannot find opencv_core.dll” ect : If you are using VisualStudio version 2015 (aka VC12), the open cv path in your PATH environment should be altered to “OpenCV_2_4_10\build\x86\vc12\build”

  • QR code dectection – My Island
    March 29, 2017

    […] http://blog.ayoungprogrammer.com/2014/04/real-time-qr-code-bar-code-detection.html/ […]

  • Final Semester is nearing! – My Final Semester M.Tech Project
    July 12, 2017

    […] Reference 2: Tutorial: Real time QR Code / Bar code detection using webcam video feed / stream using OpenCV and Z… […]

  • Unknown
    December 16, 2017

    Hey, thanks for the tutorial!
    Is there a way to analyze the barcodes slowly?
    I get multiple messages with the same barcode.

    • ayoungprogrammer
      December 21, 2017

      I’m not sure what you mean by more slowly.

  • meik
    February 11, 2018

    how can i compiler ?

  • Paul Jones
    September 12, 2018

    What i need is to read and decode barcodes from images. And the output should tell me what barcode types are they. So, i tried CnetSDK. Its barcode reader sdk works well for all my needs.
    If you need, see http://www.cnetsdk.com/net-barcode-scanner-sdk.

  • gibito
    June 26, 2019

    how can i build zbar to work with codeblocks, using gcc compiler

  • Prince
    December 27, 2019

    Thank You so much.. great post . can you tell me how to display barcode text on screen ?

Leave a Reply

Your email address will not be published. Required fields are marked *