0

I'm working with Sentinel-2 satellite and i'm working with 2,3,4,8 bands. I have to make composite mergining bands. I download images from https://scihub.copernicus.eu/. I used gdal_merge in console for creating composites. I have batch files, code below:

For /F  %%i in ('where /R %cd% *B02*.jp2') do set file1=%%i
 For /F  %%n in ('where /R %cd% *B03*.jp2') do set file2=%%n
 For /F  %%m in ('where /R %cd% *B04*.jp2') do set file3=%%m
 For /F  %%o in ('where /R %cd% *B08*.jp2') do set file4=%%o
gdal_merge -o composite.tif %file1% %file2% %file3% %file4% -co COMPRESS=LZW -separate
pause

It's working, but i'd like to write own script using Python.

Could somebody give me advice how can i do it, please ? Is there another way to do it ?

1

1 Answer 1

1

You can call gdal_merge from Python using the subprocess module. To list your files you can use the glob module.

The following code should accomplish waht you want:

import glob
import os
import subprocess

path = r'C:\path\to\images'

b2_files = glob.glob(os.path.join(path, '*B02*.jp2'))
b3_files = glob.glob(os.path.join(path, '*B03*.jp2'))
b4_files = glob.glob(os.path.join(path, '*B04*.jp2'))
b8_files = glob.glob(os.path.join(path, '*B08*.jp2'))

for file1, file2, file3, file4 in zip(b2_files, b3_files, b4_files, b8_files):
    cmd = f'gdal_merge -o composite.tif {file1} {file2} {file3} {file4} -co COMPRESS=LZW -separate'
    subprocess.call(cmd)

Note that the output is always the same (composite.tif), though. You might want to change the name dynamically. Also, this works in Python versions that support f-strings (3.6+). If you need it to work on older versions change the cmd line to:

cmd = 'gdal_merge -o composite.tif {} {} {} {} -co COMPRESS=LZW -separate'.format(file1, file2, file3, file4)

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.