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
    Commented Apr 4, 2020 at 21:32
  • right! good catch! Thanks
    – Emtomp
    Commented Apr 4, 2020 at 21:39

2 Answers 2

2

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
1

I had the same issue and with some changes I reached one script that worked fine.

import os
import rasterio

Defining different objects to be used:,

src = 'C:/home/User/Documents/file.tif'
src2 = rasterio.open('C:/home/User/Documents/file.tif')
folder = 'C:/home/User/Documents'

for band in range(1, src2.count +1): #The +1 allows the writing of the last band
        single_band = src2.read(band)

        # get the output name
        out_name = os.path.basename(src)
        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 = src2.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, 1)

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.