What masking does
After the data and error correction bits are placed, some areas may end up with long runs of one color or shapes that look like finder patterns. Masking fixes this by flipping modules wherever a simple formula is true, which spreads dark and light more evenly.
The mask applies only to the data and error correction area. Finder, timing and alignment patterns, the format and version information, and the dark module are never masked.
The eight masks
Masks are numbered 000 to 111. Each is defined by a condition on the row i and column j of a module; where the condition holds, that module is flipped. A reader learns the mask number from the format information and applies the same mask again to undo it.
- 000: (i + j) mod 2 = 0, a checkerboard
- 001: i mod 2 = 0, alternating rows
- 010: j mod 3 = 0, every third column
- 011: (i + j) mod 3 = 0, diagonal stripes
- 100 to 111: more complex combinations of rows, columns and products
How the best mask is chosen
The encoder tries all eight masks and scores each result with four penalty rules. The mask with the lowest total penalty is used, which makes the finished code easier for cameras to read.
Some generators skip the full evaluation and use a fixed mask, which still produces a valid code but may be slightly harder to scan. Micro QR codes use a smaller set of four masks with their own scoring rule.
- Rule 1: long runs of the same color in a row or column
- Rule 2: 2 × 2 blocks of one color
- Rule 3: patterns that resemble the 1:1:3:1:1 finder ratio
- Rule 4: overall imbalance between dark and light modules