TypeError when saving tif with rasterio using “rasterio.open”

numpypythonrasteriosave

I have image as ndarray with 20 bands with the following shape:
(20, 2227, 3676) .
I'm trying to save it using rasterio with the following script:

savedir=pathlib.Path('myfolder/')
savedir.mkdir(parents=True,exist_ok=True)


with rasterio.open(savedir /'myImage.tif', 
                                'w',
                                driver='GTiff',
                                height=img.shape[1],
                                width=img.shape[2],
                                count=20,
                                dtype=img.dtype,
                                crs=img_crs,
                                nodata=None, # change if data has nodata value
                                transform=img_transform) as dst:  
        
        for n in np.arange(0,20,1):
                dst.write(img[n,:,:],n+1)

This fails with he following error:

—> 17 dst.write(img_arr[n,:,:],n+1)

File rasterio/_io.pyx:1700, in rasterio._io.DatasetWriterBase.write()

TypeError: object of type 'numpy.int64' has no len()

I'm not sure what is the source of this error, but I know that if I use the same script but instead of iterating through the bands I put manualy each band, it works. for example:

dst.write(img_arr[0,:,:],1)
dst.write(img_arr[1,:,:],2)
...
dst.write(img_arr[19,:,:],20)

That works.

Hence, I don't know why I get the type error, and I don't waant to put manually all the bands of the image. How can I solve this issue?

Best Answer

It's not the dtype of the img array that's the problem, it's your n variable.

rasterio is expecting a python int not a numpy.int64 for the band number.

# this works
for n in range(0,1):
    dst.write(img[n,:, :], n+1)

# this works too
for n in np.arange(0,1):
    dst.write(img[n,:, :], int(n+1))

# this works for me
dst.write(img)

# this fails with `TypeError: object of type 'numpy.int64' has no len()`
for n in np.arange(0,1):
    dst.write(img[n,:, :], n+1) # n is np.int64 not int