QR code decoding extracts the data stored in a QR code image. In a robot camera workflow, detection finds the code’s location, while decoding returns its stored text so the robot can decide whether it has reached a desired marker. section 10.3 section 10.0
With OpenCV, create a QRCodeDetector and call detectAndDecode on an image frame. The call supplies decoded data and matching corner points; when data is present, return it and use the points to visibly mark the detected code. section 10.3.2
A practical decoding loop is:
- Load a still image or receive a new frame from the camera video stream. section 10.3.2 section 10.4.4
- Pass the frame to detectAndDecode and keep the returned decoded data. section 10.3.2
- If data was found, draw lines between the four detected points and overlay the decoded text. section 10.3.2
- Compare the decoded value with the QR code being sought before deciding whether to continue moving. section 10.3
Decode and mark a printed hello label
Photograph a printed QR code containing hello, load the saved image, then decode it. Display the decoded value in the console and preview the image with a blue box and text label over the detected code. section 10.3.2
Listing 10.1 detect_qr.py: Detecting and decoding QR codes in an image
#!/usr/bin/env python3
import cv2
BLUE = (255, 0, 0)
FONT = cv2.FONT_HERSHEY_SIMPLEX
decoder = cv2.QRCodeDetector()
def draw_box(frame, points, color, thickness):
points = [(int(x), int(y)) for x, y in points]
pt1, pt2, pt3, pt4 = points
cv2.line(frame, pt1, pt2, color, thickness)
cv2.line(frame, pt2, pt3, color, thickness)
cv2.line(frame, pt3, pt4, color, thickness)
cv2.line(frame, pt4, pt1, color, thickness)
def decode_qrcode(frame):
data, matches, _ = decoder.detectAndDecode(frame)
if data:
cv2.putText(frame, f'data: {data}', (30, 30), FONT, 1, BLUE)
draw_box(frame, matches[0], BLUE, thickness=3)
return data
def main():
frame = cv2.imread('hello.jpg')
decoded_data = decode_qrcode(frame)
print('decoded_data:', repr(decoded_data))
cv2.imshow('preview', frame)
cv2.waitKey()
main()
This reusable script defines a decoder, a four-line bounding-box helper, and a decode_qrcode function for still images. section 10.3.2
The same decode-and-mark functions can run on a live stream: watch for a new camera image, decode it, and refresh the preview. Test printed labels at usable camera scale; 6 cm-wide and 6 cm-high codes were tested successfully. section 10.4.4
