Why Does a Dirty, Torn QR Code Still Scan?
The QR code on a shared bike’s handlebar is often scratched or splashed with mud, yet you hold up your phone and it still beeps and unlocks. Many QR codes even have a logo printed in the middle, covering a large patch of black and white squares, and they scan just fine.
The secret is in the squares. In a typical QR code, leaving aside the fixed patterns such as the three corners, over a third of the remaining squares hold no information at all. They hold a clever kind of “backup” called error correction. Spoil a patch, and the phone can work it out again from the other squares.
From barcodes to QR codes
The barcode on a supermarket product holds its information in one direction only: a row of bars of different widths, usually just 13 digits, the product’s number. What the product is called and what it costs are looked up from that number in the checkout system. The last digit is a check digit, calculated from the first 12; misread one digit, and the check doesn’t work out. But it can only detect an error, not fix it, so the barcode has to be scanned again.
In 1992, factories at the Japanese company DENSO found barcodes no longer enough. Factory barcodes could hold letters as well as digits, but still only about 20 characters each; more information on a parts box meant using several barcodes at once, and a worker had to scan around 1,000 barcodes a day. The company’s scanner division (today’s DENSO WAVE) took this on, and the engineer Masahiro Hara and one colleague decided to design a new code. As Hara recalled, the idea came during a lunch break in early 1993, while he was playing Go: black and white stones on a grid can carry information both across and down. In 1994 the code was released. Its name, QR, stands for Quick Response. The largest QR code has 177 × 177 squares and can hold 7,089 digits.
DENSO WAVE made the specification public: using QR codes needs no application and no licensing contract, and in 2000 it became an international standard. With anyone free to make and read them, QR codes moved out of the factory into payments, train tickets, menus and business cards.
What a QR code stores is really just a string of characters, and once the phone reads it, it decides what to do from how the string looks. If it’s a web address, the phone offers to open that page; many of the codes we scan hold a web address, which is why scanning so often opens a page. If it looks like “WIFI:S:network name;T:WPA;P:password;;”, the phone offers to join that Wi-Fi network; this format isn’t part of the QR standard, but a convention that phones have come to recognize. A payment code usually holds a web address or a string of numbers too, handed over to the matching app.
So QR codes need no registration, and in themselves aren’t “unique”: the same content with the same settings makes the same code. Each shared bike has a different code because each stores a different bike number. Nor is there any danger of running out: the smallest QR code has only 21 × 21 squares and holds at most 41 digits, and there are 1041 such numbers alone. If all 8 billion people on Earth each made a new code every second, using them up would take about 4 × 1023 years, 3 × 1013 times the age of the universe (13.8 billion years); and larger codes hold far more.
All “2D codes,” but they look different
What people loosely call a “2D code” is really a whole family. The most common, the QR code, has a square-within-a-square in three of its corners; but some codes you’ve seen don’t have them.
Some are other formats. Data Matrix finds its position by a solid L-shaped border, and is often printed on electronic parts and medicine boxes; Aztec’s marker is a bullseye in the middle, used on some train tickets; PDF417 is rows of barcode stacked up, common on paper boarding passes. WeChat’s mini-program codes are round, WeChat’s own format that only WeChat can read. And some QR codes, for looks, draw the corner squares with rounded corners or the squares as little dots; the structure is the same.
The QR code has relatives of its own. Micro QR has a single corner square and goes in very small spaces; rMQR is rectangular, as narrow as 7 squares, became an international standard in 2022, and goes in long, narrow spaces. A standard QR code is always square, and comes in only 40 sizes: 21, 25, 29 and so on up to 177 squares a side, each size 4 squares bigger than the last.
A scanning program has to know a format to read it. The scanner built into a phone’s camera is mainly made for QR codes, and the codes we scan day to day are almost all QR codes. Dedicated scanning programs often know several formats, like zxing-cpp, which we used to make and check the figure above. From here on, it’s all about the most common kind, the QR code.
The squares in three corners
In a phone’s photo, a QR code may be small, tilted or upside down, surrounded by all sorts of other patterns. The first thing Hara’s team had to solve was letting a machine find it quickly.
A scanning program looks at the photo row by row. Each row of pixels is a line, black for a stretch, then white for a stretch, and it records how long each stretch is. They wanted to put a marker on the code so that a line crossing it gives a special ratio of black and white, but worried that other patterns on the paper might happen to have that ratio too. So they surveyed what was printed on fliers, magazines and cardboard boxes, and picked the ratio rarest on printed matter: black : white : black : white : black = 1 : 1 : 3 : 1 : 1. That’s the square within a square.
The finder pattern is squares nested inside one another. A line through its centre from any direction crosses it in the ratio 1:1:3:1:1, and the ratio doesn’t change with distance or size either. When the program finds this ratio along both rows and columns, it has found a corner. According to DENSO WAVE, the QR code could be read more than 10 times faster than other codes of the time.
Why only three corners? If all four had one, the code would look the same turned through 90 degrees, and the phone couldn’t tell which way is up. Leaving one corner empty settles the direction. (A code printed back to front is fine too: flip it left to right, as in a mirror, and both scanning programs we tried still read it.)
The other fixed parts each have a job. The two alternating timing patterns, like the marks on a ruler, tell the phone how many squares each row and column has; codes of version 2 and up have an alignment pattern, which helps the phone straighten a code photographed at an angle; the format information records settings such as the error-correction level; and from version 7 up, another area records the code’s size. Every standard QR code has these parts, and only the remaining squares hold data and error correction.
Every 8 squares are a number
Turning a web address into black and white squares takes these steps:
- Into bits. https://mybreathtaking.com/ has 27 characters, each one byte, that is 8 bits. In front goes a short header: “what follows is in bytes, 27 of them.”
- Eight bits at a time. Every 8 bits make a codeword, a number from 0 to 255. The code in the figure leaves room for 64 data codewords; the address and header don’t fill them, so the rest is padded with fixed numbers.
- Work out the error correction. From these 64 numbers, 36 more numbers for error correction are calculated (how, in the next section).
- Into the squares. The 100 numbers go in one after another: in two-square columns, starting at the lower right, up and down, around the fixed patterns.
- Apply a mask. Once placed, the black and white of the squares is set by the data, which can produce long runs of one colour, or even an accidental fake finder pattern that misleads the phone. So a fixed pattern is laid over it: wherever the pattern is coloured, black turns white and white turns black. The standard has 8 patterns; when making a code, each is tried, the one with the fewest large patches of one colour and finder-like shapes is chosen, and its number goes into the format information.
Scanning runs the other way: find the three corners, straighten the code, count off the squares using the timing patterns, and decide black or white; read the pattern number from the format information and flip the squares back with the same pattern, removing the mask; then read the 100 numbers, correct errors, and finally recover the string of characters.
Error correction: mathematics decades older than the QR code
The QR code’s error correction uses mathematics that already existed. The story starts in the 1940s.
The crudest way to correct errors is to send every bit three times and let the majority decide: receive 101, and take it as 1. The cost is sending twice as much again.
In 1947, Richard Hamming at Bell Labs could use a relay computer only at weekends. The machine could detect that it had made an error, but then it simply dropped the problem and moved on to the next; with no one watching at weekends, he often came back on Monday to find his problems had produced nothing. As he later recalled, his thought was: “Damn it, if the machine can detect an error, why can’t it locate the position of the error and correct it?” In 1950 he published the Hamming code, which corrects errors automatically.
The Hamming code can be drawn as three circles. The 4 data bits go where the circles overlap; 3 check bits are added, each in a part only one circle has, chosen so every circle holds an even number of 1s.
On arrival, count: if all three circles are even, there’s no error; if circles B and C have turned odd while A is still even, the error is in the part inside B and C but outside A. Each of the seven places gives a different pattern of odd and even, so whichever bit goes wrong, it can be found and fixed. The 4 data bits need only 3 extra, far fewer than sending each one three times.
A Hamming code can fix only one error per group. QR codes use the Reed–Solomon code, proposed in 1960 by Irving Reed and Gustave Solomon of MIT Lincoln Laboratory in a five-page paper, which can fix many errors per group. The idea can be seen with a curve.
Say we want to send 4 numbers: 4, 6, 5, 3. Plot them at positions 1, 3, 5 and 7, and exactly one cubic curve passes through these 4 points: 4 points fix a cubic, just as 2 points fix a straight line. Then read off this curve’s values at positions 2, 4, 6 and 8, and send 4 more numbers. In a QR code, each position is one codeword.
On the way, 2 of the numbers are spoiled. The spoiled numbers don’t vanish; they just become wrong numbers, and the receiver doesn’t know which two. But of the 8 points received, 6 are still on the original curve. Two different cubics cross at most 3 times, so any other cubic meets at most 3 of these 6 good points, and with the 2 spoiled ones passes through only 5 points. Only the original passes through 6. Find it, and the spoiled numbers are worked out again.
What if 4 are spoiled? The 4 good points left lie on the original curve, so it passes through 4 points; but the 4 spoiled points also fix a cubic, which likewise passes through 4 (the red curve in the figure). Both are equally “reasonable,” and there’s no telling which is the original. So 4 extra numbers can fix at most 2 errors: every 2 extra numbers fix 1 more error. If you know beforehand which 4 are spoiled, it’s easy: throw them away, and the 4 good points left fix the original curve exactly. Knowing where the errors are, 1 extra number restores 1.
The real Reed–Solomon code doesn’t calculate with ordinary numbers but with the 256 whole numbers from 0 to 255. Adding, subtracting, multiplying and dividing follow a special set of rules, so the result is always a whole number from 0 to 255 again: it fits exactly into 8 squares, with no rounding error. The principle that two different curves cross only a limited number of times still holds.
The 1960 paper had no fast way to decode. Only in the late 1960s did Elwyn Berlekamp and others find efficient algorithms, and then the code really came into use. The CD, launched in 1982, uses two Reed–Solomon codes interleaved with each other: a run of errors about 2.5 mm long along the track is corrected perfectly, which is why a scratched disc still plays the music. In 1986, Voyager 2 flew past Uranus, about 3 billion km from Earth, so its signals took 2 hours 45 minutes to arrive; of every 255 numbers in the image data it sent back, 32 were error correction, and each group could fix 16 errors. In 1994, the QR code took it up too.
How much can be covered and still scan?
More error correction can fix more errors, but leaves less room for data. QR codes have four error-correction levels, L, M, Q and H, which by the standard can restore roughly 7%, 15%, 25% and 30% of the codewords. In oily factories, Q or H is the usual choice; a code with a logo in the middle also needs a higher level.
We ran an experiment. For the same web address, we made one 33 × 33 code at each of the four levels, drew an opaque coffee stain right in the middle, and let it grow from nothing until it covered 30% of the code. At every step, the picture was handed to OpenCV’s QR code reader and really scanned.
The results: level L still reads at 5%, M at 8%, Q at 12% and H at 17%. Another reader, zxing-cpp, gives almost the same (4%, 8%, 12%, 18%). That’s only about half to seven tenths of the nominal values. The reason is that a stain covers area, while error correction counts codewords: a codeword is 8 squares, and a codeword at the edge of the stain with only one corner covered counts as wrong too. So while the stain’s area is still well below the nominal value, the codewords it touches already exceed what can be fixed.
Where it’s covered matters more than how much
On the same level-H code, one stain covering 10% still scans. Split the same 10% of area into small spots landing only in the data area, and in 40 random layouts we tried, it never scanned once: spots scattered here and there touch many more codewords.
Worse still are the corner squares. The three finder patterns aren’t covered by error correction: whiten just the 3 × 3 black block in the middle of one of them, less than 1% of the code’s area, and both programs fail. If the phone can’t find that corner, error correction never gets a chance. The format information is crucial too, since it tells the phone which level to correct with, so it is stored twice, in two separate places, with error correction of its own.
That’s why a logo on a QR code usually goes right in the middle, with a higher error-correction level: the middle is data area, and what’s covered is one patch.
A QR code in shadow
Dirt is only one kind of trouble. More common is uneven light: half in the sun, half in shadow.
Each pixel of a phone camera measures how much light lands on it (see How Does a Phone Take a Photo?). Brightness is the light falling on a spot times that spot’s reflectance. Assume white paper reflects 80% of the light and black ink only 5%; on a sunny day, the shadow gets only about a tenth of the light in the sun. Then paper in the sun has a brightness of 0.8, while paper in shadow has only 0.8 × 0.1 = 0.08, only a little brighter than ink in the sun (0.05).
A scanning program first has to turn the photo into pure black and white. The simplest way is one threshold for the whole photo: brighter is white, darker is black. The program sets the threshold itself, for instance at the photo’s average brightness, about 0.3 here, and all the paper in shadow turns black. To get both sides right, the threshold has to fall exactly between 0.05 and 0.08. Brightness in the photo comes as whole numbers from 0 to 255, and we tried every threshold: with a little blur and noise in the photo the gap is narrower still, and zxing-cpp scans at only 6 of them, OpenCV at none. With a deeper shadow, say a twentieth of the sunlight, paper in shadow (0.04) is darker than ink in the sun, and no threshold works at all.
But at any one spot, paper and the ink next to it get the same light, so the paper is always 0.80 / 0.05 = 16 times brighter. So scanning programs often do something else: each spot is compared only with the average brightness of a small patch around it. The light is a common factor, and the comparison cancels it out.
Our eyes see things the same way: put a sheet of white paper in shadow, and it still looks white to us.
In one line: a large share of a QR code’s squares hold no information but error correction, like the extra points read off a curve; spoil part of the code, and the phone works out the original numbers from the rest, with every 2 extra numbers fixing 1 more error. But the corner squares mustn’t be damaged: the phone needs them to find the code in the first place.
Try it yourself
- A sticky note: cover a QR code with a sticky note, starting from the middle and moving out slowly, and see how much it takes before it won’t scan. Then cover only one of the corner squares, and compare.
- Four levels: many QR code generator sites let you choose the error-correction level. Make one code at L and one at H for the same address: the H one has denser squares. This site’s address takes 25 × 25 squares at level L, and 33 × 33 at level H.
- Sun and shadow: put a QR code half in the sun and half in shadow, and see whether your phone can still scan it.
What we don’t know yet
The Reed–Solomon code is already the “most economical” kind: 2 extra numbers per error fixed, and it’s proven that no code can do better. But it has a limit: a block can’t hold too many numbers. Each codeword in a QR code takes one of only 256 values, and a Reed–Solomon block then holds at most 255 numbers; QR codes, CDs and Voyager all stay within that length. Mathematically it can be extended to 257.
So is there some other code, just as economical, whose blocks can be longer? Mathematicians conjecture that, apart from a very few known special cases, there isn’t: 257 is the end. This is the “MDS conjecture” (MDS is the technical name for these most economical codes), which grew out of a question in finite geometry posed by the Italian mathematician Beniamino Segre in 1955. In 2012, Simeon Ball proved it holds when the number of values is a prime (251, say). But 256 isn’t a prime, and the case QR codes use is still unproven.
Going further: numbers, formulas and sources
Codewords and error-correction levels. The figures show a version 4 QR code, 33 × 33 squares (modules). Taking away the finder, timing and alignment patterns and the format information leaves 807 modules, which hold 100 codewords (800 modules) and 7 spare bits. The data / error-correction codewords at the four levels are: L 80 / 20 (1 block), M 64 / 36 (2 blocks of 32 + 18), Q 48 / 52 (2 blocks of 24 + 26), H 36 / 64 (4 blocks of 9 + 16). A block can fix half as many codewords as it has error-correction codewords: L 10, M 9 per block, Q 13 per block, H 8 per block, i.e. 10%, 18%, 26% and 32% of the codewords in a block. The codewords of the blocks are interleaved, so a stain is shared among them. The standard’s 7%, 15%, 25% and 30% summarize all versions. Version is modules a side. The largest, version 40 at level L, holds 7,089 digits or 2,953 bytes.
How the codewords are laid out. The data are first written as a bit string: mode 0100 (bytes), the length 27 in 8 bits, then the 27 bytes, followed by a terminator and the pad bytes 236 and 17 in turn, to fill 64 codewords. Codewords run in two-module columns from the lower right, alternately upward and downward, skipping the fixed patterns (the whole column 6 of the timing pattern is skipped). The labels in figure 3 were checked this way: reading all the modules in this order and removing the mask (here number 4: modules where is even are flipped) gives 100 codewords; split into the two interleaved blocks, each passes the Reed–Solomon check (all syndromes zero), and the data part decodes to this very address.
The Hamming code. The usual way to write it numbers the 7 places 1 to 7, puts check bits at 1, 2 and 4, and makes check bit cover all places whose number has binary digit equal to 1; on arrival, the checks are redone, and the numbers of the failed checks add up to the position of the error. The three circles show the same thing: each circle is the range one check bit covers.
The curve example. The cubic through (1, 4), (3, 6), (5, 5), (7, 3) is ; its values at are 5.5, 5.75, 4 and 2.25. In the middle panel, the 6 at is changed to 1.6 and the 4 at to 7.6; fitting a cubic through every choice of 4 of the 8 received points, only the original passes through at least 6. In the bottom panel, the values at are replaced by the original curve plus ; the red curve these 4 points fix is a cubic too, and no cubic passes through more than 4 of the 8 points.
The real Reed–Solomon code. Codewords are elements of the finite field GF(256): addition is bitwise XOR, and multiplication is taken modulo the primitive polynomial . The data codewords are treated as a polynomial of degree less than , and its values at different points are sent (as in the original paper). QR codes use the equivalent “generator polynomial” form: the data polynomial is multiplied by and divided by , and the remainder gives the error-correction codewords. Two different polynomials of degree less than agree at no more than points, so as long as , the code can fix errors at unknown positions together with “erasures” at known positions. This limit is the Singleton bound, and codes that reach it are called MDS (maximum distance separable) codes. A Reed–Solomon code over GF() is at most long, and the doubly extended version . The MDS conjecture says that an MDS code over GF() with data symbols is never longer than ; the only exceptions are a power of 2 with or , which reach .
Masks and format information. There are 8 mask patterns; the encoder tries each and, by the standard’s penalty rules (large areas of one colour, patterns like a finder pattern, and so on), picks the one with the lowest penalty. Which pattern was used, plus the error-correction level, makes 5 bits; 10 bits of BCH error correction are added to give 15 bits of format information, stored twice.
Kinds of 2D code. Figure 1 was made with zxing-cpp 3.2.1, and each code was read back with it to check. QR Code ISO/IEC 18004; Micro QR 11 to 17 modules a side; rMQR (ISO/IEC 23941, 2022) from 7 × 43 to 17 × 139 modules, with the finder patterns cut from three to “one and a half”; Data Matrix ISO/IEC 16022; Aztec ISO/IEC 24778; PDF417 ISO/IEC 15438.
The stain experiment. Made with segno 1.6.6, fixed at version 4, address https://mybreathtaking.com/; 12 pixels per module, with a 4-module blank margin. The stain is an opaque disc centred on the code, colour RGB (120, 84, 48); its area is measured against the 33 × 33 code area, in steps of 1%. Decoding uses OpenCV 5.1.0’s QRCodeDetector and zxing-cpp 3.2.1; the largest stain still read is 5%, 8%, 12% and 17% with OpenCV, and 4%, 8%, 12% and 18% with zxing-cpp.
Spots and finder patterns. The spots are about 2 modules across, placed at random in the data area (away from the finder, timing and alignment patterns and the format information) until they cover 10% of the code area; in 40 random layouts, neither program read the code once, while both read it with one stain of the same area. Whitening only the 3 × 3 black block in the middle of the upper-left finder pattern (0.8% of the code area), or the whole finder pattern (4.5%), makes all four levels fail. Flipping the code across its diagonal (a mirror image), both programs still read it.
The shadow. Reflectance: paper 0.80, ink 0.05; the shadow gets 0.10 of the light in the sun (direct sunlight on a clear day is about 100,000 lux, shade about 10,000 lux), with a soft edge, plus perspective distortion, slight blur and noise. The middle panel’s threshold is the mean brightness of the whole image (96, with brightness on a 0 to 255 scale and paper in the sun at 255). Every global threshold from 0 to 254 was tried (brighter than the threshold counts as white): OpenCV reads none; zxing-cpp reads only 18 to 23, right between ink in the sun (about 16) and paper in shadow (about 25). With the shadow at 1/20 of the sunlight, neither program reads it at any global threshold. The right panel uses OpenCV’s adaptiveThreshold, comparing each spot with the mean brightness of the surrounding 51 × 51 pixels minus 5 (brightness on a 0 to 255 scale). zxing-cpp’s two binarizers agree: one threshold for the whole image (GlobalHistogram) fails, the local average (LocalAverage) reads it.
The CD and Voyager. The CD’s cross-interleaved Reed–Solomon code (CIRC) is made of two codes, (32, 28) and (28, 24). It fully corrects bursts of about 4,000 bits (about 2.5 mm of track) and conceals about 12,000 bits (about 7.5 mm) by interpolation. From Uranus on, Voyager used a (255, 223) Reed–Solomon outer code together with a (7, 1/2) convolutional code.
Sources. DENSO WAVE, History of QR Code, FAQ and rMQR Code (qrcode.com); DENSO WAVE, QR Code development story. D. Pogue, The Man Who Invented QR Codes, Unsung Science (2023, interview with Masahiro Hara). ISO/IEC 18004 (the QR code standard). R. W. Hamming, Bell System Technical Journal 29, 147 (1950); T. M. Thompson, From Error-Correcting Codes Through Sphere Packings to Simple Groups (1983; Hamming’s recollection is quoted from it). I. S. Reed and G. Solomon, J. SIAM 8, 300 (1960). E. R. Berlekamp, Algebraic Coding Theory (1968). K. A. S. Immink, Reed–Solomon Codes and the Compact Disc, in S. B. Wicker and V. K. Bhargava (eds.), Reed–Solomon Codes and Their Applications (1994). R. J. McEliece and L. Swanson, Reed–Solomon Codes and the Exploration of the Solar System (ibid.). B. Segre, Annali di Matematica 39, 357 (1955). S. Ball, J. Eur. Math. Soc. 14, 733 (2012).