0

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.

CODE:

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)
brook
  • 247
  • 2
  • 15

1 Answers1

0

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])

Christoph Rieke
  • 707
  • 5
  • 7
  • 1
    so the docs say you can use `rasterio.windows.Window` as you described **or** a tuple `((row_start, row_stop), (col_start, col_stop))` which is what i've done. that said, i'll try using the rasterio Window class and see if that works. – brook Oct 17 '18 at 21:58
  • thanks! rasterio.windows.Window worked. i think i could have gotten the tuple to work as well. turns out i was still on rasterio 0.36. i had to update to the latest (1.something) to use Window, but I did and it worked just fine. thanks again – brook Oct 18 '18 at 00:39
  • @brook: Glad it worked. You are right with the tuple, tuple though. What shape was your original image and clipped image? Seeing that you are using out_size[1] for both axis I guess it had the same number of rows and columns? If not that could have been the catch? – Christoph Rieke Oct 18 '18 at 21:16
  • yep - i was using square images and doing a square cropping so i could simplify a bit. thanks again. – brook Oct 19 '18 at 05:05