A Python packet involving the use of the cv2 module to detect and decode the scanned QR code and display the coded data in the form of a string.
This Python packet uses cv2, os, pillow modules to detect and decode the QR code of the live frame from the cam and displays the data coded in the QR code.
import cv2 import os from PIL import Image
The QRCodeDetector() function of the cv2 module creates the QR code detection function that takes the frame as the input and returns the data and coordinates of the scanned QR code. The os module is used to save the data decoded from the QR code.
Capturing and reading frame:
# Capturing frame in cap varibale cap = cv2.VideoCapture(0) # Creating detection function for QR Code detection = cv2.QRCodeDetector() while True: # Reading frame cap ret,frame = cap.read()
The above code captures the live frame in the 'cap' variable. The 'detection' is the QR code detection and decoding function created using the cv2 module to extract useful information from the QR code. The captured frame is read into the 'frame' variable that is passed onto the detection function for decoding.
Detecting, Decoding, and Display QR code data:
while True: # Reading frame cap ret,frame = cap.read() # Decoding the frame for QR Code data data,box,point = detection.detectAndDecode(frame) # Printing frame cv2.imshow("QR Code Scanner",frame) if cv2.waitKey(1) & len(data)>1: break # Printing the QR Code data print(data) cap.release() cv2.destroyAllWindows()
This code detects the QR code and decodes its data into a 'data' variable. If the QR code is not detected the 'data' is empty. Box variable stores the output array of vertices of the found QR code quadrangle and will remain empty if QR code is not found. The point variable stores the output image containing rectified and binarized QR code.
After detecting and decoding, the frame is released and data decoded from the QR code is displayed in form of a string. The frame window is destroyed using the destroyAllWindows() function of the cv2 module.
Submitted by Rachit R Jindal (rachit99)
Download packets of source code on Coders Packet