0

I'm new with rasterio and I need to reduce the pixel size of a GeoTiff. Using the code below

def resample(input_raster: str, output_raster: str = None):
    upscale_factor = 2
    with rasterio.open(input_raster) as src:

        # resample data to target shape
        data = src.read(
            out_shape=(
                src.count,
                int(src.height * upscale_factor),
                int(src.width * upscale_factor)
            ),
            resampling=Resampling.bilinear
        )

        # scale image transform
        transform = src.transform * src.transform.scale(
            (src.width / data.shape[-1]),
            (src.height / data.shape[-2])
        )

        with rasterio.open(
            output_raster,
            "w",
            driver='GTiff',
            height=data.shape[2],
            width=data.shape[1],
            count=1,
            dtype=src.dtypes[0],
            crs=src.crs,
            transform=transform,
        ) as dest:
            print(dest)
            dest.write(1, data)

I see this error:

test_raster.py:28 (test_resample) tmp_path = PosixPath('/tmp/pytest-of-maxdragonheart/pytest-0/test_resample0')

def test_resample(tmp_path: Path) -> None:
    output_data = str(tmp_path / "resampled.tif")

   resample(
        input_raster=input_raster,
        output_raster=output_data
    )

test_raster.py:32: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ../../raster.py:123: in resample dest.write(1, data)


??? E rasterio.errors.InvalidArrayError: Positional argument arr must be an array-like object

rasterio/_io.pyx:1338: InvalidArrayError

How I can solve?

2
  • 1
    Posting the full traceback would be helpful
    – mikewatt
    Commented Mar 5, 2021 at 19:16
  • Ok @mikewatt I do this Commented Mar 5, 2021 at 19:55

1 Answer 1

0

It looks like you have the output band index and array arguments swapped.

Try changing this:

dest.write(1, data)

to this:

dest.write(data, 1)
3
  • Unfortunately now I have this error ValueError: Source shape (1, 1, 334, 414) is inconsistent with given indexes 1 Commented Mar 5, 2021 at 20:29
  • Slice/np.squeeze off those unnecessary axes. Perhaps if you exclude src.count from the out_shape in your read() call that wouldn't be necessary
    – mikewatt
    Commented Mar 5, 2021 at 21:23
  • Nothing is changed @mikewatt However I've used this example rasterio.readthedocs.io/en/latest/topics/resampling.html Commented Mar 7, 2021 at 11:57

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.