• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Learn OpenCV

OpenCV, PyTorch, Keras, Tensorflow examples and tutorials

  • Home
  • Getting Started
    • Installation
    • PyTorch
    • Keras & Tensorflow
    • Resource Guide
  • Courses
    • Opencv Courses
    • CV4Faces (Old)
  • Resources
  • AI Consulting
  • About

OpenCV QR Code Scanner ( C++ and Python )

Vikas Gupta
November 26, 2018 Leave a Comment
Application OpenCV 4 Tutorial

November 26, 2018 By Leave a Comment

QR Code scanner image

Recently, OpenCV 4.0 was released with many improvements and new features. One of them is the QR code scanner. We had already written about Bar Code and QR code scanner in a previous post, which uses an external library – ZBar. So, we wanted to check how the OpenCV scanner works and if it is better than the Zbar one. In this post, we will see how to use this new QR code scanner from OpenCV. We will also compare it with the ZBar based scanner in case you want to chose which one to use.

You will need OpenCV 3.4.4 or 4.0.0 and above to run the code. In case you want to upgrade, Please refer to the posts:
OpenCV 3.4.4 on Windows / Ubuntu ,
OpenCV 4.0.0 on Windows / Ubuntu

QR Code Scanner in OpenCV

If you want to get more details on What exactly is a QR Code, I would suggest you visit the Wikipedia. Let’s just dive into the code for QR Code Detection. Please download the code from the link below. We have also provided code for comparing ZBar and OpenCV QR Code Detector in the download section.

Download Code To easily follow along this tutorial, please download code by clicking on the button below. It's FREE!

Download Code

C++ Code

First include the required header files

#include <opencv2/objdetect.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

using namespace cv;
using namespace std;

Utility function to display the box around the detected QR Code

void display(Mat &im, Mat &bbox)
{
  int n = bbox.rows;
  for(int i = 0 ; i < n ; i++)
  {
    line(im, Point2i(bbox.at<float>(i,0),bbox.at<float>(i,1)), Point2i(bbox.at<float>((i+1) % n,0), bbox.at<float>((i+1) % n,1)), Scalar(255,0,0), 3);
  }
  imshow("Result", im);
}

In the main funcion, we first read the image. Then, we instantiate a QRCodeDetector Object and use the detectAndDecode method to find the data and the location of the QR Code. Finally, we display the results.

int main(int argc, char* argv[])
{
  // Read image
  Mat inputImage;
  if(argc>1)
    inputImage = imread(argv[1]);
  else
    inputImage = imread("qrcode-learnopencv.jpg");

  QRCodeDetector qrDecoder = QRCodeDetector::QRCodeDetector();

  Mat bbox, rectifiedImage;

  std::string data = qrDecoder.detectAndDecode(inputImage, bbox, rectifiedImage);
  if(data.length()>0)
  {
    cout << "Decoded Data : " << data << endl;

    display(inputImage, bbox);
    rectifiedImage.convertTo(rectifiedImage, CV_8UC3);
    imshow("Rectified QRCode", rectifiedImage);

    waitKey(0);
  }
  else
    cout << "QR Code not detected" << endl;
}

Python Code

First import the modules

import cv2
import numpy as np
import sys
import time

Next, we read the input image, you can specify your own image from the command line

if len(sys.argv)>1:
    inputImage = cv2.imread(sys.argv[1])
else:
    inputImage = cv2.imread("qrcode-learnopencv.jpg")

Utility function to display the box around the QR Code

# Display barcode and QR code location
def display(im, bbox):
    n = len(bbox)
    for j in range(n):
        cv2.line(im, tuple(bbox[j][0]), tuple(bbox[ (j+1) % n][0]), (255,0,0), 3)

    # Display results
    cv2.imshow("Results", im)

Create a QRCodeDetector Object and detect the code and its location using the detectAndDecode method.

qrDecoder = cv2.QRCodeDetector()

# Detect and decode the qrcode
data,bbox,rectifiedImage = qrDecoder.detectAndDecode(inputImage)
if len(data)>0:
    print("Decoded Data : {}".format(data))
    display(inputImage, bbox)
    rectifiedImage = np.uint8(rectifiedImage);
    cv2.imshow("Rectified QRCode", rectifiedImage);
else:
    print("QR Code not detected")
    cv2.imshow("Results", inputImage)

cv2.waitKey(0)
cv2.destroyAllWindows()

Output

The decoded data is shown on the Terminal and a bounding box is drawn around the detected QR Code.

output-qr-code

Terminal Output

Time Taken for Detect and Decode : 0.044 seconds
Decoded Data : http://LearnOpenCV.com

Comparison

Now, let us compare the two implementations on the following grounds. Surprisingly, ZBar based scanner outperforms OpenCV’s QR Code in all aspects.

Speed

The ZBar library is almost twice as fast as the OpenCV QR code detector.

Robustness

The ZBar library produces more robust results as compared to OpenCV on the following factors as shown in the above video :

  • ZBar is better or comparable at various rotation
  • ZBar is better at different image sizes as seen from the different zoom levels in the video
  • ZBar is better at handling perspective distortions ( when the image is not upright w.r.t the camera.

Features

The ZBar library provides support for Bar codes as well, which is not yet there in OpenCV.

Overall, we can say that QR Code is launched recently in OpenCV and it might get better in future releases. Till then, if you want to use Bar code or QR Code in your application, stick with ZBar.

References

[OpenCV Documentation]

Subscribe

If you liked this article, please subscribe to our newsletter. You will also receive a free Computer Vision Resource guide. In our newsletter, we share Computer Vision, Machine Learning and AI tutorials written in Python and C++ using OpenCV, Dlib, Keras, Tensorflow, CoreML, and Caffe.

Subscribe Now


Tags: barcode OpenCV4 qrcode

Filed Under: Application, OpenCV 4, Tutorial

About

I am an entrepreneur with a love for Computer Vision and Machine Learning with a dozen years of experience (and a Ph.D.) in the field.

In 2007, right after finishing my Ph.D., I co-founded TAAZ Inc. with my advisor Dr. David Kriegman and Kevin Barnes. The scalability, and robustness of our computer vision and machine learning algorithms have been put to rigorous test by more than 100M users who have tried our products. Read More…

Getting Started

  • Installation
  • PyTorch
  • Keras & Tensorflow
  • Resource Guide

Resources

Download Code (C++ / Python)

ENROLL IN OFFICIAL OPENCV COURSES

I've partnered with OpenCV.org to bring you official courses in Computer Vision, Machine Learning, and AI.
Learn More

Recent Posts

  • Making A Low-Cost Stereo Camera Using OpenCV
  • Optical Flow in OpenCV (C++/Python)
  • Introduction to Epipolar Geometry and Stereo Vision
  • Depth Estimation using Stereo matching
  • Classification with Localization: Convert any Keras Classifier to a Detector

Disclaimer

All views expressed on this site are my own and do not represent the opinions of OpenCV.org or any entity whatsoever with which I have been, am now, or will be affiliated.

GETTING STARTED

  • Installation
  • PyTorch
  • Keras & Tensorflow
  • Resource Guide

COURSES

  • Opencv Courses
  • CV4Faces (Old)

COPYRIGHT © 2020 - BIG VISION LLC

Privacy Policy | Terms & Conditions

We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.AcceptPrivacy policy