Skip to content

Instantly share code, notes, and snippets.

@decrispell
Last active January 7, 2023 15:56
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save decrispell/9a071620ce066de27d04933d9eb50ea9 to your computer and use it in GitHub Desktop.
Save decrispell/9a071620ce066de27d04933d9eb50ea9 to your computer and use it in GitHub Desktop.
quick and dirty geotiff crop using rasterio
import rasterio
# load the geotiff (a DSM in this case) and read the data - only one index in this case
dsm = rasterio.open(dsm_fname)
dsm_data = dsm.read()[0]
# crop the data
dsm_crop = dsm_data[min_y:min_y+height, min_x:min_x+width]
# make a copy of the geotiff metadata
new_meta = dsm.meta.copy()
# create a translation transform to shift the pixel coordinates
crop = rasterio.Affine.translation(min_x, min_y)
# prepend the pixel translation to the original geotiff transform
new_xform = dsm.transform * crop
# update the geotiff metadata with the new dimensions and transform
new_meta['width'] = width
new_meta['height'] = height
new_meta['transform'] = new_xform
# write the cropped geotiff to disk
with rasterio.open(output_filename, "w", **new_meta) as dest:
dest.write(dsm_crop.reshape(1,dsm_crop.shape[0], dsm_crop.shape[1]))
@shanedoolane
Copy link

works well. thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment