gen_tiles.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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=-1, 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. elif scale > 0:
  20. scaled_size = (orig_im.size[0] >> scale, orig_im.size[1] >> scale)
  21. im = orig_im.resize(scaled_size)
  22. else:
  23. scaled_size = (orig_im.size[0] << (-scale), orig_im.size[1] << (-scale))
  24. im = orig_im.resize(scaled_size, resample=PIL.Image.BILINEAR)
  25. for x in range(0, im.size[0], crop_x):
  26. for y in range(0, im.size[1], crop_y):
  27. geom = (x, y, min(im.size[0], x + crop_x),
  28. min(im.size[1], y + crop_y))
  29. dest = os.path.join(output_path,
  30. "{:03}-{:03}-{:03}.jpg".format(scale,
  31. x // crop_x,
  32. y // crop_y))
  33. im.crop(geom).save(dest)
  34. if __name__ == '__main__':
  35. if len(sys.argv) < 2:
  36. print("Usage: {} <image>".format(sys.argv[0]))
  37. print("Generate tiles of the given image.")
  38. exit(1)
  39. origin = sys.argv[1]
  40. out = tempfile.mkdtemp(prefix="demo-pano-")
  41. print("Generating tiles in {} ...".format(out))
  42. gen_tiles(origin, out)