Detect and Decode QR Code in Image using OpenCV and Python

QR code is a two-dimensional barcode which stores encoded data. It can be a website URL, contact details, location coordinates, email address, plain text, etc. QR code can store more data than a linear barcode of equal size.

This tutorial provides example how detect and decode a QR code in image using OpenCV and Python.

Using pip package manager install opencv-python from the command line.

pip install opencv-python

We create an object of class QRCodeDetector. QR code is detected and decoded by using detectAndDecode method. It returns a tuple of values:

  • Decoded data.
  • An array of vertices of the found QR code.
  • An image that contains processed and binarized QR code.
import cv2

image = cv2.imread('test.jpg')

qrCodeDecoder = cv2.QRCodeDetector()
decodedData, points, straightQrCode = qrCodeDecoder.detectAndDecode(image)

if points is not None:
    print('Decoded data: ' + decodedData)

    points = points[0]

    n = len(points)
    for i in range(n):
        point1 = points[i]
        point2 = points[(i + 1) % n]
        cv2.line(image, tuple(point1), tuple(point2), color=(255, 0, 0), thickness=3)

    cv2.imshow('Detected QR Code', image)

If a QR code was found we print the decoded data and draw a bounding box around the detected QR Code.

Decoded data:
Detected QR Code

Leave a Comment

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