gen_tiles.py 1.5 KB

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