I have a raster that, for the most part, contains no-data values. Only on the right side there is data:

what i have

I would like to get rid of the left part and have a new raster. The extent of the new raster would be the smallest bounding box around the valid data:

what i want

The part that actually contains the valid data would stay untouched. I am working with Python.

I feel like this is a trivial task but can't think of a reasonable way to do it. I work with the rasterio library but can't find this functionality in their docs.

I don't need the actual code, just an idea on how to do it.

1 Answer 1


Have a look at

You would then use windowed reading to read only the valid data and then you can write out a new clipped raster.

import rasterio as rio
from rasterio.windows import get_data_window, transform, shape

input = 'input.tif'
output = 'output.tif'

with rio.open(input) as src:
    profile = src.profile.copy()
    data_window = get_data_window(src.read(masked=True))
    data_transform = transform(data_window, src.transform)

    data = src.read(window=data_window)

with rio.open(output, 'w', **profile) as dst:

In the case where your raster doesn't have a nodata value set, find out what value the areas you wish to mask are, then set that as nodata:

with rio.open(input, 'r+') as src:  # open as append mode r+
    src.nodata = 0  # my empty areas are 0, so I set them to NoData
    profile = src.profile.copy()
    data_window = get_data_window(src.read(masked=True))

Input (blue) and output nodata (green) shown below:

enter image description here

  • Thank you! I tried your code and with my data it results in the following error: "AxisError: axis 0 is out of bounds for array of dimension 0" on the get_data_window() line. When I don't specify masked=True then it runs ok but the result is the same size as input. Any idea what might be wrong? Thanks!
    – Jan Pisl
    Apr 18, 2022 at 17:22
  • For anyone running into the problem I describe in my previous comment, try create the mask yourself instead of having rasterio do it. Have a look at the answer of sgillies in the following question to see how to do it: gis.stackexchange.com/questions/224043/…
    – Jan Pisl
    Apr 18, 2022 at 17:29
  • 1
    @JanPisl it's because your raster doesn't have a NoData value set. So the "NoData" areas you refer to aren't considered NoData and your mask is empty. See edit.
    – user2856
    Apr 18, 2022 at 22:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.