As an alternative to other solutions, we will construct the tiles by generating a grid of coordinates using itertools.product
. We will ignore partial tiles on the edges, only iterating through the Cartesian product between the two intervals, i.e. range(0, h-h%d, d) X range(0, w-w%d, d)
.
Given fp
: the file name to the image, d
: the tile size, opt.path
: the path to the directory containing the images, and opt.out
: is the directory where tiles will be outputted:
def tile(filename, dir_in, dir_out, d):
name, ext = os.path.splitext(filename)
img = Image.open(os.path.join(dir_in, fp))
w, h = img.size
grid = list(product(range(0, h-h%d, d), range(0, w-w%d, d)))
for i, j in grid:
box = (j, i, j+d, i+d)
out = os.path.join(dir_out, f'{name}_{i}_{j}{ext}')
img.crop(box).save(out)