Skip to content

Instantly share code, notes, and snippets.

@br0nstein
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save br0nstein/9106701 to your computer and use it in GitHub Desktop.
Save br0nstein/9106701 to your computer and use it in GitHub Desktop.
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