python切图

书途 238 0
Python
  1. # importing functions
  2. import sys
  3. import os
  4. import math
  5. from PIL import Image
  6. from tqdm import tqdm
  7. # source path
  8. img_path = r"C:\Users\Shen\PycharmProjects\pythonProject\0-TileGroup抓图法\魁星图.jpg"
  9. # output tile directory
  10. tile_path = 'tiles'
  11. # tile size
  12. tile_size = 256
  13. Image.MAX_IMAGE_PIXELS = None # 禁用解压缩炸弹限制
  14.  
  15.  
  16. def adjustImage(src_img): # ajust image size to tile size
  17. # get image size
  18. img_w, img_h = src_img.size
  19. # calculate tilable img size
  20. out_w = img_w + (tile_size - img_w % tile_size)
  21. out_h = img_h + (tile_size - img_h % tile_size)
  22. # create transparent extra background
  23. out_img = Image.new('RGBA', (out_w, out_h))
  24. # combine src image and background
  25. out_img.paste(src_img, (0,0))
  26. return out_img
  27.  
  28.  
  29. img = Image.open(img_path)
  30. w, h = img.size[0], img.size[1]
  31.  
  32. # calculate max zoom level
  33. max_zoom = int(math.ceil(math.log((max(w, h) / tile_size), 2)))
  34. # main loop for all zoom levels
  35. for z in tqdm(range(max_zoom, -1, -1)):
  36. # adjusting image
  37. adj_img = adjustImage(img)
  38. # calculating number of rows and columns of tiles
  39. n_cols = int(adj_img.size[0] / tile_size)
  40. n_rows = int(adj_img.size[1] / tile_size)
  41. # print(n_cols,n_rows)
  42. # loop for creating directories and tiles
  43. for x in range(n_cols):
  44. # create z/x directory
  45. path = os.path.join(tile_path, str(z), str(x))
  46. if not os.path.isdir(path):
  47. os.makedirs(path)
  48. # cut tiles
  49. for y in range(n_rows):
  50. bounds = (x * tile_size, y * tile_size, (x + 1) * tile_size, (y + 1) * tile_size)
  51. tile = adj_img.crop(bounds)
  52. print(x,y,z)
  53. tile.save('%s/%s.png' % (path, y))
  54. # resize image - go to next zoom level
  55. w, h = img.size[0], img.size[1]
  56. img = img.resize((int(w/2), int(h/2)), Image.ANTIALIAS)
复制 文本 高亮
(Visited 90 times, 1 visits today)

发表评论 取消回复
表情 图片 链接 代码

分享