Image Slicer

Take a large image and output smaller output slices into a directory


In [19]:
# on osx yosemite: sudo pip install http://effbot.org/media/downloads/Imaging-1.1.7.tar.gz
import Image, ImageDraw
import math
import os

img = Image.open("waldo/ww6kc.png")
outdir = "waldo/ww6kc400"
prefix = "ww6kc400"  # prefix for slice filenames (ex. "prefix_0_0.png" ) 
width, height = img.size
hopx = 350
hopy = 350
slicex = 400
slicey = 400
assert hopx <= slicex, "x: hop size (%i) should be less than slice size (%i)" % (hopx, slicex)
assert hopy <= slicey, "y: hop size (%i) should be less than slice size (%i)" % (hopy, slicey)

# 2000 x 1800 --> 2400 x 2200
num_slices_x = int(math.ceil((width  - slicex) / hopx)) + 2
num_slices_y = int(math.ceil((height - slicey) / hopy)) + 2
print "Num slices", (num_slices_x, num_slices_y), "Total", num_slices_x * num_slices_y 

#  extend the canvas of the image with white so that hopping slices divide exactly
width2  = (num_slices_x-1) * hopx + slicex
height2 = (num_slices_y-1) * hopy + slicey

""" debugging
print height, hopy, slicey, height2, num_slices_y
for y in xrange(0,height2 - slicey + hopy, hopy):
    print (y, y+slicey) 
"""
img2 = img.crop( (0,0,width2, height2) )  
draw = ImageDraw.Draw(img2)
draw.rectangle( (width,0,width2,height2), fill="white" )
draw.rectangle( (0,height,width2,height2), fill="white" )
del draw
img2.save("img2.png", "PNG")

# mkdir
!mkdir {outdir}

# Begin slicing
print "Slicing.."
for x in xrange(0,width2 - slicex + hopx, hopx):
    for y in xrange(0,height2 - slicey + hopy, hopy):
        bbox = (x, y, x+ slicex, y + slicey)
        slice = img2.crop(bbox)
        slice.save(os.path.join(outdir, prefix + "_" + str(x) + "_" + str(y) + ".png"))
print "Done."


Num slices (18, 14) Total 252
Slicing..
Done.