gen_tiles.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. "{:03}-{:03}-{:03}.jpg".format(scale,
  28. x // crop_x,
  29. y // crop_y))
  30. im.crop(geom).save(dest)
  31. if __name__ == '__main__':
  32. if len(sys.argv) < 2:
  33. print("Usage: {} <image>".format(sys.argv[0]))
  34. print("Generate tiles of the given image.")
  35. exit(1)
  36. origin = sys.argv[1]
  37. out = tempfile.mkdtemp(prefix="demo-pano-")
  38. print("Generating tiles in {} ...".format(out))
  39. gen_tiles(origin, out)