Skip to content

Instantly share code, notes, and snippets.

@shanedoolane
Forked from decrispell/crop_geotiff.py
Created November 5, 2022 05:29
Show Gist options
  • Save shanedoolane/7d74b7742c46b6d95c92aebcc03fbae4 to your computer and use it in GitHub Desktop.
Save shanedoolane/7d74b7742c46b6d95c92aebcc03fbae4 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]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment