To complete this chapter, we are going to learn how to detect QR codes in images. This way, QR codes can also be used as markers for our augmented reality applications. The cv2.detectAndDecode() function both detects and decodes a QR code in the image containing the QR code. The image can be grayscale or color (BGR).
This function returns the following:
- An array of vertices of the found QR code is returned. This array can be empty if the QR code is not found.
- The rectified and binarized QR code is returned.
- The data associated with this QR code is returned.
In the qr_code_scanner.py script, we make use of the aforementioned function to detect and decode QR codes. The key points are commented next.
First, the image is loaded, as follows:
image = cv2.imread("qrcode_rotate_45_image.png")
Next, we create the QR code detector with the following code:
qr_code_detector = cv2.QRCodeDetector()
Then, we apply the cv2.detectAndDecode() function, as follows:
data, bbox, rectified_qr_code = qr_code_detector.detectAndDecode(image)
We check whether the QR code is found before decoding the data and show the detection by using the show_qr_detection() function:
if len(data) > 0:
print("Decoded Data : {}".format(data))
show_qr_detection(image, bbox)
The show_qr_detection() function draws both the lines and the corners of the detected QR code:
def show_qr_detection(img, pts):
"""Draws both the lines and corners based on the array of vertices of the found QR code"""
pts = np.int32(pts).reshape(-1, 2)
for j in range(pts.shape[0]):
cv2.line(img, tuple(pts[j]), tuple(pts[(j + 1) % pts.shape[0]]), (255, 0, 0), 5)
for j in range(pts.shape[0]):
cv2.circle(img, tuple(pts[j]), 10, (255, 0, 255), -1)
The output of the qr_code_scanner.py script can be seen in the next screenshot:
In the preceding screenshot, you can see the rectified and binarized QR code (left), and the detected marker (right), with a blue border, and magenta square points highlighting the detection.