TransWikia.com

Merging multiple TIFF files into one TIFF file with multiple bands using Python

Geographic Information Systems Asked by Mohamed Amin HITORI on February 10, 2021

I am trying to merge multiple TIFF files into one multi-band TIFF using Python.
I used subprocess.checkoutput(‘python gdal.merge.py’) and it was working well.
But I am looking for another way to do this without using any external process.
Is there a library or a way that I can use.
This is the code I used

basename = '*'
outdir2 = './TIFF_Files'
filelist2 = glob.glob(os.path.join(outdir2, basename))
files_string = " ".join(filelist2)
print(files_string)
Tiff_output = os.path.join(outdir2,'Multi_band.tif')
command = "python gdal_merge.py -o " + Tiff_output + " -of gtiff -separate " + files_string
output = subprocess.check_output(command)

Keep in mind that I am not really advanced in Python.

One Answer

I found a way to replace the external process by using rasterio.

filelist2 = glob.glob(os.path.join(outdir2, basename))

# Read metadata of first file
with rasterio.open(filelist2[0]) as src0:
    meta = src0.meta

# Update meta to reflect the number of layers
meta.update(count = len(filelist2))

# Read each layer and write it to stack
Tiff_output = os.path.join(outdir2,'Multi_band.tif')
with rasterio.open(Tiff_output, 'w', **meta) as dst:
    for id, layer in enumerate(filelist2, start=1):
        with rasterio.open(layer) as src1:
            dst.write_band(id, src1.read(1))

outdir2 is the directory of the tiff files and basename = '*.tif'

Answered by Mohamed Amin HITORI on February 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP