GDAL – Merging GeoTIFF Images with Separate Band Input Using GDAL Script

gdalgdal-translatemergeraster

In QGIS when I merge two images with 3 and 5 bands respectively via Raster >> Miscellaneous >> Merge with the option checked on place each input into a separate band it resulted in a merged image that has 8 bands which is what I wanted.

enter image description here

Now I want to replicated this result in python/GDAL, but it doesn't give me same result. Instead it returns a merged image with just 2 bands not 8 bands. My code is below:-

from osgeo import gdal

img_list = ['img1.tif', 'img2.tif']

vrt = gdal.BuildVRT("merged.vrt", img_list, separate=True)
gdal.Translate('merge_img.tif', vrt)

Best Answer

As mentioned in the other answer :

-separate

Place each input file into a separate band. In that case, only the first band of each dataset will be placed into a new band. Contrary to the default mode, it is not required that all bands have the same datatype.

the workaround in command line is a bit long but it works: It consists in making two sets of 1 band images before you merge them

gdalbuildvrt -b 1 im1b1.vrt im1.tif
gdalbuildvrt -b 2 im1b2.vrt im1.tif
....
gdalbuildvrt -b 1 im2b1.vrt im2.tif
gdalbuildvrt -b 2 im2b2.vrt im2.tif
....
gdalbuildvrt -separate multiband.vrt im*.vrt
gdal_translate multiband.vrt multiband.tif
Related Question