0

I have the following working function that saves a raster stack to geotiff using rasterio:

def saveRasterToDisc(out_image, raster_crs, out_transform, output_raster_path):
    # save raster to disk
    with rasterio.open(output_raster_path, 'w',
                       driver='GTiff',
                       height=out_image.shape[1],
                       width=out_image.shape[2],
                       count=out_image.shape[0], 
                       dtype=out_image.dtype,
                       crs=raster_crs,
                       transform=out_transform,
                       nodata=0,
                       ) as dst:
        dst.write(out_image)

However, the individual bands do not contain any names yet. I tried the following:

# e.g. raster stack with three bands
bands = ["B02","B03","B04"]

def saveRasterToDisc(out_image, raster_crs, out_transform, bands, output_raster_path):
    # save raster to disk
    with rasterio.open(output_raster_path, 'w',
                       driver='GTiff',
                       height=out_image.shape[1],
                       width=out_image.shape[2],
                       count=out_image.shape[0], 
                       dtype=out_image.dtype,
                       crs=raster_crs,
                       transform=out_transform,
                       nodata=0,
                       descriptions=bands
                       ) as dst:
        dst.write(out_image)

I also tried:

with rasterio.open(output_raster_path, 'w',
                  ...
                  ) as dst:
     dst.write(out_image)
     dst.descriptions = tuple(bands)

and:

with rasterio.open(output_raster_path, 'w',
                  ...
                  ) as dst:
    dst.write(out_image)
    for index, band_name in enumerate(bands):
        dst.set_band_description(index+1, band_name)

The code runs always sucessfully, but when I look at the tif in ArcGIS the band names are not shown:

ArcGIS tif as is

This is what I expect:

ArcGIS tif as expected

Any ideas? Thank you!

Zozzoy
  • 63
  • 6

1 Answers1

1

I encountered the same problem and this worked for me

bands = ["B02","B03","B04"]

with rasterio.open(output_raster_path, "r+") as dataset:
    for i in range(1, dataset.count + 1):
        print(f'Band {str(i)} name: {dataset.descriptions[i - 1]}') #print the original band name
        for index, item in enumerate(bands):
            if index == i-1: #the -1 set the index to 0 position otherwise it would start from position 1
                    dataset.set_band_description(i, item)
                    print(f'Band {str(i)} name: {dataset.descriptions[i - 1]}') #print the new band name
Giacomo
  • 123
  • 6