Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Script to generate a series of crops of a source image
import Image
import random
def dice_image(input_image, width, height, num_pics):
"""
Dice_image creates num_pics images from a source image. It passes
a window of specified size over the image, crops and
exports new images.
Inputs:
input_image - filename of the PNG image to dice up (in local directory)
width - width of each resulting cropped image
height - height of each resulting cropped image
num_pics - number of thumbnails to create
"""
input_img = Image.open(input_image)
source_width, source_height = input_img.size
start_x, start_y = 0, 0
iteration, pic_num = 1, 1
max_crops = (source_width / width) * (source_height / height)
# Set of window IDs to crop, ignore the rest
try:
crops = set(random.sample(range(1, max_crops + 1), num_pics))
except ValueError:
crops = set(range(1, max_crops + 1))
for start_x in range(0, source_width - width + 1, width):
for start_y in range(0, source_height - height + 1, height):
if iteration in crops:
box = (start_x, start_y, start_x + width, start_y + height)
output_img = input_img.crop(box)
# Strip .png extension, append unique ID
output_img.save(input_image[:-4] + "_" + str(pic_num) + ".png")
pic_num += 1
iteration += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment