I have used GDAL to add descriptions to my raster band. I have verified in QGIS that the bands are indeed correctly named. I use the following function for adding names as band descriptions, which has a .txt file as input with the names separated by a comma:
def set_band_descriptions(raster_fpath: str, bands_txt: str) -> None:
"""Sets descriptions of raster bands using a .txt file.
Args:
raster_fpath (str): Filepath of raster.
bands_txt (str): Filepath of .txt file with band names.
"""
# Open raster using GDAL
ds = gdal.Open(raster_fpath, gdal.GA_Update)
# Open .txt file
band_file = open(bands_txt, "r")
# Splitting the content by comma
bands = band_file.read().split(sep = ",")
# Loop through all bands
for band in range(1, len(bands)+1):
rb = ds.GetRasterBand(band)
rb.SetDescription(bands[band - 1])
# Delete dataset
del ds
In another part of my script, I need to read the raster band description. This is my, very straightforward, code for doing so:
from osgeo import gdal
dataset = gdal.Open(raster_fpath)
band = dataset.GetRasterBand(1)
description = band.GetDescription()
print(description)
The print function returns an empty string. How do I correctly get the band description of a GeoTIFF file, preferably using GDAL?
Best Answer
As far as I see from the code, the problem might be in the way the raster dataset is closed in
set_band_descriptions()
. The GDAL Raster API tutorial suggests not to call thedel
operator on raster data sets:Instead, the recommended way to close the raster data set is to set it to
None
. The following code excerpt presents 2 functions that, respectively, display and set a description for a given band of a raster fileExecuting the following code on an example file, which originally had no description in the raster band, gives the following output: