Holiday Sale - 40% OFF on All Courses and Programs Image

Holiday Sale - 40% OFF on All Courses and Programs Image

Holiday Sale - 40% OFF on All Courses and Programs Image

Holiday Sale - 40% OFF on All Courses and Programs Image

Holiday Sale - 40% OFF on All Courses and Programs Image

OpenCV QR Code Scanner ( C++ and Python )

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

QR Code scanner image
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!

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 : https://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]



Read Next

VideoRAG: Redefining Long-Context Video Comprehension

VideoRAG: Redefining Long-Context Video Comprehension

Discover VideoRAG, a framework that fuses graph-based reasoning and multi-modal retrieval to enhance LLMs' ability to understand multi-hour videos efficiently.

AI Agent in Action: Automating Desktop Tasks with VLMs

AI Agent in Action: Automating Desktop Tasks with VLMs

Learn how to build AI agent from scratch using Moondream3 and Gemini. It is a generic task based agent free from…

The Ultimate Guide To VLM Evaluation Metrics, Datasets, And Benchmarks

The Ultimate Guide To VLM Evaluation Metrics, Datasets, And Benchmarks

Get a comprehensive overview of VLM Evaluation Metrics, Benchmarks and various datasets for tasks like VQA, OCR and Image Captioning.

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.

Subscribe to receive the download link, receive updates, and be notified of bug fixes

Which email should I send you the download link?

 

Get Started with OpenCV

Subscribe To Receive
Image

We hate SPAM and promise to keep your email address safe.​