3

I have a geotiff file with many bands...

I will like to create a .asc file or tiff file by converting only one band from the geotiff file.

I don't find the solution by using python...

With os.system, i use:

os.system("gdal_translate -b 4 -of AAIGrid C:\in.tif C:\out_onlyband4.asc")

it is ok, but i will like to use by from osgeo import gdal... How can i do that?

from osgeo import gdal

drv = gdal.GetDriverByName('AAIGrid')

ds_in = gdal.Open('in.tif')

#i just want to extract one band (sample 4...) and create AAIGrid or GTiff with only one band, can you help me?

ds_out = drv.CreateCopy('out_onlyband4.asc', ds_in)

ds_in = None

ds_out = None

1 Answer 1

4

Individual bands can be accessed by calling GetRasterBand(4) from your datasource. You could then write your band as array into a newly created copy.

For instance like this:

driver = gdal.GetDriverByName("....") 
tDs = driver.Create(output, cols, rows, 1, gdal.GDT_Float32)

ds_in = gdal.Open('in.tif')
array = ds_in.GetRasterBand(4).ReadAsArray() # get values for band 4
# then write to band 1
band = tDs.GetRasterBand(1)
band.WriteArray(array)
band.FlushCache()

However If I am not mistaken the ESRI grid format doesn't support driver.create in gdal. Only createCopy. The easiest workaround is to simply call gdal_translate on your system...

1
  • What do I put inside this: gdal.GetDriverByName("....") ? Mar 30, 2022 at 12:54

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.