Calculating the position of QR Code alignment patterns

前端 未结 5 1542
陌清茗
陌清茗 2021-01-13 05:25

I need to know how to calculate the positions of the QR Code alignment patterns as defined in the table of ISO/IEC 18004:2000 Annex E.

I don\'t understand how it\'s

5条回答
  •  萌比男神i
    2021-01-13 06:06

    Here's a Python solution which is basically equivalent to the C# solution posted by @jgosar, except that it corrects a deviation from the thonky.com table for version 32 (that other solution reports 110 for the second last position, whereas the linked table says 112):

    def get_alignment_positions(version):
        positions = []
        if version > 1:
            n_patterns = version // 7 + 2
            first_pos = 6
            positions.append(first_pos)
            matrix_width = 17 + 4 * version
            last_pos = matrix_width - 1 - first_pos
            second_last_pos = (
                (first_pos + last_pos * (n_patterns - 2)  # Interpolate end points to get point
                + (n_patterns - 1) // 2)                  # Round to nearest int by adding half
                                                          # of divisor before division
                // (n_patterns - 1)                       # Floor-divide by number of intervals
                                                          # to complete interpolation
                ) & -2                                    # Round down to even integer
            pos_step = last_pos - second_last_pos
            second_pos = last_pos - (n_patterns - 2) * pos_step
            positions.extend(range(second_pos, last_pos + 1, pos_step))
        return positions
    

    The correction consists of first rounding the second last position (up or down) to the nearest integer and then rounding down to the nearest even integer (instead of directly rounding down to the nearest even integer).

    Disclaimer: Like @jgosar, I don't know whether the thonky.com table is correct (I'm not going to buy the spec to find out). I've simply verified (by pasting the table into a suitable wrapper around the above function) that my solution matches that table in its current version.

提交回复
热议问题