3

I would like to save a 3-band raster to file using rasterio.

The official docs have examples for saving a single band image in both the quickstart and in the advanced topics.

What I would like to do is something like..

with rasterio.open('image.tif', 'w', **meta) as dst:
    dst.write(array)

This raises the following error for an array with a shape of (256, 256, 3).

ValueError: Source shape (256, 256, 3) is inconsistent with given indexes 3
0

2 Answers 2

8

To rearrange the axis (i.e., move the bands channel to make it the first axis), you can use np.rollaxis.

with rasterio.open('image.tif', 'w', **meta) as dst:
    # Note: assumes band info is in axis 2. Also, break up commands for clarity.
    rolled_array = np.rollaxis(array, axis=2)  # Roll axis 2 to 0th position
    dst.write(rolled_array)  

rasterio also has some built-in function to help with this as shown here. See rasterio.plot.reshape_as_raster and rasterio.plot.reshape_as_image.

1
  • np.rollaxis won't work if array is in (x, y, z) order, you'll end up with (z, x, y) instead of (z, y, x).
    – user2856
    Apr 8, 2020 at 1:21
4

The numpy array needs to be in bands, rows, cols order (z, y, x) not cols, rows, bands (x, y, z).

You can rearrange the axes with numpy.moveaxis

e.g.

import numpy as np
import rasterio

with rasterio.open('image.tif', 'w', **meta) as dst:
    # If array is in (x, y, z) order (cols, rows, bands)
    dst.write(np.moveaxis(array, [0, 1, 2], [2, 1, 0]))

    # If array is in (y, x, z) order (rows, cols, bands)
    dst.write(np.moveaxis(array, [0, 1, 2], [2, 0, 1]))  # same as np.rollaxis(array, axis=2)
2
  • how do you change the order?
    – Emtomp
    Apr 7, 2020 at 15:55
  • @Emtomp, see answer below
    – wronk
    Apr 7, 2020 at 19:46

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.