Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. # Example licensed under cc by-sa 3.0 with attribution required
  2.  
  3. from contextlib import contextmanager
  4.  
  5. import rasterio
  6. from rasterio import Affine, MemoryFile
  7. from rasterio.enums import Resampling
  8.  
  9. # use context manager so DatasetReader and MemoryFile get cleaned up automatically
  10. @contextmanager
  11. def resample_raster(raster, scale=2):
  12. t = raster.transform
  13.  
  14. # rescale the metadata
  15. transform = Affine(t.a / scale, t.b, t.c, t.d, t.e / scale, t.f)
  16. height = raster.height * scale
  17. width = raster.width * scale
  18.  
  19. profile = src.profile
  20. profile.update(transform=transform, driver='GTiff', height=height, width=width)
  21.  
  22. data = raster.read( # Note changed order of indexes, arrays are band, row, col order not row, col, band
  23. out_shape=(raster.count, height, width),
  24. resampling=Resampling.bilinear,
  25. )
  26.  
  27. with MemoryFile() as memfile:
  28. with memfile.open(**profile) as dataset: # Open as DatasetWriter
  29. dataset.write(data)
  30. del data
  31.  
  32. with memfile.open() as dataset: # Reopen as DatasetReader
  33. yield dataset # Note yield not return
  34.  
  35.  
  36. with rasterio.open('path/to/raster') as src:
  37. with resample_raster(src) as resampled:
  38. print('Orig dims: {}, New dims: {}'.format(src.shape, resampled.shape))
  39. print(repr(resampled))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement