gen_tiles.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # -*- coding: utf-8 -*-
  2. """
  3. Given an image, generate a set of tiles at various zoom levels.
  4. The format of the filename of times is:
  5. 00<zoom>-00<x>-00<y>.jpg
  6. where zoom is 0 for the original size, 1 when the image is downscaled 2
  7. times, 2 when the image is downscaled 4 times, etc.
  8. """
  9. from __future__ import unicode_literals, division, print_function
  10. import sys
  11. import os
  12. import tempfile
  13. import PIL.Image
  14. def gen_tiles(image, output_path, min_scale=0, max_scale=8, crop_x=256, crop_y=256):
  15. orig_im = PIL.Image.open(image)
  16. for scale in range(min_scale, max_scale + 1):
  17. if scale == 0:
  18. im = orig_im
  19. else:
  20. scaled_size = (orig_im.size[0] >> scale, orig_im.size[1] >> scale)
  21. im = orig_im.resize(scaled_size, resample=PIL.Image.BILINEAR)
  22. for x in range(0, im.size[0], crop_x):
  23. for y in range(0, im.size[1], crop_y):
  24. geom = (x, y, min(im.size[0], x + crop_x),
  25. min(im.size[1], y + crop_y))
  26. dest = os.path.join(output_path,
  27. "{}-{}-{}.jpg".format(-scale,
  28. x // crop_x,
  29. y // crop_y))
  30. tile = im.crop(geom)
  31. if x + crop_x > im.size[0] or y + crop_y > im.size[1]:
  32. # The tile is smaller than 256x256, so fill the rest with black
  33. tile = im.transform((crop_x, crop_y), PIL.Image.AFFINE, (1, 0, x, 0, 1, y))
  34. tile.save(dest)
  35. if __name__ == '__main__':
  36. if len(sys.argv) < 2:
  37. print("Usage: {} <image>".format(sys.argv[0]))
  38. print("Generate tiles of the given image.")
  39. exit(1)
  40. origin = sys.argv[1]
  41. out = tempfile.mkdtemp(prefix="demo-pano-")
  42. print("Generating tiles in {} ...".format(out))
  43. gen_tiles(origin, out)