I am trying to stack four bands into one TIFF, this is the code I'm using:

            red_raster = rasterio.open(r"red.tif")
            red = red_raster.read(1, masked=True)

            nir_raster = rasterio.open(r"nir.tif")
            nir = nir_raster.read(1, masked=True)

            green_raster = rasterio.open(r"green.tif")
            green = green_raster.read(1, masked=True)

            blue_raster = rasterio.open(r"blue.tif")
            blue = blue_raster.read(1, masked=True)

            out_img = "stack.tif"

            out_meta = red_raster.meta.copy()
            out_meta.update({"count": 4,
                             "nodata": -10000})

            stack = np.dstack((blue, green, red, nir))
            with rasterio.open(out_img, "w", **out_meta) as dest:
               dest.write(stack, 4)

I am getting the error:

ValueError: Source shape (1, 10980, 10980, 4) is inconsistent with given indexes 1

I tried following the steps here: Using Rasterio or GDAL to stack multiple bands without using subprocess commands

but I don't understand exactly what they are doing and am still getting errors.

  • It seems like you are trying to write a 4D array whereas you should be writing a 3D array instead. – Marcelo Villa-Piñeros Apr 7 '20 at 18:21

You're trying to write all four bands at once to the file. If you study the example you gave carefully, you'll see that the bands are written to the destination file one at the time. Try something like:

file_list = [blue, green, red, nir]
with rasterio.open(out_img, 'w', **out_meta) as dest:
    for band_nr, src in enumerate(file_list, start=1):
        dest.write(src, band_nr)
  • new error now: dest.write(src, band_nr) File "rasterio_io.pyx", line 1389, in rasterio._io.DatasetWriterBase.write AttributeError: 'int' object has no attribute 'shape' – Emtomp Apr 7 '20 at 19:51
  • woops, that's because I forgot that enumerate gives the enumeration first and then the item. Let me make an edit to fix that. – Hans Roelofsen Apr 7 '20 at 19:57
  • it writes now, but the whole thing is nan, not sure why. Using gdal works, but was hoping to be able to do it in rasterio – Emtomp Apr 7 '20 at 20:07
  • 1
    Glad it works. Have you checked if the rasters you're reading are not NaN to begin with? If not, check if the pixel type of the numpy arrays correspond to the pixel type of dest – Hans Roelofsen Apr 7 '20 at 20:11
  • 1
    I read in the wrong thing... I read in red_raster instead of red. It works. Thank you! – Emtomp Apr 7 '20 at 20:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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