getS2THEIAFromShp.py 2.62 KiB
#! /usr/bin/env python
import sys
import os
import getopt
import ogr
import osr
import platform
import subprocess
from datetime import date

from mtdUtils import getShapefileExtent_WGS84

def main(argv):
    if platform.system() == 'Linux':
        sh = False
    elif platform.system() == 'Windows':
        sh = True
    else:
        sys.exit("Platform not supported!")

    try:
        opts, args = getopt.getopt(argv, 'w:d:f:c:m:')
    except getopt.GetoptError as err:
        sys.exit(err)

    shp_file = args[-2]
    if not os.path.exists(shp_file):
        sys.exit('%s does not exist'%shp_file)
    theia_folder = args[-1]
    if not os.path.exists(theia_folder):
        sys.exit('%s does not exist, please give the path to the theia_download folder'%theia_folder)
    else :
        id_file = theia_folder + os.sep + 'config_theia.cfg'
        if not os.path.exists(id_file) :
            sys.exit('%s does not exist, the usual file for theia ID is named "config_theia.cfg"'%id_file)
    output_folder = os.path.dirname(shp_file)
    date_beg = None
    date_end = None
    collection = 'SENTINEL2'
    max_cloud = None

    for opt,val in opts:
        if opt == '-w':
            output_folder = str(val)
            if not os.path.exists(output_folder):
                os.mkdir(output_folder)
        elif opt == '-d':
            date_beg = str(val)
        elif opt == '-f':
            date_end = str(val)
        elif opt == '-c' :
            if val in ['Landsat','SpotWorldHeritage','SENTINEL2','Snow','VENUS']:
                collection = str(val)
            else :
                sys.exit("%s is not a valide collection, please use one of the following values : \
                        ['Landsat','SpotWorldHeritage','SENTINEL2','Snow','VENUS']"%val)
        elif opt == '-m':
            max_cloud = val

    extent = getShapefileExtent_WGS84(shp_file)

    cmd = ['python3', theia_folder+'/theia_download.py', '-a', id_file, '-w', output_folder, '-c', collection,
    	'--lonmin', str(extent[0]), '--lonmax',  str(extent[2]), '--latmin', str(extent[3]), '--latmax', str(extent[1]), '--level', 'LEVEL2A']
    if date_beg != None :
        cmd += ['-d', date_beg]
    if date_end != None:
        cmd += ['-f', date_end]
    if max_cloud != None:
        cmd += ['-m', max_cloud]
    print(cmd)
    subprocess.call(cmd, shell=sh)

if __name__ == '__main__':
    if len(sys.argv) < 3:
        sys.exit(
            'Usage: python getS2THEIAFromShp.py [-w <output folder>] [-d <begin-date YYYY-MM-DD>] [-f <end-date YYYY-MM-DD>] [-c <collection>] [-m <maxcloud>] <shp-file> <theia_download-installation-folder>')
    else:
        main(sys.argv[1:])