|
| 1 | +from PIL import Image |
| 2 | +import itertools |
| 3 | + |
| 4 | +def get_origin(col, row, pattern_size, margin): |
| 5 | + """ produces the origin position of the pattern at the specified grid pos |
| 6 | + """ |
| 7 | + w,h = pattern_size |
| 8 | + origin = col*(w+margin), row*(h+margin) |
| 9 | + return origin |
| 10 | + |
| 11 | +def make_pattern(pixels, origin, pattern_size, ndots): |
| 12 | + """ assigns the pixels for the pattern to image data region """ |
| 13 | + w,h = pattern_size |
| 14 | + ow,oh = origin |
| 15 | + coordinates = itertools.product(range(h), range(w)) |
| 16 | + with_offset = [(c+ow, r+oh) for r,c in coordinates] |
| 17 | + # take only n dots |
| 18 | + with_offset = with_offset[:ndots] |
| 19 | + for c,r in with_offset: |
| 20 | + pixels[c, r] = 0 |
| 21 | + |
| 22 | +# calculate image size from pattern dimensions and number of patterns |
| 23 | +pattern_width, pattern_height = 10, 10 |
| 24 | +pattern_size = pattern_width, pattern_height |
| 25 | +n_cols, n_rows = 7, 10 |
| 26 | +margin = 10 |
| 27 | +image_size = (pattern_width+margin)*n_cols-margin, (pattern_height+margin)*n_rows-margin |
| 28 | + |
| 29 | +# create image |
| 30 | +img = Image.new('L', image_size, "white") # 'L' for grayscale, initialize white |
| 31 | +pixels = img.load() # create the pixel map |
| 32 | + |
| 33 | +# write image data |
| 34 | +for n_dots,rc in enumerate(itertools.product(range(n_rows), range(n_cols)), 1): |
| 35 | + r,c = rc |
| 36 | + n_dots = 100 - n_dots |
| 37 | + origin = get_origin(c, r, pattern_size, margin) |
| 38 | + make_pattern(pixels, origin, pattern_size, n_dots) |
| 39 | + |
| 40 | +img.save("test.bmp") |
0 commit comments