4

In GDAL warp you can simply set an xRes and yRes value. I'm trying to only use rasterio, but the process seems a lot less clear.

According to the docs https://rasterio.readthedocs.io/en/latest/topics/resampling.html you use a upscale or downscale factor to make a new cell resolution. Is there a way to just force a set value? For example, what if your new resolution doesn't divide evenly into your old one?

1 Answer 1

7

You just need to figure out the scale factor from your chosen and current pixel size, e.g. I want to resample this 10m resolution "input.tif" to 12.5m:

import rasterio
from rasterio.enums import Resampling

xres, yres = 12.5, 12.5

with rasterio.open("input.tif") as dataset:
    scale_factor_x = dataset.res[0]/xres
    scale_factor_y = dataset.res[1]/yres

    profile = dataset.profile.copy()
    # resample data to target shape
    data = dataset.read(
        out_shape=(
            dataset.count,
            int(dataset.height * scale_factor_y),
            int(dataset.width * scale_factor_x)
        ),
        resampling=Resampling.bilinear
    )

    # scale image transform
    transform = dataset.transform * dataset.transform.scale(
        (1 / scale_factor_x),
        (1 / scale_factor_y)
    )
    profile.update({"height": data.shape[-2],
                    "width": data.shape[-1],
                   "transform": transform})

with rasterio.open("output.tif", "w", **profile) as dataset:
    dataset.write(data)

And here's how the output looks (a single red 10m pixel over the output 12.5m pixels in greyscale): enter image description here

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.