Skip to content

Instantly share code, notes, and snippets.

@carderne
Created February 14, 2022 15:52
Show Gist options
  • Save carderne/0048bf6f96b75ce56319d342771ae97a to your computer and use it in GitHub Desktop.
Save carderne/0048bf6f96b75ce56319d342771ae97a to your computer and use it in GitHub Desktop.
Run as follows: `python clip_to_same.py source.tif raster_with_desired_shape.tif outputfile.tif`
import sys
import numpy as np
import rasterio as rio
from rasterio.warp import reproject, Resampling
def make_same(src_path: str, like_path: str, out_path: str) -> None:
with rio.open(like_path) as ds:
like_arr = ds.read(1)
like_aff = ds.transform
like_crs = ds.crs
with rio.open(src_path) as ds:
src_arr = ds.read(1)
src_aff = ds.transform
src_crs = ds.crs
dest_arr = np.empty_like(like_arr, dtype=src_arr.dtype)
with rio.Env():
reproject(
source=src_arr,
destination=dest_arr,
src_transform=src_aff,
dst_transform=like_aff,
src_crs=src_crs,
dst_crs=like_crs,
resampling=Resampling.nearest,
)
with rio.open(
out_path,
"w",
driver="GTiff",
count=1,
width=dest_arr.shape[0],
height=dest_arr.shape[1],
transform=like_aff,
crs=like_crs,
dtype=dest_arr.dtype,
) as ds:
ds.write(dest_arr, indexes=1)
if __name__ == "__main__":
src_path = sys.argv[1]
like_path = sys.argv[2]
out_path = sys.argv[3]
make_same(src_path, like_path, out_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment