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 ?

Marcelo Villa
  • 5,928
  • 2
  • 19
  • 38
kGummyBear
  • 25
  • 5
  • I like to use Rasterio for this sort of image processing in Python. Check this out: https://gis.stackexchange.com/a/223920/8104 – Aaron Nov 29 '19 at 04:51

1 Answers1

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)
Marcelo Villa
  • 5,928
  • 2
  • 19
  • 38