Skip to content

Instantly share code, notes, and snippets.

@nonZero
Created May 23, 2016 09:27
Show Gist options
  • Save nonZero/851d49a307794a6bc78a865fbe0639c6 to your computer and use it in GitHub Desktop.
Save nonZero/851d49a307794a6bc78a865fbe0639c6 to your computer and use it in GitHub Desktop.
pillow + argparse example
#!/usr/bin/env python3
import random
from PIL import Image
def main(source, target, cols, rows):
im = Image.open(source)
print("Original image size: {}x{}".format(*im.size))
w, h = im.size
# If the image size does not divide by (COLS, ROWS), resize it a bit.
# This leaves us with integers and not subpixels...
if w % cols or h % rows:
w, h = w // cols * cols, h // rows * rows
print("Resizing to {}x{}".format(w, h))
im.resize((w, h))
# piece sizes
dx, dy = w // cols, h // rows
def pos(x, y):
"""Returns (x0, y0, x1, y1) of a piece (x, y)"""
x0 = x * dx
y0 = y * dy
return x0, y0, x0 + dx, y0 + dy
target_image = Image.new(im.mode, (w, h))
pieces = [(x, y) for y in range(rows) for x in range(cols)]
random.shuffle(pieces)
for i, piece in enumerate(pieces):
y, x = divmod(i, cols) # same as y, x = i // COLS, i % COLS
# print(pos(x, y), pos(*piece))
target_image.paste(im.crop(pos(x, y)), pos(*piece))
target_image.save(target)
print("Saving to", target)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Create a puzzle.')
parser.add_argument('source', type=str, help="source file")
parser.add_argument('target', type=str, help="target file")
parser.add_argument('--cols', type=int, default=10,
help="number of columns")
parser.add_argument('--rows', type=int, default=8, help="number of rows")
args = parser.parse_args()
main(args.source, args.target, args.cols, args.rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment