Using Rasterio or GDAL to stack multiple bands without using subprocess commands
Using rasterio
you could do
import rasterio
file_list = ['file1.tif', 'file2.tif', 'file3.tif']
# Read metadata of first file
with rasterio.open(file_list[0]) as src0:
meta = src0.meta
# Update meta to reflect the number of layers
meta.update(count = len(file_list))
# Read each layer and write it to stack
with rasterio.open('stack.tif', 'w', **meta) as dst:
for id, layer in enumerate(file_list, start=1):
with rasterio.open(layer) as src1:
dst.write_band(id, src1.read(1))
It of course assumes that your input layers already share the same extent, resolution and data type
If using GDAL 2.1+ it's as simple as gdal.BuildVRT
then gdal.Translate
:
from osgeo import gdal
outvrt = '/vsimem/stacked.vrt' #/vsimem is special in-memory virtual "directory"
outtif = '/tmp/stacked.tif'
tifs = ['a.tif', 'b.tif', 'c.tif', 'd.tif']
#or for all tifs in a dir
#import glob
#tifs = glob.glob('dir/*.tif')
outds = gdal.BuildVRT(outvrt, tifs, separate=True)
outds = gdal.Translate(outtif, outds)