Table of Contents
ToggleQR codes have become a go-to tool for embedding information like URLs, texts, or even payment details and providing it to consumers. The main reason why QR codes have become famous is because they can be scanned with a camera and decoded instantly making them highly effective for quick access to data.
In this blog, we will explore a way to detect QR codes in Images using Python. OpenCV (Open Source Computer Vision Library) is an open-source computer vision library that has tools for image processing and analysis
Why OpenCV for QR Code Detection?
When I think of computer vision one of the libraries which comes to my mind is OpenCV. It gives us algorithms and functions for tasks like image processing, object detection, face recognition, and more. It is good for real-time applications that find QR codes in images.
The cv2.QRCodeDetector() function in OpenCV is specifically designed for detecting and decoding QR codes in images. With a few lines of code, we can identify QR codes in any image and extract the data they encode.
In this tutorial, we will learn how to use OpenCV to find the QR code in an image and read the embedded image.
Prerequisites
pip install opencv-python
Understanding OpenCV’s QRCodeDetector
The QRCodeDetector function in OpenCV simplifies the task of QR code detection. It has the capability to detect QR codes in an image and extract the data encoded inside them. The QRCodeDetector works by looking for specific patterns in the image, such as the three large squares in the corners of the QR code, and decoding the data from the rest of the image.
QRcodeDetector provides three outputs:
- Value: It contains the decoded data from the QR code
- Points: The four corners in the image where QR is present.
- Straightened QR code image: The QR code as a perspective-transformed image.
Step-by-Step Guide: Detecting QR Codes Using OpenCV
To understand it easily let us break down the process into simple steps.
Step 1: Import LibrariesImport all the libraries like cv2 (OpenCV) for QR code detection and Pillow for image handling.
import cv2 from PIL import Image import numpy as npStep 2: Load the Image
Once you have imported the necessary libraries then you need to load an image that contains QR.
If you want to generate a QR code then you can use this code.
import cv2 # Create an instance of QRCodeEncoder qr_encoder = cv2.QRCodeEncoder() # The data you want to encode into the QR code data = "https://www.example.com" # Generate the QR code qr_code = qr_encoder.encode(data) # Save the QR code image cv2.imwrite("generated_qr_code.png", qr_code)
To load the image you need to use cv2.imread() function with input parameter as the path of an image with QR code.
# Load the image image = cv2.imread('image_with_qrcode.png')Step 3: Initialize the QRCodeDetector
Initializing the QRCodeDetector object from OpenCV:
# Initialize the QRCodeDetector detector = cv2.QRCodeDetector()
This object performs QR code detection on the loaded image.
Step 4: Detect and Decode the QR CodeUsing the QRCodeDetector object, you can now detect and decode the QR code from the image.
The detectAndDecode() function returns three values i.e. value, points and straight_qrcode. Value provides encoded text from QR. Points are four corner points of QR in the image. Parameter straight_qrcode gives QR code image after perspective transformation.
# Detect and decode the QR code value, points, _ = detector(image)Step 5: Check if the QR Code is Detected
If QR code is detected then the value variable will contain decoded text. If no QR is found the value will be empty. We can use if statement to check whether QR is detected or not.
# Check if QR code is detected if value: print(f'Detected QR Code: {value}') else: print('No QR code detected')Step 6: Draw a Bounding Box Around the QR Code (Optional)
If a QR code is detected we highlight it by drawing a bounding box around it by using points returned by the detector. It is useful when we want visual verification of QR detection.
# Draw the bounding box around the QR code if points is not None: points = np.int32(points) for i in range(4): cv2.line(image, tuple(points[i]), tuple(points[(i+1)%4]), (0, 255, 0), 5) # Display the image with bounding box cv2.imshow('QR Code Detection', image) cv2.waitKey(0) cv2.destroyAllWindows()Step 7: Save or Process the Data
Once the QR code is detected and decoded we can save the decoded data as per our need. We can save the data in the database, and display it on GUI.
For instance, if the QR code contains a URL, you could open it in a web browser:
import webbrowser if value: webbrowser.open(value)
Full Code for QR detection in image using Python.
import cv2 import numpy as np from PIL import Image # Load the image image = cv2.imread('image_with_qrcode.png') # Initialize the QRCodeDetector detector = cv2.QRCodeDetector() # Detect and decode the QR code value, points, _ = detector(image) # Check if QR code is detected if value: print(f'Detected QR Code: {value}') else: print('No QR code detected') # Draw the bounding box around the QR code if points is not None: points = np.int32(points) for i in range(4): cv2.line(image, tuple(points[i]), tuple(points[(i+1)%4]), (0, 255, 0), 5) # Display the image with bounding box cv2.imshow('QR Code Detection', image) cv2.waitKey(0) cv2.destroyAllWindows()
Conclusion
In this blog, you have learned how to detect QR codes in images using Python giving you the capability to build more complex applications that require QR code scanning and decoding.
You can also read our other blogs on OpenCV QR code tracking and how to truncate decimal points.
Happy coding!