Writing a QR code reader from scratch
November 22, 2026
QR codes are everywhere, and they’ve been around since the 90s. I wondered if I could write my own QR code reader from scratch. I didn’t have time to do it all by hand, so I used agentic coding to speed up the research and coding. I still chose the detection algorithms without looking up how other readers work. Even so, I was surprised by how much work it took to get something halfway decent.
The problem: finding a QR code in an image
The scope of the project is simple: detect a QR code, find its corners, and decode the payload. Before diving in, let’s look at a QR code:
You may notice the patterns in the top-left, top-right and bottom-left corners. These are the finder patterns of a QR code. They are always present and contain no data themselves; they exist purely to help locate the code. If you draw a horizontal or vertical line through one of these patterns, you always see black, white, black, white, black in a ratio of 1:1:3:1:1. That signature makes the finder patterns relatively easy to spot, and later on we’ll see how.
To detect a QR code, you only need to find three things that look like finder patterns under the 1:1:3:1:1 rule and sit roughly in an isosceles triangle. Such a triangle has one right angle and two 45-degree angles, and the finder pattern at the right angle must be the top-left one. Assuming the QR code is not mirrored, the bottom-left finder pattern then sits counterclockwise from the top-left, and the top-right one sits clockwise from it.
There’s more to it, though. QR codes come in different sizes, known as versions. The smallest is version 1, which is 21×21 dots, up to version 40 at 177×177. In general, version has dots on each side. To decode a code you need to know its version. Fortunately, each finder pattern measures dots on a side. So if, say, the finder patterns are 70 px on a side and the gap between them is 110 px, then one dot is 10 px and the total side length is px, i.e. 25 dots — which is version 2. This works well for small versions. For larger versions we may only be able to pin the version down to a range like 32–35. In that case we can try decoding under the most promising candidate versions and move on to the next when one fails. The version is also encoded separately in the QR code itself for version 7 and up, which helps.
To decode the code, we do need to know the corners of the three finder patterns fairly precisely. That establishes a correspondence from pixels to the dot grid: if we want to know whether the dot at (4, 10) is black or white, we know which pixels to inspect in the original image. The more precisely we know the location and orientation of the finder patterns, the more reliable this correspondence will be, and the more likely decoding is to succeed.
This suggests the following pipeline:
- Find parts of the image that look like finder patterns using the 1:1:3:1:1 rule.
- Find the corners of each finder pattern, or reject the candidates that fail.
- Find which triplets of finder patterns actually make up a QR code.
- Determine the version
V, and thus the number of dotsN=4*V+17on each side. - Sample the QR code to get the
NxNdot pattern. - Decode the payload.
That, at a high level, is the pipeline I implemented. None of these steps use OpenCV. That would feel a bit like cheating: OpenCV already implements so many of the useful algorithms, but then they would remain black boxes. A big part of this project was figuring out what is inside those boxes.
One thing the pipeline above leaves out is the alignment patterns. These are smaller 1:1:1:1:1 patterns (a black outer ring, a white inner ring, and a black dot in the center) that you can see in every QR code with version greater than 1. Their number and placement depend on the version. Because the sampling step needs the QR code geometry more precisely at higher versions, these patterns help improve localization. For simplicity I started without them; as we will see, they are not strictly necessary to decode a QR code, even at higher versions, but they do help on the harder photos.
Finally, there is the matter of perspective. A QR code captured head-on is much easier to decode than one captured at an angle. I want my detector to handle QR codes that are rotated or viewed at unusual angles — basically, snap a photo from any odd angle and the detector should still find the code. That is far more satisfying than requiring the code to already be roughly aligned. But, as we will see, it also makes the problem much harder.
I hope the basic idea and scope of the project are now clear, so let’s dive into how each step of the algorithm works.
From pixels to candidates
The finder patterns follow a 1:1:3:1:1 dark-bright-dark-bright-dark pattern. How can you detect that? First you have to know what ‘dark’ and ‘bright’ even means in the first place. In a photo, the white part of a QR code is more like light gray plus some random noise. An easy way to do that is by converting the image to pure black and white using a threshold. We can convert the RGB value to grayscale, and then compare the value to a threshold . If the mean RGB value is below , then it’s black, above it’s white. The figure below shows the same crop in color and in grayscale.
But how do you determine ? You can’t just set it to , because some images are bright and some are dark depending on ambient light and camera settings. One way to automatically determine a reasonable threshold is using Otsu’s method. This converts the pixel intensities of the whole image into a histogram, and then finds the threshold that best separates the image into a bright and dark class (minimizing the intra-class variance). It is a relatively simple and very popular thresholding method, and it works well for many images. The animation below shows the same image at different thresholds.
Otsu’s method does have a major flaw: the lighting in the image isn’t always uniform. It often happens that some parts of the image are more brightly lit than others, and then the ideal threshold may be higher in a brighter part of the image and lower in a darker part of the image.
To correct for this we can try to estimate the difference in luminance across the image. We apply an aggressive blur, which destroys all details, but retains information on how bright a region is on average. We then correct the image by dividing by that mean luminance.
As you can see below, this makes the histogram much more bimodal (having two peaks), which Otsu’s method can cleanly separate. The result is a binarized image that is much cleaner than using Otsu’s method directly.
Now the image is divided in ‘dark’ (0) and ‘light’ (1) pixels. One row of the image could look like this: 111001100000011001111001, where the bold numbers are a 1:1:3:1:1 pattern. How do we detect this pattern? We can use run-length encoding. We convert the string of 0’s and 1’s above into the lengths of consecutive 1’s or 0’s. The string starts with 3x1, then 2x0, etc. so we can write: 3, 2,2,6,2,2, 4,2,1. Now observe that 2:2:6:2:2 is precisely the same set of ratios as 1:1:3:1:1!
The real world is messy, and a perfectly valid finder pattern might have RLE 51, 47, 148, 45, 52. How do we compare that to 1:1:3:1:1? There are many ways to do this, but a simple way is to divide by the sum and compare to the ideal, keeping each element within 30% of the ideal. Here the sum is 343, and the reference 1:1:3:1:1 sums to 7, so we can use that to normalize. This transforms 51, 47, 148, 45, 52 into 1.04, 0.96, 3.02, 0.92, 1.06; all within 30% of 1:1:3:1:1, so we accept this sequence as a potential finder pattern.
The figure below shows a real row through two finder patterns. The left finder is centered on the scanline, so its five runs normalize cleanly. The right finder is off-center at this row, so its cut is distorted.
You may think that 30% is a pretty loose threshold, and you’d be right. But there are good reasons for this. First of all, it’s easy to throw away false positives later, so we are optimizing for high recall at this point. On the other hand, QR codes can be rotated, blurred, distorted by perspective, etc., so a loose threshold is really necessary in practice. Even then this method is not ideal. Just one rogue pixel can mess everything up. There are ways around that, but it works well enough in practice. It’s rather effective for something so cheap and simple!
The animation below shows the scan in action: the binary image is recolored, the scanline sweeps down, and every 1:1:3:1:1 match leaves a box behind.
Observe, however, that a finder pattern can have many matching RLE 5-tuples. We ideally only output one candidate region per finder pattern, so we have to group the RLE 5-tuples that belong to the same finder pattern somehow. This is fortunately really easy! Well, it took a few tries to get right, but you know, it’s easy in hindsight. What I settled on after some painful trial and error is the following approach.
- Encode each candidate with the pixels denoting each of the 6 transitions (white to black, black to white, …). We estimate the cluster’s height from the width of the center segment.
- We can check if candidate A overlaps candidate B if all segment widths are within 22% of each other, if the vertical distance is less than 1.2× the ‘height’ of the candidate, and if the center x coordinate of B lies in the central segment of A.
Then if two candidates overlap we merge them by taking the mean of all quantities of interest (segment widths, estimated height). This gives a candidate cluster. When merging clusters consisting of different numbers of candidates, we take a weighted mean to give more weight to clusters with more candidates.
The full procedure is to take a cluster, check it against all other clusters, and merge greedily. You do this top to bottom, and stop when there’s nothing left to merge. With some minor optimization this is pretty fast.
At first I tried fancier clustering approaches like agglomerative clustering, and different overlap metrics. Some methods were too expensive, but most simply didn’t work that well and would for example refuse to merge candidates, or end up with a cluster center that is not really representative of the finder pattern’s center. My approach works and is fast and simple, but I have no good intuition why it works better than other approaches I tried. I think that the simple merge rule just ends up capturing the right geometry.
This clustering step reduces the number of candidate finder patterns substantially, but we’re not done yet! There is a cheap trick to substantially reduce false positives. A real finder pattern still looks like a finder pattern if you rotate it 90°, because, well, it’s a square (duh). So we can just take a look at the RLE in the vertical direction (column by column instead of row by row). If our candidate finder pattern also has a match on the RLE in the vertical direction (with a slightly more relaxed threshold) then we keep it, else we throw it out.
The animation below shows both steps on a real photo. The raw candidates merge into five clusters, and the vertical check throws out the two false positives in the QR data region, leaving the three finder patterns.
Finding the corners
Now we have hopefully correctly identified the locations of all the finder patterns, with maybe some false positives. How do we go from there to a decoded QR code? We could just take all triplets of candidate finder patterns, and see if they roughly form a right-angled triangle, and just try to decode the QR code. But that doesn’t work, because to decode you need to know pretty precisely where you are inside the QR code.
The animation below shows what that looks like on a v1 code. The three finder centers are enough to get a rough affine alignment, but not enough to correct the perspective. The sampled matrix is close, and then the bits in the bottom-right start to go wrong.
The first attempt: flood filling the finder pattern
At this point I was still writing everything by hand. No AI, no autocomplete doing the thinking for me — partly because I wanted to keep my hand in, and partly because I hadn’t given in yet.
The finder-pattern detector had already done most of the hard work for free. The 1:1:3:1:1 scan gives us a seed pixel on the outer black ring, plus the white and black ring structure around it. So the obvious next move was to grow that seed into the whole finder pattern.
All the pixels that belong to the pattern form a connected component. The simplest way to recover one is flood filling: start with a single pixel, look at its neighbors, and if they have the same color, add them to the mask. Then keep going. A few iterations later you have the entire pattern.
Once we have the mask, we can look for its corners. I used a few heuristics: the point farthest from the center is probably one corner, the others should be roughly 90 degrees away and also be local maxima along the boundary. A bit of non-maximum suppression leaves four candidates.
In practice the flood fill itself was usually not the problem. The thresholding isn’t perfect, so a mask can have holes, and that does happen. But the failure I kept running into was one step later: turning the boundary into four corners. The farthest-point heuristic works fine when the finder is roughly square in the image. Under perspective it doesn’t. The finder becomes a general quadrilateral, the farthest points are not necessarily the corners, and the four points can end up bunched around the same acute corner. The mask was clean; the corners were wrong.
The two animations below show what that looks like on the same photo. In the first, the fill and the corner picks work. In the second, the mask is still clean, but the corners collapse onto the acute side.
I spent quite a bit of time trying to make this work, but it never reached the recall or precision I wanted. So I dropped it and started over.
The second attempt: Hough lines
The next thing I tried was a more classical computer-vision approach: Hough lines.
The basic idea is almost annoyingly simple. Finding edges is not that hard, and once you have an edge, the image gradient also tells you its direction. If you know the direction and one point on the edge, you know the line. So you can let every strong edge pixel vote for the line it thinks it is on. Discretize the angle and the intercept into bins — I used about half a degree and half a pixel — and keep a table of votes. If many edge pixels agree that “the line with this angle and this intercept” exists, there probably is a line there. Then you take the largest peaks in the table, turn each peak into a line segment, and intersect the four outer segments to get the corners.
To find the edges and angles I used something like Canny, but with fewer steps. First a little blurring, which matters: without it you get staircase edges and messy angles. Then a Sobel filter for the x and y derivatives, from which you get the gradient magnitude and angle. Then non-maximum suppression along the gradient direction, so you keep only the thin edge pixels you actually want. For the Hough table, you find the largest peak, suppress a small neighborhood around it, and repeat. Each peak gives you a line; to turn it into a segment you look at the support set — the edge pixels close to that line — and fit or trim the segment to those points. Intersect the four outer segments and you have the finder corners.
This was a step up from flood filling. It worked better, and it was a lot faster. On synthetic images it looked like it was going to work. On real images it kind of, sort of worked, but never reliably enough.
There were three problems. The first was gaps. Real edges are not perfectly smooth, so the non-maximum suppression leaves gaps that the algorithm cannot bridge, and a line that should be one segment comes out as several disconnected pieces. The second was that the cutout around the finder pattern still contains other edges: parts of the QR code, or just background clutter. We do not know exactly where the finder pattern is — if we did, we would already know its corners — so we cannot exclude those edges, and they mess up the voting. The third was weak edges. If the finder boundary is not strong enough, its votes get diluted, and the right line either does not win or does not show up at all.
So we ended up in the same place as before. The basic approach looked good on synthetic images, but on real images it was finicky. Some parameter tuning helped, but no setting made it work all the time. Finding the corners was still hard, and making it robust was harder.
The two figures below show a clean case and a failure case. In the clean one, each outer edge produces a single clear peak, and the four lines intersect at the corners. In the failure, the edges break into pieces and other QR edges compete for votes, so the selected lines are wrong.
The third attempt: ray profiles
The next idea was to treat the finder pattern as a signal-processing problem.
If you start at the center of a finder pattern and cast a ray outward, the intensity along that ray has a very specific shape. It starts dark, goes bright, dark again, bright again, and then eventually turns into whatever is around the finder pattern. The 1:1:3:1:1 structure is right there in the signal. So instead of trying to find edges and lines, I could fit a known template to that one-dimensional profile and read off the transition points. The fit has a scale parameter — the module pitch — and once we know the pitch, we know where every transition should be along that ray.
This is much more robust than thresholding and then trying to recover a clean boundary. If one pixel in the middle is the wrong color, or the threshold is slightly off, the fit doesn’t care. The whole profile votes on the scale, and the transitions come out as a smooth compromise instead of a hard edge.
We sample 36 half-rays, 10 degrees apart, at 120 points each. For each ray, we fit the template and place a boundary point 3.5 module pitches from the center. That gives us 36 candidate boundary points, one per direction, each one probably sitting somewhere on the outer edge. The inner transitions help estimate the pitch, but we don’t need them to find the corners.
Then the problem became clustering those points into the four sides. This turned out to be the hardest part of the whole ray-fitting approach. The ray profiles themselves were fairly straightforward, and the rest was mostly parameter tuning, but getting the clustering right took a lot of iterations. I tried a whole range of clustering algorithms here. What worked best was to treat a cluster as defining a single line, fit that line with total least squares, and then decide whether a nearby point belongs to it by seeing how much the fit worsens. If the point makes the line much worse, it probably belongs to a different edge. Refit, repeat. TLS is a simple line fit, and the residual tells you how well the points actually lie on a line, which is exactly the signal I needed.
Once we have four line clusters, we can intersect the lines to get the corners. I also added a gate: the four clusters have to contain most of the boundary points. In a real finder pattern, almost all of the ray points land on one of the four outer edges; there are a few outliers, but the majority are consistent. If the clusters explain too few points, we discard the candidate.
I only used the outer edges for the final geometry. You could use the inner transitions too and get a slightly better fit, but that wasn’t the bottleneck anymore. The ray fitting worked well enough that the bottleneck moved: now the hard part was finding the candidate finder patterns in the first place. Which meant the corner finder was no longer the thing holding the detector back.
Choosing a triplet
Suppose we have found three finder patterns and their corners. Which one is the top-left, which is the top-right, and which is the bottom-left? We do not assume the QR code is upright — it could be rotated by any angle, including 180°. And if we found more than three candidates, which three belong to the same QR code? We need an algorithm for this, and as with everything else in this project, it is trickier than it appears at first glance.
Matching the outer edges
Each finder has four outer edges. If two finders sit next to each other in the QR grid, two of their edges should lie on the same line. So for every pair of finders, we compare their four edges. We don’t know which edge is which, so we try both one-to-one pairings of the opposite edges and keep the best match. If two pairs line up, the finders are associated.
The three finders of a QR form an L. One finder is connected to the other two, and those two are not connected to each other. The finder at the corner of the L is the top-left finder.
That leaves the top-right and bottom-left. Call the two remaining finders A and B. Take the vectors from the top-left finder to A and B. If the cross product (A − TL) × (B − TL) is positive, A is the top-right and B is the bottom-left; if it is negative, swap them. That’s the orientation.
And that’s the triplet.
Finding the version
At this point we have a triplet, so we know where the QR code is and roughly how it is oriented. But we are not ready to decode anything yet. To sample the code we need to map it onto a standardized grid, and before we can do that we need to know how many modules that grid has. That’s the version. Version 1 is 21×21 modules, and each version after that adds four modules per side, so version is . If we get the version wrong, the grid is wrong, and every sample after that is wrong too.
The naive way is to try all forty versions and see which one decodes. That works, but it means forty homographies, forty samplings, and forty decode attempts, and almost all of them are obviously wrong. We can rule out most versions before we do any of that, just by looking at the points we already have.
Each finder pattern gives us four outer corners. Those are landmarks: we know where they sit on an ideal QR code. The top-left finder is a 7×7 square, the top-right finder is the same square shifted modules to the right, and the bottom-left finder is the same square shifted modules down. The only unknown is .
The trick is to measure something that does not change under perspective. Take four ordered points on a line, with coordinates along that line. Their cross-ratio is
This number is invariant under any projective transformation. If you photograph the same line from a different angle, the individual distances change, but the cross-ratio stays the same. That is exactly what we need, because the QR code in the photo has been through an unknown projective transform.
Now look at the left edge of the QR code. It passes through four corners: the top-left and bottom-left corners of the top-left finder, and the top-left and bottom-left corners of the bottom-left finder. On an ideal version- code those points sit at positions , , and along the edge. So we can compute the cross-ratio of the four points we detected, compute the cross-ratio those four points would have for a candidate , and compare the two. If the candidate is right, the numbers should match. If it is wrong, they won’t.
We can do the same thing on the other three sides of the top-left finder: the right side of the top-left and bottom-left finders, the top side of the top-left and top-right finders, and the bottom side of the top-left and top-right finders. That gives us four separate measurements. We could add more if we had the inner corners of the finder patterns or the alignment patterns, but the ray fit only gives us the outer corners, and four is plenty.
In other words, the four lines are just the four sides of the top-left finder, extended until they hit the other two finders. All four lines use the same four positions, so they all share the same expected cross-ratio for a given .
For each candidate version we compute the error
where the median runs over the four constraints. The median keeps one bad line from dominating. We then pick the version with the smallest error. We still loop over all forty versions, but each iteration is just a few arithmetic operations on four numbers, so the whole ranking costs almost nothing compared with sampling and decoding.
In practice this works well. We keep the runner-up around just to avoid small errors, but usually we don’t need it.
The figure below shows the four lines on a real photo, with the measured cross-ratios next to the lines and the expected value for version 10.
Estimating the homography
By now we have a triplet and a version. The next problem is to find the mapping between the QR code in the photo and the ideal QR grid. That is a homography problem.
A homography is a projective transformation between two planes. It is more general than an affine transformation: affine is the special case where the bottom row of the matrix is . The extra two parameters let the plane tilt, which is what happens when you photograph a flat QR code from an angle. We can write it as a matrix . If is a point on the ideal QR grid, its image in the photo is
The matrix is defined up to an overall scale, so it has eight independent entries; we set .
To find the homography we need point correspondences between the two planes: the photo and the ideal QR code. We already have a natural set: the twelve outer corners of the three finder patterns. Once we know the version, we know where those corners sit on the ideal grid. The top-left finder is the square at the origin, the top-right finder is the same square shifted modules to the right, and the bottom-left finder is shifted modules down. That gives us twelve correspondences between ideal grid points and detected image points.
We want the homography that maps the twelve grid corners as close as possible to the twelve detected corners. The cost is the reprojection error:
where is an ideal grid corner and is the corresponding detected corner. The division in the formula makes this nonlinear in the entries of , so we cannot solve it in one step. We first solve a linearized version of the problem to get an initial guess, and then refine it with a standard nonlinear optimizer — Levenberg-Marquardt in this case — starting from that guess.
Once we have , mapping the ideal grid into the photo is just a matter of plugging points into the formula. That is what the sampling step uses, and it is also how we produce the rectified view on the right of the figure. The bottom-left inset zooms in on the top-left finder pattern so you can see the actual residual at true scale, and the close-up beside it isolates the finder’s bottom-left corner, where the offset is largest. In principle we could stop here and start sampling. But ideally we would use a few more landmarks to get a better homography estimate.
Finding the alignment patterns
With only the twelve finder corners, the homography is pretty good. But it is constrained at three corners and extrapolated at the fourth, and on the harder photos that extrapolation is not good enough. That is where the alignment patterns come in.
From version 2 onward, QR codes also contain alignment patterns: the small 5×5 squares in the interior. They are there exactly to make the alignment easier. If we only use the three finder patterns, the bottom-right corner is the obvious weak spot, but at high versions the modules are small enough that the whole grid can drift. The alignment patterns give us more landmarks spread across the code.
They also look different from the finder patterns. A finder pattern has a 1:1:3:1:1 ratio, while an alignment pattern has a 1:1:1:1:1 ratio. We could run the same ray-profile fit on them, but it is slower and the weaker profile makes it a poor fit. We do not need to: the homography from the finder corners is already a good prior for where each alignment pattern should be. We just need to search a small window around that prediction.
The search is template matching. We render what the pattern should look like at the local scale predicted by the homography — a dark center, a white ring, a dark border, plus a white quiet ring — and slide it over the image one pixel at a time. At each shift we compute the Pearson correlation between the template and the image patch. The shift with the highest correlation is the best match.
The GIF below shows the template sliding across a real capture. The right panel is the correlation surface, and the peak is the match.
You might look at that GIF and wonder why we could not do the same thing for the finder patterns. The reason is that we do not just need to know where a finder pattern is: we need to know where its corners are, since those are the landmarks the homography is built from, and a template match only gives us the center. There is a second problem. For an alignment pattern we know its size almost exactly, because the homography predicts the local module scale before we search, so one template is enough. For a finder pattern we would have to try many sizes and rotations, and we could not use the homography to narrow them down, because the finder patterns are what we need in order to build the homography in the first place.
The peak of the correlation surface is at integer pixel coordinates, and one pixel can be a lot in a small QR code. So we refine it with a quadratic fit: take the correlation values immediately left, right, above, and below the peak, fit a 1-D parabola in each direction, and use the vertex as the sub-pixel center.
The figure below shows the two parabolas through the peak.
The correlation at every shift sounds expensive, but it is a convolution, so we can compute it with FFTs. The whole search costs a millisecond or two per image. Once we have the centers, we add them to the twelve finder corners and refit the homography the same way. The extra points are spread across the symbol, so the fit is no longer extrapolating the fourth corner from three. If the search fails, we keep the twelve-corner homography.
On most photos this makes no difference; the twelve corners were already good enough. But on the harder ones it can be the difference between a decode and a failure. That is not a huge win, but it is a real one, and it is why the pipeline keeps the alignment patterns.
Sampling the modules
The homography gives us a map from the ideal QR grid to the photo. Sampling is then almost trivial: for each module, map its center through the homography and read the pixel. But one pixel is fragile. A speck of noise, a bit of blur, or a small error in the homography can flip it.
So we take nine samples per module instead, at 25%, 50%, and 75% across the module in each direction. The points are projected through the homography and read with bilinear interpolation. The center sample counts double, and the other eight count once.
The nine values still need a threshold. We do not reuse the global Otsu threshold from the start. That threshold was chosen for the whole image, and the QR code may be only a small part of it; the code’s black and white levels can sit somewhere else. But we do know some modules for certain: the finder patterns have a fixed pattern of black and white modules. We sample the centers of those known modules, take the median of the black values and the median of the white values, and use the midpoint as the threshold. The median ignores a few bad samples.
This gives us a single threshold for the whole code. It’s usually good enough, though it doesn’t account for changes in lighting across the code.
With the threshold, the vote is simple. Each of the nine samples is either above or below it, and we call the module white when the weighted vote is at least five out of ten. A single bad sample cannot outvote the rest. And because the nine points sit in the middle half of the module, a slightly misplaced grid does not pull in the neighboring module.
The figure below zooms in on a real capture. In one module, the center pixel lands on the wrong side of the threshold, but the nine-sample vote gets it right.
We could instead warp the whole image to a clean grid and average each cell. That would be exact, but it is slower, and sampling is already one of the more expensive steps in the pipeline.
The result is an grid of bits, and that is what the decoder consumes.
Decoding
I am going to be honest: I did not care about this part. The decoder is a port of zxing-cpp’s decoder. I told the agent to use their source as reference and make a basic implementation, not the full spec. I did not guide it, I did not check it, and I am not going to explain it. The hard parts are hard, and I do not understand them. Credit for those goes to zxing-cpp; I just wanted the bits to turn into text. It skips parts of the spec, and it still decodes every QR code I have thrown at it in daily life. I would not touch an algorithm like this with a 10-meter fierljeppen pole.
Test data
The first thing I did in this project, before I had written any decoding code, was generate a single QR image. I wrote most of that generator myself. It took a clean QR code, applied a perspective transform (which includes rotation), added noise, and blurred it. At first it was one fixed image, generated from a fixed seed. Later it grew into a small dataset across versions and difficulty levels.
This was a good starting point because the way I like to develop this is to keep the failure modes in mind at every step. A real photo is never a straight-on QR code; it is rotated, perspective-distorted, noisy, and blurred. If we can reproduce those problems in a synthetic image, we can stress-test a stage before there is any real data. A blank background is not very realistic, though, so the next step was to composite the QR patches onto photos of indoor scenes. That added a bit more: now the background and the foreground can have different lighting and brightness.
Once the pipeline was drafted, it was time to find out how good it actually was, and the synthetic sets did not cut it anymore. So I printed 15 QR codes — five versions, three physical sizes — and spent about an hour taking 100 photos of them. They all encode rikvoorhaar.com, so no annotation was needed: if the reader returns that string, the whole pipeline worked. This set is a different problem from the synthetic ones. It is more realistic, but the ground truth is worse.
The figure below shows one example from each, all version 3.
With the synthetic images we know the exact corner coordinates, and the coordinates of every other landmark, which means we can measure the corner error in pixels and benchmark the corner finder and the homography on their own, not just the final decode. With the captured set the only ground truth is the payload, and annotating every corner by hand is exactly the kind of work I wanted to avoid. So the two sets do different jobs, and I used both.
Results
One thing you might wonder at this point is whether any of this is actually good. The answer is mixed.
Running the three implementations on the same 100 captured photos gives this. The timing is the median total over three runs, with the images already loaded into memory and each reader using one thread.
| This project (Python) | OpenCV | zxing-cpp | |
|---|---|---|---|
| Correct payload | 66/100 | 48/100 | 77/100 |
| Median time for 100 photos | 6.31 s | 7.22 s | 0.39 s |
What is encouraging is that my implementation, even though it is not super optimized and not in a compiled language, is both faster and more accurate than OpenCV. And it does that without using OpenCV in the reader itself. I did use OpenCV for testing and for this comparison, but not to find or decode the QR codes. That is a real result. On the other hand, zxing-cpp is a genuinely good implementation, so comparing to it makes sense. It still beats mine on both accuracy and speed. We are nowhere near as good.
That is humbling. Beating OpenCV is an achievement, but it is not close to being useful in practice next to a dedicated QR library. And that is okay; this is a hobby project. A fair conclusion is that we made something that is not crap. It is not terrible, it is not great. I’ll take pride in that.
Where the pipeline breaks
That was a lot of steps. The figure below recaps the pipeline and shows how many of the 100 captured photos make it through each part without resizing the image. To find a triplet, we need at least three candidate clusters and three fitted finders, so the figure counts images with fewer than three as lost at those stages.
There are losses at several points:
- Finding candidates: 5 images have no candidates at all. The scan didn’t find anything that looked like a finder pattern.
- Clustering: 12 more have fewer than three candidate clusters. There may simply not have been candidates for all three finders to begin with.
- Fitting finders: 2 more have at least three clusters, but fewer than three fitted finders.
- Finding triplets: 9 more have at least three finders, but no valid triplet was found. There might not have been a valid triplet among them, or the algorithm might have missed it.
- Decoding: 9 more don’t produce the correct payload. That doesn’t necessarily mean the decoder itself is the problem: the triplet or finder corners could be wrong, or the homography could be inaccurate, leaving us sampling the wrong bits.
These numbers tell us where the images drop out, but not exactly what went wrong. For that, we’d have to look at the images in more detail.
Without resizing, we decode 63 photos. If decoding fails and we found exactly two finder patterns, we enlarge the image by 25% and run the pipeline again. That recovers three more photos, bringing the total to 66.
Final thoughts
This was a lot more complicated than I expected, but figuring it out was a fun puzzle. QR codes have been around since 1994, and it’s a bit humbling how much there is to learn just by trying to read one. Many of the ideas I came across or rediscovered along the way have been around for a long time.
I finished a preliminary version of the code months ago, but kept putting off this post because it was such a large task. I think I spent more time writing it than on the initial implementation. On the other hand, writing it helped me understand the algorithm better, and I made quite a few improvements along the way.
I even finished two other side projects between writing the code and finishing this post. Hopefully the next one will be a bit smaller.
Keep reading
18th of October, 2026
Generating a book-specific Danish dictionary from an EPUB and installing it on a Kobo e-reader.
15th of January, 2025
I made an array programming language as a language extension to Rust
31st of May, 2021
Finally, let's look at how we can automatically sharpen images, without knowing how they were blurred in the first place.
2nd of May, 2021
Deconvolving and sharpening images is actually pretty tricky. Let's have a look at some more advanced methods for deconvolution.
9th of April, 2021
In order to automatically sharpen images, we need to first understand how a computer can judge how 'natural' an image looks.
13th of March, 2021
Deconvolution is one of the cornerstones of image processing. Let's take a look at how it works.
29th of October, 2026
I made an algorithm for 3D printing mathematical shapes. Here's how I did it.
1st of August, 2024
Self-hosting your own cloud services not only saves money, it is also a great way to learn
7th of October, 2023
In my first dive into Rust, I implemented an unscented Kalman filter in and made it 20x faster than the equivalent Python implementation.
1st of May, 2023
I made an interactive dashboard for this website, and here is the story of how I did it.
26th of February, 2023
Read this blog post if you're curious what I worked on during my PhD!
29th of March, 2022
Linear least-squares system pop up everywhere, and there are many fast way to solve them. We'll be looking at one such way: GMRES.
10th of March, 2022
We recently made a paper about supervised machine learning using tensors, here's the gist of how this works.
26th of September, 2021
A lot of data is naturally of 'low rank'. I will explain what this means, and how to exploit this fact.
29th of August, 2021
Parsing and editing Word documents automatically can be extremely useful, but doing it in Python is not that straightforward.
13th of February, 2021
I have 15 years worth of email traffic data, let's take a closer look and discover some fascinating patterns.
9th of November, 2020
We use exams to determine how much a student knows, but exams aren't perfect. How can we estimate the uncertainty in students' exams scores?
26th of August, 2020
Cross validation is extremely important, but how should we choose the size of our validation and test sets?
12th of August, 2020
I use last.fm to track my music listening. Let's look at my data to discover how my musical preferences evolve over time.
10th of August, 2020
Normally distributed data is great, but how do you know whether your data is normally distributed?
20th of June, 2020
Judging in figure skating is biased. Let's use data science to figure out just how bad the issue is.