1

I have been trying to break down my multi-band raster into individual bands with rasterio and I am getting this error:

ValueError: Source shape (11356, 9488) is inconsistent with given indexes 1

here's the code:

import os
import rasterio


 src = rasterio.open(wv_tif)
    for band in range(1, src.count):
        single_band = src.read(band)

        # get the output name
        out_name = os.path.basename(wv_tif)
        file, ext = os.path.splitext(out_name)
        name = file + "_" + "B" + str(band) + ".tif"
        out_img = os.path.join(folder, name)

        print(out_img + " done")

        # Copy the metadata
        out_meta = src.meta.copy()

        out_meta.update({"count": 1})

        # save the clipped raster to disk
        with rasterio.open(out_img, "w", **out_meta) as dest:
            dest.write(single_band)

I have no idea what is going wrong

2
  • 1
    Note you need to use for band in range(1, src.count + 1): or you'll miss the last band as the range(start, stop) function only returns values >= start and < stop. E.g. if you have a 4 band raster range(1, 4) will only have values [1, 2, 3]. – user2856 Apr 4 '20 at 21:32
  • right! good catch! Thanks – Emtomp Apr 4 '20 at 21:39
1

You're telling rasterio to write a dataset so it's expecting an array shape of (bands, rows, cols), but you're passing a single band, an array shape of (rows, cols).

Either reshape your array:

dest.write(single_band[np.newaxis,...])`

Or tell rasterio to write a single band:

dest.write(single_band, 1)
0

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.