I'm trying to do a simple center crop of as square geotiff using rasterio.
I crop the image using numpy, which works as expected, then update the image profile's height and width.
I also update the affine transform using src.window_transform
, but I am doing something wrong. The affine transform ends up being incorrect.
My code is below. Can anyone tell me where I am messing up? Thanks.
import rasterio as rio
#
# FUNCTIONS
#
def get_image_and_profile(path):
with rio.open(path) as src:
profile=src.profile
image=src.read()
return image, profile
def image_write(im,path,profile):
with rio.open(path,'w',**profile) as dst:
dst.write(im)
def crop_image(image,crp):
return image[:,crp:-crp,crp:-crp]
def crop_profile(profile,out_size,crp):
win=(
(crp,out_size+crp),
(crp,out_size+crp))
profile=profile.copy()
profile.pop('transform',None)
profile['width']=out_size
profile['height']=out_size
profile['affine']=src.window_transform(win)
return profile
#
# CROP GEOTIFF
#
path='input.tif'
out_path='output.tif'
crp=92
im,profile=get_image_and_profile(path)
im=crop_image(im,crp)
profile=crop_profile(profile,im.shape[1],crp)
image_write(im,out_path,profile)
Your window seems off, should be
rasterio.windows.Window(col_off, row_off, width, height)
so:
rasterio.windows.Window(crp, crp, img.shape1, img.shape[0])