TheBird

qrcode.py

1.5 kB · python · 53 lines

1import mrlypy.two as m22from mrlypy.core.colors import black, white3import numpy as np4from config import DATA_DIR56string = "Hello, World!"78def str_to_bits(s: str) -> np.ndarray:9    result = []10    for char in s:11        bits = bin(ord(char))[2:]12        bits = bits.zfill(8)13        result.extend([int(b) for b in bits])14    return np.array(result, dtype=np.uint8)1516def embed_data(cell: m2.Cell2d, bits: np.ndarray) -> m2.Cell2d:17    indices = np.where(cell.types == 1)18    capacity = len(indices[0])19    if len(bits) > capacity:20        print(f"Warning: Message truncated. Capacity: {capacity}, Message: {len(bits)}")21        bits = bits[:capacity]22    if len(bits) < capacity:23        repeats = capacity // len(bits) + 124        bits = np.tile(bits, repeats)[:capacity]25    cell.types[indices] = bits26    return cell2728def main():29    number = 330    level = 231    tile_0 = m2.carpet_2d(number, level)32    tile_1 = m2.tree_2d(number, level).rotate(90)33    tile_2 = m2.tree_2d(number, level)34    tile_3 = m2.carpet_2d(number, level).copy()35    bits = str_to_bits(string)36    tile_3 = embed_data(tile_3, bits)37    mask = np.array([38        [0, 1, 1, 1, 0],39        [2, 3, 3, 3, 2],40        [2, 3, 3, 3, 2],41        [2, 3, 3, 3, 2],42        [0, 1, 1, 1, 0]43    ], dtype=np.uint8)44    cells = [tile_0, tile_1, tile_2, tile_3]45    qr_cell = m2.mosaic_2d(mask, cells)46    qr_cell = qr_cell.paint({0: [white], 1: [black]})47    fp = f"{DATA_DIR}/qrcode.png"48    image = qr_cell.to_image(scale=10) 49    image.save(fp)50    print(f"Saved: {fp}")5152if __name__ == "__main__":53    main()