I need help with a python script to iterate merge (gdal_merge.py) of rasters:

For each folder located in /home/geodata/sentinel2/ look in subfolder IMG_DATA and merge the three rasters with filenames ending with B08.jp2, B04.jp2 and B03.jp2 to output /home/geodata/outputfolder/raster1.tif

and then move to the next folder in /home/geodata/sentinel2/ and do the same thing and output raster2.tif to the same output folder as raster1

and so on... enter image description here


rather than giving you a full answer I want to give you some tools:

from os import listdir 


will give you files, folders. Take a look at .basename and .extenhsion. You can use regular expressions to filter the files you need as an alternative to exact matches.

think you can find all sub questions in other topics.


This will get the job done with ArcGIS (most likely can be done with shorter/better code):

import os, arcpy
from datetime import datetime, time
print "Running script..."

arcpy.env.outputCoordinateSystem = r"D:\Projektionsfiler\SWEREF99TM.prj"
arcpy.env.geographicTransformations = "SWEREF99_To_WGS_1984_1"

arbetsmapp = r'D:\S2'
utdatamapp = r'D:\S2\utdata'

#the color bands to be composited
filandelse = ["B08.jp2", "B04.jp2", "B03.jp2"]

#lists rasters with file paths that end with filandelse
lista = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(arbetsmapp)
    for f in files if f.endswith(tuple(filandelse))]

#reverse list from ...B03.jp2, 04, 08 to 08 04 03 (red green blue)

#Divide list in parts of three
listaomtre =  zip(*[iter(lista)]*3)

#Run composite bands
for grupp in listaomtre:
    starttid = datetime.now()
    arcpy.CompositeBands_management(in_rasters=grupp, out_raster=os.path.join(utdatamapp,grupp[-1][-13:-8])+".tif")
    sluttid = datetime.now()
    tidsatgang = sluttid-starttid
    print "Finished raster " + grupp[-1][-13:-8] + " in " + str(tidsatgang.seconds) + " seconds"

print "Script complete"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.