6

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.

2
  • It seems like you are trying to write a 4D array whereas you should be writing a 3D array instead. Apr 7, 2020 at 18:21
  • You could also do this on the command line with rio stack red.tif nir.tif green.tif blue.tif -o stack.tif. When you have rasterio installed, you also have rio.
    – j08lue
    Aug 4, 2021 at 7:55

1 Answer 1

9

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)
5
  • 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, 2020 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. Apr 7, 2020 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, 2020 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 Apr 7, 2020 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, 2020 at 20:15

Your Answer

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

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