A QR code scanning algorithm turns the black-and-white square you point your phone at into text, a link, or a Wi-Fi password. The short version: the scanner locates the code's three corner squares, straightens the image, reads the timing patterns to work out the grid size, samples every module, checks the error-correction bits, then decodes the data. You don't need to write code to use this guide — it walks through the process a scanner follows, so you can build one, debug one, or just understand why a scan fails.
What You'll Need
- A camera or image source (phone camera, webcam, or a stored image file).
- A programming language with image access — Python with OpenCV and a QR library such as pyzbar or zxing-cpp is the easiest starting point.
- A sample QR code: generate one from any reputable online generator and save it as a PNG.
- Optional: a printed copy and a phone, so you can test live camera capture as well as still images.
Step-by-Step
- Capture or load the image. For a still image, read it into memory as a grayscale array — colour adds nothing to decoding and triples the data you process. For a live camera, grab frames one at a time rather than streaming, so you can process each frame fully before the next arrives.
- Convert to grayscale and boost contrast. A QR code is designed for high contrast, but phone photos often arrive washed out. A simple threshold (turning each pixel pure black or pure white above or below a cutoff) works for clean images. For uneven lighting, use an adaptive threshold that calculates the cutoff separately for small patches of the image.
- Find the three finder patterns. Every QR code has three large square markers — one in each of the top-left, top-right and bottom-left corners. The algorithm scans rows and columns looking for the 1:1:3:1:1 ratio of dark-light-dark-light-dark runs that defines these markers. Three hits in the expected L-shape confirm a candidate code and give you its position, scale and rotation.
- Correct perspective. Because the code may be photographed at an angle, the algorithm maps the three finder centres (plus the bottom-right corner, inferred from the grid) onto a flat square. This is a perspective transform: it warps the tilted quadrilateral into a straight-on view so every module lands on a predictable pixel.
- Read the timing patterns and format information. A line of alternating black and white modules runs between the finder patterns. Counting them tells the algorithm the grid size — versions range from 21×21 modules up to 177×177. Next to the finder patterns sit the format bits, which state the error-correction level (L, M, Q or H) and the mask pattern applied to the data.
- Unmask the data. QR encoders XOR the data area with a repeating pattern to avoid large blank regions that confuse scanners. The algorithm reverses that XOR using the mask number from the format bits, restoring the raw module values.
- Read the modules in the correct order. Data is stored in a zigzag: two-module-wide columns read upward, then downward, skipping the function patterns (finders, timing, alignment and format areas). The algorithm walks this path and assembles a bit stream.
- Decode the data segments. The bit stream starts with a mode indicator (numeric, alphanumeric, byte or kanji), a character count, and then the payload. The algorithm parses each segment in turn until it hits the terminator. Byte mode is usually UTF-8 text; alphanumeric mode packs pairs of characters into 11 bits for compactness.
- Apply error correction. Reed-Solomon codewords are interleaved with the data. The algorithm computes syndromes and, if they are non-zero, runs the correction maths to repair flipped modules — up to roughly 7% of codewords at level L, 30% at level H. Only after correction does the payload count as valid.
- Validate and return. Check the decoded length against the character count, confirm the mode is one you support, and hand back the string. If any check fails, discard the frame and try the next one rather than returning garbage.
Common Mistakes
Treating a colour image as if it were grayscale without converting it first produces nonsense thresholds. Skipping the perspective transform and sampling on a fixed grid fails the moment the code is tilted. Forgetting to skip function patterns when reading the zigzag corrupts every codeword after the first finder. Ignoring the format bits means you unmask with the wrong pattern and get plausible-looking but wrong text. Finally, decoding before error correction — or accepting a result whose Reed-Solomon check failed — is how scanners end up returning half-correct URLs.
Tips
Test with codes at all four error-correction levels; level H codes survive heavy damage and are the best stress test. Rotate and skew your sample images deliberately to confirm the perspective step works. Keep a library of real-world photos — receipts, screens, stickers — because synthetic images hide problems that camera noise exposes. Log the grid version and mask number on every decode; when something breaks, those two numbers tell you instantly whether the failure is in detection or in reading. And cap the work per frame: if no finder pattern is found within a reasonable search, drop the frame rather than grinding through a full scan.
Troubleshooting
No code detected: check that the image is actually grayscale and that your threshold produces clean black and white. If the code is small in frame, upscale before searching. Finder patterns found but decode fails: the perspective transform is probably off — verify the fourth corner is being inferred correctly. Garbled text: confirm the mask number and error-correction level are being read from the right modules; a one-module offset in the format area flips both. Works on stills, fails on camera: motion blur and rolling-shutter distortion are the usual culprits — request a higher shutter speed or average two frames before thresholding. Intermittent failures on damaged codes: raise the error-correction level in the generator and retest; if it still fails, the damage exceeds the correction capacity and no algorithm will recover it.
Frequently Asked Questions
Do I need to write my own decoder?
No. Mature libraries handle detection, correction and decoding; building your own is useful for learning but rarely necessary in production.
Why does a QR code need three finder patterns?
Three points define position, scale and rotation unambiguously; a fourth corner is inferred mathematically, which is why only three are printed.
What is the maximum amount of data a QR code holds?
It depends on version, mode and error-correction level — the largest versions hold a few thousand bytes in byte mode. Check the specification for exact limits rather than assuming a single number.
Can a scanner read a code from a screen?
Yes, but screen glare, refresh flicker and low brightness reduce contrast; increase screen brightness and avoid direct reflections.
Does error correction mean a damaged code always works?
No. Reed-Solomon repairs up to a percentage of codewords set by the level; beyond that, decoding fails cleanly rather than guessing.