AI Hints
Home›Computer Vision Tutorial›Vision Projects One
Computer Vision · Lesson 77 of 111

Reading QR Codes

The easiest win in vision.

⏱ 2 min read▶ Video at 2:01:00🎓 Free
Watch this lesson in the Computer Vision courseWatch on YouTube ↗Full Computer Vision course

Every crate at Orchard Vision has to be tracked from the tree to the supermarket. The owner asks if you can use AI to read the crate labels. You could. Or you could print a QR code on each crate, and read it with three lines of code. The best vision engineers change the problem whenever they can.

Reading QR Codes
From the video: Reading QR Codes
  • Track every crate
  • Use AI to read labels?
  • Or change the problem

Reading a code

We generate a QR code, holding a crate number, and add the white border that it needs. Then the detector finds and reads it. For a tougher test, we blur the code, and rotate it by twenty five degrees. Run it. Both read perfectly. That's because QR codes were designed to be easy for machines. They have big corner squares for finding the code, and built in error correction, so that even a code with a damaged corner can still be read. So when you control what's being photographed, add markers, and save yourself months of machine learning.

qr.pypython
import cv2
import numpy as np

code = cv2.QRCodeEncoder.create().encode("CRATE-4471")
img = cv2.resize(code, (300, 300), interpolation=cv2.INTER_NEAREST)
img = cv2.copyMakeBorder(img, 40, 40, 40, 40, cv2.BORDER_CONSTANT, value=255)

text, points, _ = cv2.QRCodeDetector().detectAndDecode(img)
print("Read:", text)

blurred = cv2.GaussianBlur(img, (9, 9), 0)
turned = cv2.warpAffine(blurred, cv2.getRotationMatrix2D((190, 190), 25, 1), (380, 380), borderValue=255)
print("Rotated and blurred:", cv2.QRCodeDetector().detectAndDecode(turned)[0])
Output
Read: CRATE-4471
Rotated and blurred: CRATE-4471

Change the problem

This is a real mindset. Can't detect a shiny part? Change the light. Can't read a label? Print a code. Can't tell objects apart? Paint a mark on them. Warehouse robots follow QR stickers on the floor, because that's much more reliable than understanding a room. Before you train anything, ask whether you can control the scene.

Add markersQR and ArUco
Control the lightsimplest fix
Simplify the sceneplain backgrounds
Ask firstcan I change the problem?

Summary

If you can change the scene, you might not need a model at all. Next, a project that you've used on your phone.

Key takeaways
  • Markers beat models
  • QR codes correct errors
  • Control the scene when you can
Next up: A Document Scanner — build the classic phone app