Advertisement
Abhisek92

split_by_size.py

Aug 23rd, 2022 (edited)
991
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. import rasterio as rio
  2. from pathlib import Path
  3. from rasterio.windows import Window
  4.  
  5. src_path = Path("")
  6. dst_dir = Path("")
  7. tile_lengths = (1, 1)
  8.  
  9. with rio.open(src_path, 'r') as src:
  10.     meta = src.meta.copy()
  11.     tile_height, tile_width = (np.array(tile_lengths) / np.array(src.res)).tolist()
  12.     total_window = Window(0, 0, src.height, src.width)
  13.     x0, y0 = np.meshgrid(
  14.         np.arange(0, src.height, tile_height),
  15.         np.arange(0, src.width, tile_width)
  16.     )
  17.     x0, y0 = x0.ravel().tolist(), y0.ravel().tolist()
  18.     for xa, ya in zip(x0, y0):
  19.         dst_path = dst_dir / f"{src_path.stem}_{xa}_{ya}{src_path.suffix}"
  20.         w = Window(xa, ya, tile_height, tile_width).intersection(total_window)
  21.         arr = src.read(window=w)
  22.         meta['count'], meta['height'], meta['width'] = arr.shape
  23.         meta['transform'] = src.window_transform(w)
  24.         with rio.open(dst_path, 'w', **meta) as dst:
  25.             dst.write(arr)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement