コード例 #1
0
def soilOccupationChange(input_plot_vector, output_plot_vector, footprint_vector, input_tx_files_list, evolutions_list=['0:1:11000:10:50:and', '0:1:12000:10:50:and', '0:1:21000:10:50:and', '0:1:22000:10:50:and', '0:1:23000:10:50:and'], class_label_dico={11000:'Bati', 12000:'Route', 21000:'SolNu', 22000:'Eau', 23000:'Vegetation'}, epsg=2154, no_data_value=0, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster='.tif', extension_vector='.shp', postgis_ip_host='localhost', postgis_num_port=5432, postgis_user_name='postgres', postgis_password='******', postgis_database_name='database', postgis_schema_name='public', postgis_encoding='latin1', path_time_log='', save_results_intermediate=False, overwrite=True):

    if debug >= 3:
        print('\n' + bold + green + "Evolution de l'OCS par parcelle - Variables dans la fonction :" + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "input_plot_vector : " + str(input_plot_vector) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "output_plot_vector : " + str(output_plot_vector) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "footprint_vector : " + str(footprint_vector) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "input_tx_files_list : " + str(input_tx_files_list) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "evolutions_list : " + str(evolutions_list) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "class_label_dico : " + str(class_label_dico) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "epsg : " + str(epsg) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "no_data_value : " + str(no_data_value) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "format_raster : " + str(format_raster) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "format_vector : " + str(format_vector) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "extension_raster : " + str(extension_raster) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "extension_vector : " + str(extension_vector) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "postgis_ip_host : " + str(postgis_ip_host) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "postgis_num_port : " + str(postgis_num_port) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "postgis_user_name : " + str(postgis_user_name) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "postgis_password : "******"    soilOccupationChange() : " + endC + "postgis_database_name : " + str(postgis_database_name) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "postgis_schema_name : " + str(postgis_schema_name) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "postgis_encoding : " + str(postgis_encoding) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "path_time_log : " + str(path_time_log) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC)
        print(cyan + "    soilOccupationChange() : " + endC + "overwrite : " + str(overwrite) + endC + '\n')

    # Définition des constantes
    EXTENSION_TEXT = '.txt'
    SUFFIX_TEMP = '_temp'
    SUFFIX_CUT = '_cut'
    AREA_FIELD = 'st_area'
    GEOM_FIELD = 'geom'

    # Mise à jour du log
    starting_event = "soilOccupationChange() : Début du traitement : "
    timeLine(path_time_log, starting_event)

    print(cyan + "soilOccupationChange() : " + bold + green + "DEBUT DES TRAITEMENTS" + endC + '\n')

    # Définition des variables 'basename'
    output_plot_basename = os.path.splitext(os.path.basename(output_plot_vector))[0]

    # Définition des variables temp
    temp_directory = os.path.dirname(output_plot_vector) + os.sep + output_plot_basename + SUFFIX_TEMP
    plot_vector_cut = temp_directory + os.sep + output_plot_basename + SUFFIX_CUT + extension_vector

    # Définition des variables PostGIS
    plot_table = output_plot_basename.lower()

    # Fichier .txt associé au fichier vecteur de sortie, sur la liste des évolutions quantifiées
    output_evolution_text_file = os.path.splitext(output_plot_vector)[0] + EXTENSION_TEXT

    # Nettoyage des traitements précédents
    if debug >= 3:
        print(cyan + "soilOccupationChange() : " + endC + "Nettoyage des traitements précédents." + endC + '\n')
    removeVectorFile(output_plot_vector, format_vector=format_vector)
    removeFile(output_evolution_text_file)
    cleanTempData(temp_directory)
    dropDatabase(postgis_database_name, user_name=postgis_user_name, password=postgis_password, ip_host=postgis_ip_host, num_port=postgis_num_port, schema_name=postgis_schema_name)

    #############
    # Etape 0/2 # Préparation des traitements
    #############

    print(cyan + "soilOccupationChange() : " + bold + green + "ETAPE 0/2 - Début de la préparation des traitements." + endC + '\n')

    # Découpage du parcellaire à la zone d'étude
    cutVector(footprint_vector, input_plot_vector, plot_vector_cut, overwrite=overwrite, format_vector=format_vector)

    # Récupération du nom des champs dans le fichier source (pour isoler les champs nouvellement créés par la suite, et les renommer)
    attr_names_list_origin = getAttributeNameList(plot_vector_cut, format_vector=format_vector)
    new_attr_names_list_origin = attr_names_list_origin

    # Préparation de PostGIS
    createDatabase(postgis_database_name, user_name=postgis_user_name, password=postgis_password, ip_host=postgis_ip_host, num_port=postgis_num_port, schema_name=postgis_schema_name)

    print(cyan + "soilOccupationChange() : " + bold + green + "ETAPE 0/2 - Fin de la préparation des traitements." + endC + '\n')

    #############
    # Etape 1/2 # Calculs des statistiques à tx
    #############

    print(cyan + "soilOccupationChange() : " + bold + green + "ETAPE 1/2 - Début des calculs des statistiques à tx." + endC + '\n')

    len_tx = len(input_tx_files_list)
    tx = 0

    # Boucle sur les fichiers d'entrés à t0+x
    for input_tx_file in input_tx_files_list:
        if debug >= 3:
            print(cyan + "soilOccupationChange() : " + endC + bold + "Calcul des statistiques à tx %s/%s." % (tx+1, len_tx) + endC + '\n')

        # Statistiques OCS par parcelle
        statisticsVectorRaster(input_tx_file, plot_vector_cut, "", 1, True, False, False, [], [], class_label_dico, path_time_log, clean_small_polygons=True, format_vector=format_vector, save_results_intermediate=save_results_intermediate, overwrite=overwrite)

        # Récupération du nom des champs dans le fichier parcellaire (avec les champs créés précédemment dans CVR)
        attr_names_list_tx = getAttributeNameList(plot_vector_cut, format_vector=format_vector)

        # Isolement des nouveaux champs issus du CVR
        fields_name_list  = []
        for attr_name in attr_names_list_tx:
            if attr_name not in new_attr_names_list_origin:
                fields_name_list.append(attr_name)

        # Gestion des nouveaux noms des champs issus du CVR
        new_fields_name_list  = []
        for field_name in fields_name_list:
            new_field_name = 't%s_' % tx + field_name
            new_field_name = new_field_name[:10]
            new_fields_name_list.append(new_field_name)
            new_attr_names_list_origin.append(new_field_name)

        # Renommage des champs issus du CVR, pour le relancer par la suite sur d'autres dates
        renameFieldsVector(plot_vector_cut, fields_name_list, new_fields_name_list, format_vector=format_vector)

        tx += 1

    print(cyan + "soilOccupationChange() : " + bold + green + "ETAPE 1/2 - Fin des calculs des statistiques à tx." + endC + '\n')

    #############
    # Etape 2/2 # Caractérisation des changements
    #############

    print(cyan + "soilOccupationChange() : " + bold + green + "ETAPE 2/2 - Début de la caractérisation des changements." + endC + '\n')

    # Pré-traitements dans PostGIS
    plot_table = importVectorByOgr2ogr(postgis_database_name, plot_vector_cut, plot_table, user_name=postgis_user_name, password=postgis_password, ip_host=postgis_ip_host, num_port=postgis_num_port, schema_name=postgis_schema_name, epsg=epsg, codage=postgis_encoding)
    connection = openConnection(postgis_database_name, user_name=postgis_user_name, password=postgis_password, ip_host=postgis_ip_host, num_port=postgis_num_port, schema_name=postgis_schema_name)

    # Requête SQL pour le calcul de la surface des parcelles
    sql_query = "ALTER TABLE %s ADD COLUMN %s REAL;\n" % (plot_table, AREA_FIELD)
    sql_query += "UPDATE %s SET %s = ST_Area(%s);\n" % (plot_table, AREA_FIELD, GEOM_FIELD)

    # Boucle sur les évolutions à quantifier
    temp_field = 1
    for evolution in evolutions_list:
        evolution_split = evolution.split(':')
        idx_bef = int(evolution_split[0])
        idx_aft = int(evolution_split[1])
        label = int(evolution_split[2])
        evol = abs(int(evolution_split[3]))
        evol_s = abs(int(evolution_split[4]))
        combi = evolution_split[5]
        class_name = class_label_dico[label]
        def_evo_field = "def_evo_%s" % str(temp_field)
        if debug >= 3:
            print(cyan + "soilOccupationChange() : " + endC + bold + "Caractérisation des changements t%s/t%s pour la classe '%s' (%s)." % (idx_bef, idx_aft, class_name, label) + endC + '\n')

        if evol != 0 or evol_s != 0:

            # Gestion de l'évolution via le taux
            evol_str = str(evol) + ' %'
            evo_field = "evo_%s" % str(temp_field)
            t0_field = 't%s_' % idx_bef + class_name.lower()[:7]
            t1_field = 't%s_' % idx_aft + class_name.lower()[:7]

            # Gestion de l'évolution via la surface
            evol_s_str = str(evol_s) + ' m²'
            evo_s_field = "evo_s_%s" % str(temp_field)
            t0_s_field = 't%s_s_' % idx_bef + class_name.lower()[:5]
            t1_s_field = 't%s_s_' % idx_aft + class_name.lower()[:5]

            # Requête SQL pour le calcul brut de l'évolution
            sql_query += "ALTER TABLE %s ADD COLUMN %s REAL;\n" % (plot_table, evo_field)
            sql_query += "UPDATE %s SET %s = %s - %s;\n" % (plot_table, evo_field, t1_field, t0_field)
            sql_query += "ALTER TABLE %s ADD COLUMN %s REAL;\n" % (plot_table, evo_s_field)
            sql_query += "UPDATE %s SET %s = %s - %s;\n" % (plot_table, evo_s_field, t1_s_field, t0_s_field)
            sql_query += "ALTER TABLE %s ADD COLUMN %s VARCHAR;\n" % (plot_table, def_evo_field)
            sql_query += "UPDATE %s SET %s = 't%s a t%s - %s - aucune evolution';\n" % (plot_table, def_evo_field, idx_bef, idx_aft, class_name)

            # Si évolution à la fois via taux et via surface
            if evol != 0 and evol_s != 0:
                text_evol = "taux à %s" % evol_str
                if combi == 'and':
                    text_evol += " ET "
                elif combi == 'or':
                    text_evol += " OU "
                text_evol += "surface à %s" % evol_s_str
                sql_where_pos = "%s >= %s %s %s >= %s" % (evo_field, evol, combi, evo_s_field, evol_s)
                sql_where_neg = "%s <= -%s %s %s <= -%s" % (evo_field, evol, combi, evo_s_field, evol_s)

            # Si évolution uniquement via taux
            elif evol != 0:
                text_evol = "taux à %s" % evol_str
                sql_where_pos = "%s >= %s" % (evo_field, evol)
                sql_where_neg = "%s <= -%s" % (evo_field, evol)

            # Si évolution uniquement via surface
            elif evol_s != 0:
                text_evol = "surface à %s" % evol_s_str
                sql_where_pos = "%s >= %s" % (evo_s_field, evol_s)
                sql_where_neg = "%s <= -%s" % (evo_s_field, evol_s)

            sql_query += "UPDATE %s SET %s = 't%s a t%s - %s - evolution positive' WHERE %s;\n" % (plot_table, def_evo_field, idx_bef, idx_aft, class_name, sql_where_pos)
            sql_query += "UPDATE %s SET %s = 't%s a t%s - %s - evolution negative' WHERE %s;\n" % (plot_table, def_evo_field, idx_bef, idx_aft, class_name, sql_where_neg)

            # Ajout des paramètres de l'évolution quantifiée (temporalités, classe, taux/surface) au fichier texte de sortie
            text = "%s --> évolution entre t%s et t%s, pour la classe '%s' (label %s) :\n" % (def_evo_field, idx_bef, idx_aft, class_name, label)
            text += "    %s --> taux d'évolution brut" % evo_field + " (%)\n"
            text += "    %s --> surface d'évolution brute" % evo_s_field + " (m²)\n"
            text += "Evolution quantifiée : %s\n" % text_evol
            appendTextFileCR(output_evolution_text_file, text)
            temp_field += 1

    # Traitements SQL de l'évolution des classes OCS
    executeQuery(connection, sql_query)
    closeConnection(connection)
    exportVectorByOgr2ogr(postgis_database_name, output_plot_vector, plot_table, user_name=postgis_user_name, password=postgis_password, ip_host=postgis_ip_host, num_port=postgis_num_port, schema_name=postgis_schema_name, format_type=format_vector)

    print(cyan + "soilOccupationChange() : " + bold + green + "ETAPE 2/2 - Fin de la caractérisation des changements." + endC + '\n')

    # Suppression des fichiers temporaires
    if not save_results_intermediate:
        if debug >= 3:
            print(cyan + "soilOccupationChange() : " + endC + "Suppression des fichiers temporaires." + endC + '\n')
        deleteDir(temp_directory)
        dropDatabase(postgis_database_name, user_name=postgis_user_name, password=postgis_password, ip_host=postgis_ip_host, num_port=postgis_num_port, schema_name=postgis_schema_name)

    print(cyan + "soilOccupationChange() : " + bold + green + "FIN DES TRAITEMENTS" + endC + '\n')

    # Mise à jour du log
    ending_event = "soilOccupationChange() : Fin du traitement : "
    timeLine(path_time_log, ending_event)

    return
def imperviousSurfaceFraction(grid_input, grid_output, classif_input, class_imprevious_list, path_time_log, format_vector='ESRI Shapefile', extension_raster=".tif", save_results_intermediate=False, overwrite=True):

    print(bold + yellow + "Début du calcul de l'indicateur Impervious Surface Fraction." + endC + "\n")
    timeLine(path_time_log, "Début du calcul de l'indicateur Impervious Surface Fraction : ")

    if debug >= 3 :
        print(bold + green + "imperviousSurfaceFraction() : Variables dans la fonction" + endC)
        print(cyan + "imperviousSurfaceFraction() : " + endC + "grid_input : " + str(grid_input) + endC)
        print(cyan + "imperviousSurfaceFraction() : " + endC + "grid_output : " + str(grid_output) + endC)
        print(cyan + "imperviousSurfaceFraction() : " + endC + "classif_input : " + str(classif_input) + endC)
        print(cyan + "imperviousSurfaceFraction() : " + endC + "class_imprevious_list : " + str(class_imprevious_list) + endC)
        print(cyan + "imperviousSurfaceFraction() : " + endC + "path_time_log : " + str(path_time_log) + endC)
        print(cyan + "imperviousSurfaceFraction() : " + endC + "format_vector : " + str(format_vector) + endC)
        print(cyan + "imperviousSurfaceFraction() : " + endC + "extension_raster : " + str(extension_raster) + endC)
        print(cyan + "imperviousSurfaceFraction() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC)
        print(cyan + "imperviousSurfaceFraction() : " + endC + "overwrite : " + str(overwrite) + endC)

    if not os.path.exists(grid_output) or overwrite:

        ############################################
        ### Préparation générale des traitements ###
        ############################################

        if os.path.exists(grid_output):
            removeVectorFile(grid_output)

        temp_path = os.path.dirname(grid_output) + os.sep + "ImperviousSurfaceFraction"
        impermeability_raster = temp_path + os.sep + "impermeability" + extension_raster

        if os.path.exists(temp_path):
            shutil.rmtree(temp_path)
        os.makedirs(temp_path)

        ##############################
        ### Calcul de l'indicateur ###
        ##############################

        print(bold + cyan + "Création de la carte d'imperméabilité :" + endC + "\n")
        timeLine(path_time_log, "    Création de la carte d'imperméabilité : ")
        expression = ""
        for id_class in class_imprevious_list :
            expression += "im1b1==%s or " %(str(id_class))
        expression = expression[:-4]
        command = "otbcli_BandMath -il %s -out %s uint8 -exp '%s ? 1 : 99'" %(classif_input, impermeability_raster, expression)
        if debug >= 3 :
            print(command)
        exit_code = os.system(command)
        if exit_code != 0:
            print(command)
            print(cyan + "imperviousSurfaceFraction() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : " + command + ". Voir message d'erreur." + endC, file=sys.stderr)
            raise

        print(bold + cyan + "Récupération de Impervious Surface Fraction par maille :" + endC + "\n")
        timeLine(path_time_log, "    Récupération de Impervious Surface Fraction par maille : ")
        statisticsVectorRaster(impermeability_raster, grid_input, grid_output, 1, True, False, False, [], [], {99:'Perm', 1:'Imperm'}, path_time_log, True, format_vector, save_results_intermediate, overwrite)


        ##########################################
        ### Nettoyage des fichiers temporaires ###
        ##########################################

        if not save_results_intermediate:
            if os.path.exists(temp_path):
                shutil.rmtree(temp_path)

    else:
        print(bold + magenta + "Le calcul du Impervious Surface Fraction a déjà eu lieu." + endC + "\n")

    print(bold + yellow + "Fin du calcul de l'indicateur Impervious Surface Fraction." + endC + "\n")
    timeLine(path_time_log, "Fin du calcul de l'indicateur Impervious Surface Fraction : ")

    return
def computeVegetationHeight(
        input_grid, output_grid, soil_occupation, height_model,
        height_vegetation, divide_vegetation_classes, vegetation_label,
        high_vegetation_label, low_vegetation_label, high_vegetation_field,
        low_vegetation_field, veg_mean_field, veg_max_field, veg_rate_field,
        codage_float, suffix_temp, no_data_value, format_vector, path_time_log,
        save_results_intermediate, overwrite):

    temp_grid = os.path.splitext(
        input_grid)[0] + suffix_temp + os.path.splitext(input_grid)[1]

    if height_model != "":

        ### Récupération de la hauteur de végétation

        if debug >= 3:
            print(cyan + "computeVegetationHeight() : " + endC + bold +
                  "Récupération de la hauteur de végétation." + endC + '\n')

        if not divide_vegetation_classes:
            expression = "im1b1 == %s ? im2b1 : %s" % (vegetation_label,
                                                       no_data_value)
        else:
            expression = "im1b1 == %s or im1b1 == %s ? im2b1 : %s" % (
                high_vegetation_label, low_vegetation_label, no_data_value)

        command = "otbcli_BandMath -il %s %s -out %s %s -exp '%s'" % (
            soil_occupation, height_model, height_vegetation, codage_float,
            expression)
        if debug >= 3:
            print(command)
        exit_code = os.system(command)
        if exit_code != 0:
            raise NameError(
                cyan + "computeVegetationHeight() : " + bold + red +
                "Erreur lors de la récupération de la hauteur de végétation." +
                endC)

        ### Récupération de la hauteur moyenne de végétation

        if debug >= 3:
            print(cyan + "computeVegetationHeight() : " + endC + bold +
                  "Récupération de la hauteur moyenne de végétation." + endC +
                  '\n')

        col_to_delete_list = ["min", "median", "sum", "std", "unique", "range"]
        statisticsVectorRaster(height_vegetation, input_grid, temp_grid, 1,
                               False, False, True, col_to_delete_list, [], {},
                               path_time_log, True, format_vector,
                               save_results_intermediate, overwrite)

        renameFieldsVector(temp_grid, ['mean'], [veg_mean_field],
                           format_vector=format_vector)
        renameFieldsVector(temp_grid, ['max'], [veg_max_field],
                           format_vector=format_vector)

    else:
        print(
            cyan + "computeVegetationHeight() : " + bold + yellow +
            "Pas de calcul de l'indicateur 'hauteur moyenne de végétation' (pas de MNH en entrée)."
            + endC + '\n')
        copyVectorFile(input_grid, temp_grid, format_vector=format_vector)

    if divide_vegetation_classes:

        ### Récupération du taux de végétation haute

        if debug >= 3:
            print(cyan + "computeVegetationHeight() : " + endC + bold +
                  "Récupération du taux de végétation haute." + endC + '\n')

        sql_statement = "SELECT *, ((%s/(%s+%s))*100) AS %s FROM %s" % (
            high_vegetation_field, high_vegetation_field, low_vegetation_field,
            veg_rate_field, os.path.splitext(os.path.basename(temp_grid))[0])

        command = "ogr2ogr -sql '%s' -dialect SQLITE %s %s" % (
            sql_statement, output_grid, temp_grid)
        if debug >= 3:
            print(command)
        exit_code = os.system(command)
        if exit_code != 0:
            raise NameError(
                cyan + "computeVegetationHeight() : " + bold + red +
                "Erreur lors de la récupération du taux de végétation haute." +
                endC)

    else:
        print(
            cyan + "computeVegetationHeight() : " + bold + yellow +
            "Pas de calcul de l'indicateur 'taux de végétation haute' (pas de distinction végétation haute/basse dans l'OCS)."
            + endC + '\n')
        copyVectorFile(temp_grid, output_grid, format_vector=format_vector)

    return 0
def occupationIndicator(input_grid,
                        output_grid,
                        class_label_dico_out,
                        input_vector_classif,
                        field_classif_name,
                        input_soil_occupation,
                        input_height_model,
                        class_build_list,
                        class_road_list,
                        class_baresoil_list,
                        class_water_list,
                        class_vegetation_list,
                        class_high_vegetation_list,
                        class_low_vegetation_list,
                        epsg=2154,
                        no_data_value=0,
                        format_raster='GTiff',
                        format_vector='ESRI Shapefile',
                        extension_raster='.tif',
                        extension_vector='.shp',
                        path_time_log='',
                        save_results_intermediate=False,
                        overwrite=True):

    if debug >= 3:
        print(
            '\n' + bold + green +
            "Calcul d'indicateurs du taux de classes OCS - Variables dans la fonction :"
            + endC)
        print(cyan + "    occupationIndicator() : " + endC + "input_grid : " +
              str(input_grid) + endC)
        print(cyan + "    occupationIndicator() : " + endC + "output_grid : " +
              str(output_grid) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "class_label_dico_out : " + str(class_label_dico_out) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "input_vector_classif : " + str(input_vector_classif) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "field_classif_name : " + str(field_classif_name) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "input_soil_occupation : " + str(input_soil_occupation) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "input_height_model : " + str(input_height_model) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "class_build_list : " + str(class_build_list) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "class_road_list : " + str(class_road_list) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "class_baresoil_list : " + str(class_baresoil_list) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "class_water_list : " + str(class_water_list) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "class_vegetation_list : " + str(class_vegetation_list) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "class_high_vegetation_list : " +
              str(class_high_vegetation_list) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "class_low_vegetation_list : " + str(class_low_vegetation_list) +
              endC)
        print(cyan + "    occupationIndicator() : " + endC + "epsg : " +
              str(epsg) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "no_data_value : " + str(no_data_value) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "format_raster : " + str(format_raster) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "format_vector : " + str(format_vector) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "extension_raster : " + str(extension_raster) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "extension_vector : " + str(extension_vector) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "path_time_log : " + str(path_time_log) + endC)
        print(cyan + "    occupationIndicator() : " + endC +
              "save_results_intermediate : " + str(save_results_intermediate) +
              endC)
        print(cyan + "    occupationIndicator() : " + endC + "overwrite : " +
              str(overwrite) + endC + '\n')

    # Définition des constantes
    CODAGE_8BITS = 'uint8'
    CODAGE_FLOAT = 'float'
    NODATA_FIELD = 'nodata'

    PREFIX_S = 'S_'
    SUFFIX_TEMP = '_temp'
    SUFFIX_RASTER = '_raster'
    SUFFIX_HEIGHT = '_height'
    SUFFIX_VEGETATION = '_vegetation'

    VEG_MEAN_FIELD = 'veg_h_mean'
    VEG_MAX_FIELD = 'veg_h_max'
    VEG_RATE_FIELD = 'veg_h_rate'
    MAJ_OCS_FIELD = 'class_OCS'

    BUILT_FIELD, BUILT_LABEL = 'built', 1
    MINERAL_FIELD, MINERAL_LABEL = 'mineral', 2
    BARESOIL_FIELD, BARESOIL_LABEL = 'baresoil', 3
    WATER_FIELD, WATER_LABEL = 'water', 4
    VEGETATION_FIELD, VEGETATION_LABEL = 'veget', 5
    HIGH_VEGETATION_FIELD, HIGH_VEGETATION_LABEL = 'high_veg', 6
    LOW_VEGETATION_FIELD, LOW_VEGETATION_LABEL = 'low_veg', 7

    # Mise à jour du log
    starting_event = "occupationIndicator() : Début du traitement : "
    timeLine(path_time_log, starting_event)

    print(cyan + "occupationIndicator() : " + bold + green +
          "DEBUT DES TRAITEMENTS" + endC + '\n')

    # Définition des variables 'basename'
    output_grid_basename = os.path.basename(os.path.splitext(output_grid)[0])
    output_grid_dirname = os.path.dirname(output_grid)
    soil_occupation_basename = os.path.basename(
        os.path.splitext(input_soil_occupation)[0])

    # Définition des variables temp
    temp_directory = output_grid_dirname + os.sep + output_grid_basename
    temp_grid = temp_directory + os.sep + output_grid_basename + SUFFIX_TEMP + extension_vector
    temp_soil_occupation = temp_directory + os.sep + soil_occupation_basename + SUFFIX_TEMP + SUFFIX_RASTER + extension_raster
    temp_height_vegetation = temp_directory + os.sep + output_grid_basename + SUFFIX_HEIGHT + SUFFIX_VEGETATION + extension_raster

    # Nettoyage des traitements précédents
    if overwrite:
        if debug >= 3:
            print(cyan + "occupationIndicator() : " + endC +
                  "Nettoyage des traitements précédents." + endC + '\n')
        removeFile(output_grid)
        cleanTempData(temp_directory)
    else:
        if os.path.exists(output_grid):
            raise NameError(
                cyan + "occupationIndicator() : " + bold + yellow +
                "Le fichier de sortie existe déjà et ne sera pas regénéré." +
                endC + '\n')
        pass

    #############
    # Etape 0/3 # Préparation des traitements
    #############

    print(cyan + "occupationIndicator() : " + bold + green +
          "ETAPE 0/3 - Début de la préparation des traitements." + endC + '\n')

    # Rasterisation de l'information de classification (OCS) si au format vecteur en entrée
    if input_vector_classif != "":
        if debug >= 3:
            print(cyan + "occupationIndicator() : " + endC + bold +
                  "Rasterisation de l'OCS vecteur." + endC + '\n')
        reference_image = input_soil_occupation
        soil_occupation_vector_basename = os.path.basename(
            os.path.splitext(input_vector_classif)[0])
        input_soil_occupation = temp_directory + os.sep + soil_occupation_vector_basename + SUFFIX_RASTER + extension_raster
        command = "otbcli_Rasterization -in %s -out %s %s -im %s -background 0 -mode attribute -mode.attribute.field %s" % (
            input_vector_classif, input_soil_occupation, CODAGE_8BITS,
            reference_image, field_classif_name)
        if debug >= 3:
            print(command)
        exit_code = os.system(command)
        if exit_code != 0:
            raise NameError(
                cyan + "occupationIndicator() : " + bold + red +
                "Erreur lors de la rasterisation de l'OCS vecteur." + endC)

    # Analyse de la couche OCS raster
    class_other_list = identifyPixelValues(input_soil_occupation)
    no_data_ocs = getNodataValueImage(input_soil_occupation, 1)
    if no_data_ocs != None:
        no_data_value = no_data_ocs

    # Affectation de nouveaux codes de classification
    divide_vegetation_classes = False
    if class_high_vegetation_list != [] and class_low_vegetation_list != []:
        divide_vegetation_classes = True

    col_to_delete_list = [
        "minority", PREFIX_S + NODATA_FIELD, PREFIX_S + BUILT_FIELD,
        PREFIX_S + MINERAL_FIELD, PREFIX_S + BARESOIL_FIELD,
        PREFIX_S + WATER_FIELD
    ]
    class_label_dico = {
        int(no_data_value): NODATA_FIELD,
        int(BUILT_LABEL): BUILT_FIELD,
        int(MINERAL_LABEL): MINERAL_FIELD,
        int(BARESOIL_LABEL): BARESOIL_FIELD,
        int(WATER_LABEL): WATER_FIELD
    }
    if not divide_vegetation_classes:
        class_label_dico[int(VEGETATION_LABEL)] = VEGETATION_FIELD
        col_to_delete_list.append(PREFIX_S + VEGETATION_FIELD)
    else:
        class_label_dico[int(HIGH_VEGETATION_LABEL)] = HIGH_VEGETATION_FIELD
        class_label_dico[int(LOW_VEGETATION_LABEL)] = LOW_VEGETATION_FIELD
        col_to_delete_list.append(PREFIX_S + HIGH_VEGETATION_FIELD)
        col_to_delete_list.append(PREFIX_S + LOW_VEGETATION_FIELD)

    # Gestion de la réaffectation des classes
    if debug >= 3:
        print(cyan + "occupationIndicator() : " + endC + bold +
              "Reaffectation du raster OCS." + endC + '\n')

    reaff_class_list = []
    macro_reaff_class_list = []

    for label in class_build_list:
        if label in class_other_list:
            class_other_list.remove(label)
        reaff_class_list.append(label)
        macro_reaff_class_list.append(BUILT_LABEL)

    for label in class_road_list:
        if label in class_other_list:
            class_other_list.remove(label)
        reaff_class_list.append(label)
        macro_reaff_class_list.append(MINERAL_LABEL)

    for label in class_baresoil_list:
        if label in class_other_list:
            class_other_list.remove(label)
        reaff_class_list.append(label)
        macro_reaff_class_list.append(BARESOIL_LABEL)

    for label in class_water_list:
        if label in class_other_list:
            class_other_list.remove(label)
        reaff_class_list.append(label)
        macro_reaff_class_list.append(WATER_LABEL)

    if not divide_vegetation_classes:
        for label in class_vegetation_list:
            if label in class_other_list:
                class_other_list.remove(label)
            reaff_class_list.append(label)
            macro_reaff_class_list.append(VEGETATION_LABEL)
    else:
        for label in class_high_vegetation_list:
            if label in class_other_list:
                class_other_list.remove(label)
            reaff_class_list.append(label)
            macro_reaff_class_list.append(HIGH_VEGETATION_LABEL)
        for label in class_low_vegetation_list:
            if label in class_other_list:
                class_other_list.remove(label)
            reaff_class_list.append(label)
            macro_reaff_class_list.append(LOW_VEGETATION_LABEL)

    # Reste des valeurs de pixel nom utilisé
    for label in class_other_list:
        reaff_class_list.append(label)
        macro_reaff_class_list.append(no_data_value)

    reallocateClassRaster(input_soil_occupation, temp_soil_occupation,
                          reaff_class_list, macro_reaff_class_list,
                          CODAGE_8BITS)

    print(cyan + "occupationIndicator() : " + bold + green +
          "ETAPE 0/3 - Fin de la préparation des traitements." + endC + '\n')

    #############
    # Etape 1/3 # Calcul des indicateurs de taux de classes OCS
    #############

    print(
        cyan + "occupationIndicator() : " + bold + green +
        "ETAPE 1/3 - Début du calcul des indicateurs de taux de classes OCS." +
        endC + '\n')

    if debug >= 3:
        print(cyan + "occupationIndicator() : " + endC + bold +
              "Calcul des indicateurs de taux de classes OCS." + endC + '\n')

    statisticsVectorRaster(temp_soil_occupation, input_grid, temp_grid, 1,
                           True, True, False, col_to_delete_list, [],
                           class_label_dico, path_time_log, True,
                           format_vector, save_results_intermediate, overwrite)

    # Fusion des classes végétation dans le cas où haute et basse sont séparées (pour utilisation du taux de végétation dans le logigramme)
    if divide_vegetation_classes:
        temp_grid_v2 = os.path.splitext(
            temp_grid)[0] + "_v2" + extension_vector
        sql_statement = "SELECT *, (%s + %s) AS %s FROM %s" % (
            HIGH_VEGETATION_FIELD, LOW_VEGETATION_FIELD, VEGETATION_FIELD,
            os.path.splitext(os.path.basename(temp_grid))[0])
        os.system("ogr2ogr -sql '%s' -dialect SQLITE %s %s" %
                  (sql_statement, temp_grid_v2, temp_grid))
        removeVectorFile(temp_grid, format_vector=format_vector)
        copyVectorFile(temp_grid_v2, temp_grid, format_vector=format_vector)

    print(cyan + "occupationIndicator() : " + bold + green +
          "ETAPE 1/3 - Fin du calcul des indicateurs de taux de classes OCS." +
          endC + '\n')

    #############
    # Etape 2/3 # Calcul de l'indicateur de "hauteur de végétation"
    #############

    print(
        cyan + "occupationIndicator() : " + bold + green +
        "ETAPE 2/3 - Début du calcul de l'indicateur de \"hauteur de végétation\"."
        + endC + '\n')

    computeVegetationHeight(
        temp_grid, output_grid, temp_soil_occupation, input_height_model,
        temp_height_vegetation, divide_vegetation_classes, VEGETATION_LABEL,
        HIGH_VEGETATION_LABEL, LOW_VEGETATION_LABEL, HIGH_VEGETATION_FIELD,
        LOW_VEGETATION_FIELD, VEG_MEAN_FIELD, VEG_MAX_FIELD, VEG_RATE_FIELD,
        CODAGE_FLOAT, SUFFIX_TEMP, no_data_value, format_vector, path_time_log,
        save_results_intermediate, overwrite)

    print(
        cyan + "occupationIndicator() : " + bold + green +
        "ETAPE 2/3 - Fin du calcul de l'indicateur de \"hauteur de végétation\"."
        + endC + '\n')

    #############
    # Etape 3/3 # Calcul de l'indicateur de classe majoritaire
    #############

    print(
        cyan + "occupationIndicator() : " + bold + green +
        "ETAPE 3/3 - Début du calcul de l'indicateur de classe majoritaire." +
        endC + '\n')

    if input_height_model != "":
        computeMajorityClass(output_grid, temp_directory, NODATA_FIELD,
                             BUILT_FIELD, MINERAL_FIELD, BARESOIL_FIELD,
                             WATER_FIELD, VEGETATION_FIELD,
                             HIGH_VEGETATION_FIELD, LOW_VEGETATION_FIELD,
                             MAJ_OCS_FIELD, VEG_MEAN_FIELD,
                             class_label_dico_out, format_vector,
                             extension_vector, overwrite)
    else:
        print(
            cyan + "occupationIndicator() : " + bold + yellow +
            "Pas de calcul de l'indicateur de classe majoritaire demandé (pas de MNH en entrée)."
            + endC + '\n')

    print(cyan + "occupationIndicator() : " + bold + green +
          "ETAPE 3/3 - Fin du calcul de l'indicateur de classe majoritaire." +
          endC + '\n')

    ####################################################################

    # Suppression des fichiers temporaires
    if not save_results_intermediate:
        if debug >= 3:
            print(cyan + "occupationIndicator() : " + endC +
                  "Suppression des fichiers temporaires." + endC + '\n')
        deleteDir(temp_directory)

    print(cyan + "occupationIndicator() : " + bold + green +
          "FIN DES TRAITEMENTS" + endC + '\n')

    # Mise à jour du log
    ending_event = "occupationIndicator() : Fin du traitement : "
    timeLine(path_time_log, ending_event)

    return 0
コード例 #5
0
def computeRoughnessByOcsMnh( grid_input, grid_output, mnh_input, classif_input, class_build_list, epsg, no_data_value, path_time_log, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True):

    # Constante
    FIELD_H_TYPE = ogr.OFTReal
    FIELD_ID_TYPE = ogr.OFTInteger
    FIELD_NAME_HSUM = "sum_h"
    FIELD_NAME_HRE = "mean_h"
    FIELD_NAME_AREA = "nb_area"
    FIELD_NAME_ID = "id"

    SUFFIX_HEIGHT = '_hauteur'
    SUFFIX_BUILT = '_bati'
    SUFFIX_TEMP = '_temp'
    SUFFIX_MASK = '_mask'

    # Mise à jour du Log
    timeLine(path_time_log, "Début du calcul de l'indicateur Height of Roughness Elements par OCS et MNT starting : ")
    print(cyan + "computeRoughnessByOcsMnh() : " + endC + "Début du calcul de l'indicateur Height of Roughness Elements par OCS et MNT." + endC + "\n")

    if debug >= 3:
        print(bold + green + "computeRoughnessByOcsMnh() : Variables dans la fonction" + endC)
        print(cyan + "computeRoughnessByOcsMnh() : " + endC + "grid_input : " + str(grid_input) + endC)
        print(cyan + "computeRoughnessByOcsMnh() : " + endC + "grid_output : " + str(grid_output) + endC)
        print(cyan + "computeRoughnessByOcsMnh() : " + endC + "mnh_input : " + str(mnh_input) + endC)
        print(cyan + "computeRoughnessByOcsMnh() : " + endC + "classif_input : " + str(classif_input) + endC)
        print(cyan + "computeRoughnessByOcsMnh() : " + endC + "class_build_list : " + str(class_build_list) + endC)
        print(cyan + "computeRoughnessByOcsMnh() : " + endC + "epsg : " + str(epsg) + endC)
        print(cyan + "computeRoughnessByOcsMnh() : " + endC + "no_data_value : " + str(no_data_value) + endC)
        print(cyan + "computeRoughnessByOcsMnh() : " + endC + "path_time_log : " + str(path_time_log) + endC)
        print(cyan + "computeRoughnessByOcsMnh() : " + endC + "format_vector : " + str(format_vector) + endC)
        print(cyan + "computeRoughnessByOcsMnh() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC)
        print(cyan + "computeRoughnessByOcsMnh() : " + endC + "overwrite : " + str(overwrite) + endC)

    # Test si le vecteur de sortie existe déjà et si il doit être écrasés
    check = os.path.isfile(grid_output)

    if check and not overwrite: # Si le fichier de sortie existent deja et que overwrite n'est pas activé
        print(cyan + "computeRoughnessByOcsMnh() : " + bold + yellow + "Le calcul de Roughness par OCS et MNT a déjà eu lieu." + endC + "\n")
        print(cyan + "computeRoughnessByOcsMnh() : " + bold + yellow + "Grid vector output : " + grid_output + " already exists and will not be created again." + endC)
    else :
        if check:
            try:
                removeVectorFile(grid_output)
            except Exception:
                pass # si le fichier n'existe pas, il ne peut pas être supprimé : cette étape est ignorée

        ############################################
        ### Préparation générale des traitements ###
        ############################################

        # Récuperation de la projection de l'image
        epsg_proj = getProjectionImage(classif_input)
        if epsg_proj == 0:
            epsg_proj = epsg

        # Préparation des fichiers temporaires
        temp_path = os.path.dirname(grid_output) + os.sep + "RoughnessByOcsAndMnh"

        # Nettoyage du repertoire temporaire si il existe
        if os.path.exists(temp_path):
            shutil.rmtree(temp_path)
        os.makedirs(temp_path)

        basename = os.path.splitext(os.path.basename(grid_output))[0]
        built_height = temp_path + os.sep + basename + SUFFIX_HEIGHT + SUFFIX_BUILT + extension_raster
        built_height_temp = temp_path + os.sep + basename + SUFFIX_HEIGHT + SUFFIX_BUILT + SUFFIX_TEMP + extension_raster
        classif_built_mask = temp_path + os.sep + basename + SUFFIX_BUILT + SUFFIX_MASK + extension_raster
        grid_output_temp = temp_path + os.sep + basename + SUFFIX_TEMP + extension_vector

        ##############################
        ### Calcul de l'indicateur ###
        ##############################

        # liste des classes de bati a prendre en compte dans l'expression du BandMath
        expression_bati = ""
        for id_class in class_build_list :
            expression_bati += "im1b1==%s or " %(str(id_class))
        expression_bati = expression_bati[:-4]
        expression = "(%s) and (im2b1!=%s) and (im2b1>0)" %(expression_bati, str(no_data_value))

        # Creation d'un masque vecteur des batis pour la surface des zones baties
        command = "otbcli_BandMath -il %s %s -out %s uint8 -exp '%s ? 1 : 0'" %(classif_input, mnh_input, classif_built_mask, expression)
        if debug >= 3:
            print(command)
        exit_code = os.system(command)
        if exit_code != 0:
            print(command)
            print(cyan + "computeRoughnessByOcsMnh() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : " + command + ". Voir message d'erreur." + endC, file=sys.stderr)
            raise

        # Récupération de la hauteur du bati
        command = "otbcli_BandMath -il %s %s -out %s float -exp '%s ? im2b1 : 0'" %(classif_input, mnh_input, built_height_temp, expression)
        if debug >= 3:
            print(command)
        exit_code = os.system(command)
        if exit_code != 0:
            print(command)
            print(cyan + "computeRoughnessByOcsMnh() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : " + command + ". Voir message d'erreur." + endC, file=sys.stderr)
            raise

        command = "gdal_translate -a_srs EPSG:%s -a_nodata %s -of %s %s %s" %(str(epsg_proj), str(no_data_value), format_raster, built_height_temp, built_height)
        if debug >= 3:
            print(command)
        exit_code = os.system(command)
        if exit_code != 0:
            print(command)
            print(cyan + "computeRoughnessByOcsMnh() : " + bold + red + "!!! Une erreur c'est produite au cours de la comande : gdal_translate : " + command + ". Voir message d'erreur." + endC, file=sys.stderr)
            raise

        # Récupération du nombre de pixel bati de chaque maille pour definir la surface
        statisticsVectorRaster(classif_built_mask, grid_input, grid_output_temp, 1, False, False, True, ["min", "max", "median", "mean", "std", "unique", "range"], [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite)

        # Renomer le champ 'sum' en FIELD_NAME_AREA
        renameFieldsVector(grid_output_temp, ['sum'], [FIELD_NAME_AREA], format_vector)

        # Récupération de la hauteur moyenne du bati de chaque maille
        statisticsVectorRaster(built_height, grid_output_temp, grid_output, 1, False, False, True, ["min", "max", "median", 'mean', "std", "unique", "range"], [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite)

        # Renomer le champ 'mean' en FIELD_NAME_HRE
        renameFieldsVector(grid_output, ['sum'], [FIELD_NAME_HSUM], format_vector)

        # Calcul de la colonne FIELD_NAME_HRE division de FIELD_NAME_HSUM par FIELD_NAME_AREA
        field_values_list = getAttributeValues(grid_output, None, None, {FIELD_NAME_ID:FIELD_ID_TYPE, FIELD_NAME_HSUM:FIELD_H_TYPE, FIELD_NAME_AREA:FIELD_H_TYPE}, format_vector)

        field_new_values_list = []
        for index in range(0, len(field_values_list[FIELD_NAME_ID])) :
            value_h = 0.0
            if field_values_list[FIELD_NAME_AREA][index] > 0 :
                value_h = field_values_list[FIELD_NAME_HSUM][index] / field_values_list[FIELD_NAME_AREA][index]
            field_new_values_list.append({FIELD_NAME_HRE:value_h})

        # Ajour de la nouvelle colonne calculé FIELD_NAME_HRE
        addNewFieldVector(grid_output, FIELD_NAME_HRE, FIELD_H_TYPE, 0, None, None, format_vector)
        setAttributeValuesList(grid_output, field_new_values_list, format_vector)

        ##########################################
        ### Nettoyage des fichiers temporaires ###
        ##########################################
        if not save_results_intermediate:
            if os.path.exists(temp_path):
                shutil.rmtree(temp_path)

    print(cyan + "computeRoughnessByOcsMnh() : " + endC + "Fin du calcul de l'indicateur Height of Roughness Elements par OCS et MNT." + endC + "\n")
    timeLine(path_time_log, "Fin du calcul de l'indicateur Height of Roughness Elements par OCS et MNT  ending : ")

    return
コード例 #6
0
def createMnh(image_mns_input, image_mnt_input, image_threshold_input, vector_emprise_input, image_mnh_output, automatic, bd_road_vector_input_list, bd_road_buff_list, sql_road_expression_list, bd_build_vector_input_list, height_bias, threshold_bd_value, threshold_delta_h, mode_interpolation, method_interpolation, interpolation_bco_radius, simplify_vector_param, epsg, no_data_value, ram_otb, path_time_log, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True):

    # Mise à jour du Log
    starting_event = "createMnh() : MNH creation starting : "
    timeLine(path_time_log,starting_event)

    print(endC)
    print(bold + green + "## START : MNH CREATION" + endC)
    print(endC)

    if debug >= 2:
        print(bold + green + "createMnh() : Variables dans la fonction" + endC)
        print(cyan + "createMnh() : " + endC + "image_mns_input : " + str(image_mns_input) + endC)
        print(cyan + "createMnh() : " + endC + "image_mnt_input : " + str(image_mnt_input) + endC)
        print(cyan + "createMnh() : " + endC + "image_threshold_input : " + str(image_threshold_input) + endC)
        print(cyan + "createMnh() : " + endC + "vector_emprise_input : " + str(vector_emprise_input) + endC)
        print(cyan + "createMnh() : " + endC + "image_mnh_output : " + str(image_mnh_output) + endC)
        print(cyan + "createMnh() : " + endC + "automatic : " + str(automatic) + endC)
        print(cyan + "createMnh() : " + endC + "bd_road_vector_input_list : " + str(bd_road_vector_input_list) + endC)
        print(cyan + "createMnh() : " + endC + "bd_road_buff_list : " + str(bd_road_buff_list) + endC)
        print(cyan + "createMnh() : " + endC + "sql_road_expression_list : " + str(sql_road_expression_list) + endC)
        print(cyan + "createMnh() : " + endC + "bd_build_vector_input_list : " + str(bd_build_vector_input_list) + endC)
        print(cyan + "createMnh() : " + endC + "height_bias : " + str(height_bias) + endC)
        print(cyan + "createMnh() : " + endC + "threshold_bd_value : " + str(threshold_bd_value) + endC)
        print(cyan + "createMnh() : " + endC + "threshold_delta_h : " + str(threshold_delta_h) + endC)
        print(cyan + "createMnh() : " + endC + "mode_interpolation : " + str(mode_interpolation) + endC)
        print(cyan + "createMnh() : " + endC + "method_interpolation : " + str(method_interpolation) + endC)
        print(cyan + "createMnh() : " + endC + "interpolation_bco_radius : " + str(interpolation_bco_radius) + endC)
        print(cyan + "createMnh() : " + endC + "simplify_vector_param : " + str(simplify_vector_param) + endC)
        print(cyan + "createMnh() : " + endC + "epsg : " + str(epsg) + endC)
        print(cyan + "createMnh() : " + endC + "no_data_value : " + str(no_data_value) + endC)
        print(cyan + "createMnh() : " + endC + "ram_otb : " + str(ram_otb) + endC)
        print(cyan + "createMnh() : " + endC + "path_time_log : " + str(path_time_log) + endC)
        print(cyan + "createMnh() : " + endC + "format_raster : " + str(format_raster) + endC)
        print(cyan + "createMnh() : " + endC + "format_vector : " + str(format_vector) + endC)
        print(cyan + "createMnh() : " + endC + "extension_raster : " + str(extension_raster) + endC)
        print(cyan + "createMnh() : " + endC + "extension_vector : " + str(extension_vector) + endC)
        print(cyan + "createMnh() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC)
        print(cyan + "createMnh() : " + endC + "overwrite : " + str(overwrite) + endC)

    # LES CONSTANTES
    PRECISION = 0.0000001

    CODAGE_8B = "uint8"
    CODAGE_F = "float"

    SUFFIX_CUT = "_cut"
    SUFFIX_CLEAN = "_clean"
    SUFFIX_SAMPLE = "_sample"
    SUFFIX_MASK = "_mask"
    SUFFIX_TMP = "_tmp"
    SUFFIX_MNS = "_mns"
    SUFFIX_MNT = "_mnt"
    SUFFIX_ROAD = "_road"
    SUFFIX_BUILD = "_build"
    SUFFIX_RASTER = "_raster"
    SUFFIX_VECTOR = "_vector"

    # DEFINIR LES REPERTOIRES ET FICHIERS TEMPORAIRES
    repertory_output = os.path.dirname(image_mnh_output)
    basename_mnh = os.path.splitext(os.path.basename(image_mnh_output))[0]

    sub_repertory_raster_temp = repertory_output + os.sep + basename_mnh + SUFFIX_RASTER + SUFFIX_TMP
    sub_repertory_vector_temp = repertory_output + os.sep + basename_mnh + SUFFIX_VECTOR + SUFFIX_TMP
    cleanTempData(sub_repertory_raster_temp)
    cleanTempData(sub_repertory_vector_temp)

    basename_vector_emprise = os.path.splitext(os.path.basename(vector_emprise_input))[0]
    basename_mns_input = os.path.splitext(os.path.basename(image_mns_input))[0]
    basename_mnt_input = os.path.splitext(os.path.basename(image_mnt_input))[0]

    image_mnh_tmp = sub_repertory_raster_temp + os.sep + basename_mnh + SUFFIX_TMP + extension_raster
    image_mnh_road = sub_repertory_raster_temp + os.sep + basename_mnh + SUFFIX_ROAD + extension_raster

    vector_bd_bati_temp = sub_repertory_vector_temp + os.sep + basename_mnh + SUFFIX_BUILD + SUFFIX_TMP + extension_vector
    vector_bd_bati = repertory_output + os.sep + basename_mnh + SUFFIX_BUILD + extension_vector
    raster_bd_bati = sub_repertory_vector_temp + os.sep + basename_mnh + SUFFIX_BUILD + extension_raster
    removeVectorFile(vector_bd_bati)

    image_emprise_mnt_mask = sub_repertory_raster_temp + os.sep + basename_vector_emprise + SUFFIX_MNT + extension_raster
    image_mnt_cut = sub_repertory_raster_temp + os.sep + basename_mnt_input + SUFFIX_CUT + extension_raster
    image_mnt_clean = sub_repertory_raster_temp + os.sep + basename_mnt_input + SUFFIX_CLEAN + extension_raster
    image_mnt_clean_sample = sub_repertory_raster_temp + os.sep + basename_mnt_input + SUFFIX_CLEAN + SUFFIX_SAMPLE + extension_raster
    image_emprise_mns_mask = sub_repertory_raster_temp + os.sep + basename_vector_emprise + SUFFIX_MNS + extension_raster
    image_mns_cut = sub_repertory_raster_temp + os.sep + basename_mns_input + SUFFIX_CUT + extension_raster
    image_mns_clean = sub_repertory_raster_temp + os.sep + basename_mns_input + SUFFIX_CLEAN + extension_raster

    vector_bd_road_temp = sub_repertory_vector_temp + os.sep + basename_mnh + SUFFIX_ROAD + SUFFIX_TMP + extension_vector
    raster_bd_road_mask = sub_repertory_raster_temp + os.sep + basename_mnh + SUFFIX_ROAD + SUFFIX_MASK + extension_raster

    if image_threshold_input != "" :
        basename_threshold_input = os.path.splitext(os.path.basename(image_threshold_input))[0]
        image_threshold_cut = sub_repertory_raster_temp + os.sep + basename_threshold_input + SUFFIX_CUT + extension_raster
        image_threshold_mask = sub_repertory_raster_temp + os.sep + basename_threshold_input + SUFFIX_MASK + extension_raster

    # VERIFICATION SI LE FICHIER DE SORTIE EXISTE DEJA
    # Si un fichier de sortie avec le même nom existe déjà, et si l'option ecrasement est à false, alors on ne fait rien
    check = os.path.isfile(image_mnh_output)
    if check and not overwrite:
        print(bold + yellow +  "createMnh() : " + endC + "Create mnh %s from %s and %s already done : no actualisation" % (image_mnh_output, image_mns_input, image_mnt_input) + endC)
    # Si non, ou si la fonction ecrasement est désative, alors on le calcule
    else:
        if check:
            try: # Suppression de l'éventuel fichier existant
                removeFile(image_mnh_output)
            except Exception:
                pass # Si le fichier ne peut pas être supprimé, on suppose qu'il n'existe pas et on passe à la suite

        # DECOUPAGE DES FICHIERS MS ET MNT D'ENTREE PAR LE FICHIER D'EMPRISE
        if debug >= 3:
            print(bold + green +  "createMnh() : " + endC + "Decoupage selon l'emprise des fichiers %s et %s " %(image_mns_input, image_mnt_input) + endC)

        # Fonction de découpe du mns
        if not cutImageByVector(vector_emprise_input, image_mns_input, image_mns_cut, None, None, no_data_value, epsg, format_raster, format_vector) :
            raise NameError (cyan + "createMnh() : " + bold + red + "!!! Une erreur c'est produite au cours du decoupage de l'image : " + image_mns_input + ". Voir message d'erreur." + endC)

        # Fonction de découpe du mnt
        if not cutImageByVector(vector_emprise_input, image_mnt_input, image_mnt_cut, None, None, no_data_value, epsg, format_raster, format_vector) :
            raise NameError (cyan + "createMnh() : " + bold + red + "!!! Une erreur c'est produite au cours du decoupage de l'image : " + image_mnt_input + ". Voir message d'erreur." + endC)

        if debug >= 3:
            print(bold + green +  "createMnh() : " + endC + "Decoupage des fichiers %s et %s complet" %(image_mns_cut, image_mnt_cut) + endC)


        # REBOUCHAGE DES TROUS DANS LE MNT D'ENTREE SI NECESSAIRE

        nodata_mnt = getNodataValueImage(image_mnt_cut)
        pixelNodataCount = countPixelsOfValue(image_mnt_cut, nodata_mnt)

        if pixelNodataCount > 0 :

            if debug >= 3:
                print(bold + green +  "createMnh() : " + endC + "Fill the holes MNT for  %s" %(image_mnt_cut) + endC)

            # Rasterisation du vecteur d'emprise pour creer un masque pour boucher les trous du MNT
            rasterizeBinaryVector(vector_emprise_input, image_mnt_cut, image_emprise_mnt_mask, 1, CODAGE_8B)

            # Utilisation de SAGA pour boucher les trous
            fillNodata(image_mnt_cut, image_emprise_mnt_mask, image_mnt_clean, save_results_intermediate)

            if debug >= 3:
                print(bold + green +  "createMnh() : " + endC + "Fill the holes MNT to %s completed" %(image_mnt_clean) + endC)

        else :
            image_mnt_clean = image_mnt_cut
            if debug >= 3:
                print(bold + green +  "\ncreateMnh() : " + endC + "Fill the holes not necessary MNT for %s" %(image_mnt_cut) + endC)


        # REBOUCHAGE DES TROUS DANS LE MNS D'ENTREE SI NECESSAIRE

        nodata_mns = getNodataValueImage(image_mns_cut)
        pixelNodataCount = countPixelsOfValue(image_mns_cut, nodata_mns)

        if pixelNodataCount > 0 :

            if debug >= 3:
                print(bold + green +  "createMnh() : " + endC + "Fill the holes MNS for  %s" %(image_mns_cut) + endC)

            # Rasterisation du vecteur d'emprise pour creer un masque pour boucher les trous du MNS
            rasterizeBinaryVector(vector_emprise_input, image_mns_cut, image_emprise_mns_mask, 1, CODAGE_8B)

            # Utilisation de SAGA pour boucher les trous
            fillNodata(image_mns_cut, image_emprise_mns_mask, image_mns_clean, save_results_intermediate)

            if debug >= 3:
                print(bold + green +  "\ncreateMnh() : " + endC + "Fill the holes MNS to %s completed" %(image_mns_clean) + endC)

        else :
            image_mns_clean = image_mns_cut
            if debug >= 3:
                print(bold + green +  "createMnh() : " + endC + "Fill the holes not necessary MNS for %s" %(image_mns_cut) + endC)

        # CALLER LE FICHIER MNT AU FORMAT DU FICHIER MNS

        # Commande de mise en place de la geométrie re-echantionage
        command = "otbcli_Superimpose -inr " + image_mns_clean + " -inm " + image_mnt_clean + " -mode " + mode_interpolation + " -interpolator " + method_interpolation + " -out " + image_mnt_clean_sample

        if method_interpolation.lower() == 'bco' :
            command += " -interpolator.bco.radius " + str(interpolation_bco_radius)
        if ram_otb > 0:
            command += " -ram %d" %(ram_otb)

        if debug >= 3:
            print(cyan + "createMnh() : " + bold + green + "Réechantillonage du fichier %s par rapport à la reference %s" %(image_mnt_clean, image_mns_clean) + endC)
            print(command)

        exit_code = os.system(command)
        if exit_code != 0:
            print(command)
            raise NameError (cyan + "createMnh() : " + bold + red + "!!! Une erreur c'est produite au cours du superimpose de l'image : " + image_mnt_input + ". Voir message d'erreur." + endC)

        # INCRUSTATION DANS LE MNH DES DONNEES VECTEURS ROUTES

        if debug >= 3:
            print(bold + green +  "createMnh() : " + endC + "Use BD road to clean MNH"  + endC)

        # Creation d'un masque de filtrage des donnes routes (exemple : le NDVI)
        if image_threshold_input != "" :
            if not cutImageByVector(vector_emprise_input, image_threshold_input, image_threshold_cut, None, None, no_data_value, epsg, format_raster, format_vector) :
                raise NameError (cyan + "createMnh() : " + bold + red + "!!! Une erreur c'est produite au cours du decoupage de l'image : " + image_threshold_input + ". Voir message d'erreur." + endC)
            createBinaryMask(image_threshold_cut, image_threshold_mask, threshold_bd_value, False, CODAGE_8B)

        # Execution de la fonction createMacroSamples pour une image correspondant au données routes
        if bd_road_vector_input_list != [] :
            createMacroSamples(image_mns_clean, vector_emprise_input, vector_bd_road_temp, raster_bd_road_mask, bd_road_vector_input_list, bd_road_buff_list, sql_road_expression_list, path_time_log, basename_mnh, simplify_vector_param, format_vector, extension_vector, save_results_intermediate, overwrite)

        if debug >= 3:
            print(bold + green +  "\ncreateMnh() : " + endC + "File raster from BD road is create %s" %(raster_bd_road_mask) + endC)

        # CALCUL DU MNH

        # Calcul par bandMath du MNH definir l'expression qui soustrait le MNT au MNS en introduisant le biais et en mettant les valeurs à 0 à une valeur approcher de 0.0000001
        delta = ""
        if height_bias > 0 :
            delta = "+%s" %(str(height_bias))
        elif height_bias < 0 :
            delta = "-%s" %(str(abs(height_bias)))
        else :
            delta = ""

        # Definition de l'expression
        if bd_road_vector_input_list != [] :
            if image_threshold_input != "" :
                expression = "\"im3b1 > 0 and im4b1 > 0?%s:(im1b1-im2b1%s) > 0.0?im1b1-im2b1%s:%s\"" %(str(PRECISION), delta, delta, str(PRECISION))
                command = "otbcli_BandMath -il %s %s %s %s -out %s %s -exp %s" %(image_mns_clean, image_mnt_clean_sample, raster_bd_road_mask, image_threshold_mask, image_mnh_tmp, CODAGE_F, expression)
            else :
                expression = "\"im3b1 > 0?%s:(im1b1-im2b1%s) > 0.0?im1b1-im2b1%s:%s\"" %(str(PRECISION), delta, delta, str(PRECISION))
                command = "otbcli_BandMath -il %s %s %s -out %s %s -exp %s" %(image_mns_clean, image_mnt_clean_sample, raster_bd_road_mask, image_mnh_tmp, CODAGE_F, expression)
        else :
            expression = "\"(im1b1-im2b1%s) > 0.0?im1b1-im2b1%s:%s\"" %(delta, delta, str(PRECISION))
            command = "otbcli_BandMath -il %s %s -out %s %s -exp %s" %(image_mns_clean, image_mnt_clean_sample, image_mnh_tmp, CODAGE_F, expression)

        if ram_otb > 0:
            command += " -ram %d" %(ram_otb)

        if debug >= 3:
            print(cyan + "createMnh() : " + bold + green + "Calcul du MNH  %s difference du MNS : %s par le MNT :%s" %(image_mnh_tmp, image_mns_clean, image_mnt_clean_sample) + endC)
            print(command)

        exitCode = os.system(command)
        if exitCode != 0:
            print(command)
            raise NameError(cyan + "createMnh() : " + bold + red + "An error occured during otbcli_BandMath command to compute MNH " + image_mnh_tmp + ". See error message above." + endC)

        # DECOUPAGE DU MNH

        if bd_build_vector_input_list == []:
            image_mnh_road = image_mnh_output

        if debug >= 3:
            print(bold + green +  "createMnh() : " + endC + "Decoupage selon l'emprise du fichier mnh %s " %(image_mnh_tmp) + endC)

        # Fonction de découpe du mnh
        if not cutImageByVector(vector_emprise_input, image_mnh_tmp, image_mnh_road, None, None, no_data_value, epsg, format_raster, format_vector) :
            raise NameError (cyan + "createMnh() : " + bold + red + "!!! Une erreur c'est produite au cours du decoupage de l'image : " + image_mns_input + ". Voir message d'erreur." + endC)

        if debug >= 3:
            print(bold + green +  "createMnh() : " + endC + "Decoupage du fichier mnh %s complet" %(image_mnh_road) + endC)

        # INCRUSTATION DANS LE MNH DES DONNEES VECTEURS BATIS

        # Si demander => liste de fichier vecteur bati passé en donnée d'entrée
        if bd_build_vector_input_list != []:

            # Découpage des vecteurs de bd bati exogenes avec l'emprise
            vectors_build_cut_list = []
            for vector_build_input in bd_build_vector_input_list :
                vector_name = os.path.splitext(os.path.basename(vector_build_input))[0]
                vector_build_cut = sub_repertory_vector_temp + os.sep + vector_name + SUFFIX_CUT + extension_vector
                vectors_build_cut_list.append(vector_build_cut)
            cutoutVectors(vector_emprise_input, bd_build_vector_input_list, vectors_build_cut_list, format_vector)

            # Fusion des vecteurs batis découpés
            fusionVectors (vectors_build_cut_list, vector_bd_bati_temp)

            # Croisement vecteur rasteur entre le vecteur fusion des batis et le MNH créé precedement
            statisticsVectorRaster(image_mnh_road, vector_bd_bati_temp, "", 1, False, False, True, ['PREC_PLANI','PREC_ALTI','ORIGIN_BAT','median','sum','std','unique','range'], [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite)

            # Calcul de la colonne delta_H entre les hauteurs des batis et la hauteur moyenne du MNH sous le bati
            COLUMN_ID = "ID"
            COLUMN_H_BUILD = "HAUTEUR"
            COLUMN_H_BUILD_MIN = "Z_MIN"
            COLUMN_H_BUILD_MAX = "Z_MAX"
            COLUMN_H_MNH = "mean"
            COLUMN_H_MNH_MIN = "min"
            COLUMN_H_MNH_MAX = "max"
            COLUMN_H_DIFF = "H_diff"

            field_type = ogr.OFTReal
            field_value = 0.0
            field_width = 20
            field_precision = 2
            attribute_name_dico = {}
            attribute_name_dico[COLUMN_ID] = ogr.OFTString
            attribute_name_dico[COLUMN_H_BUILD] = ogr.OFTReal
            attribute_name_dico[COLUMN_H_MNH] = ogr.OFTReal

            # Ajouter la nouvelle colonne H_diff
            addNewFieldVector(vector_bd_bati_temp, COLUMN_H_DIFF, field_type, field_value, field_width, field_precision, format_vector)

            # Recuperer les valeur de hauteur du bati et du mnt dans le vecteur
            data_z_dico = getAttributeValues(vector_bd_bati_temp, None, None, attribute_name_dico, format_vector)

            # Calculer la difference des Hauteur bati et mnt
            field_new_values_dico = {}
            for index in range(len(data_z_dico[COLUMN_ID])) :
                index_polygon = data_z_dico[COLUMN_ID][index]
                delta_h = abs(data_z_dico[COLUMN_H_BUILD][index] - data_z_dico[COLUMN_H_MNH][index])
                field_new_values_dico[index_polygon] = {COLUMN_H_DIFF:delta_h}

            # Mettre à jour la colonne H_diff dans le vecteur
            setAttributeIndexValuesList(vector_bd_bati_temp, COLUMN_ID, field_new_values_dico, format_vector)

            # Suppression de tous les polygones bati dons la valeur du delat H est inferieur à threshold_delta_h
            column = "'%s, %s, %s, %s, %s, %s, %s, %s'"% (COLUMN_ID, COLUMN_H_BUILD, COLUMN_H_BUILD_MIN, COLUMN_H_BUILD_MAX, COLUMN_H_MNH, COLUMN_H_MNH_MIN, COLUMN_H_MNH_MAX, COLUMN_H_DIFF)
            expression = "%s > %s" % (COLUMN_H_DIFF, threshold_delta_h)
            filterSelectDataVector(vector_bd_bati_temp, vector_bd_bati, column, expression, overwrite, format_vector)

            # Attention!!!! PAUSE pour trie et verification des polygones bati nom deja present dans le MNH ou non
            if not automatic :
                print(bold + blue +  "Application MnhCreation => " + endC + "Vérification manuelle du vecteur bati %s pour ne concerver que les batis non présent dans le MNH courant %s" %(vector_bd_bati_temp, image_mnh_road) + endC)
                input(bold + red + "Appuyez sur entree pour continuer le programme..." + endC)

            # Creation du masque bati avec pour H la hauteur des batiments
            rasterizeVector(vector_bd_bati, raster_bd_bati, image_mnh_road, COLUMN_H_BUILD)

            # Fusion du mask des batis et du MNH temporaire
            expression = "\"im1b1 > 0.0?im1b1:im2b1\""
            command = "otbcli_BandMath -il %s %s -out %s %s -exp %s" %(raster_bd_bati, image_mnh_road, image_mnh_output, CODAGE_F, expression)

            if ram_otb > 0:
                command += " -ram %d" %(ram_otb)

            if debug >= 3:
                print(cyan + "createMnh() : " + bold + green + "Amelioration du MNH  %s ajout des hauteurs des batis %s" %(image_mnh_road, raster_bd_bati) + endC)
                print(command)

            exitCode = os.system(command)
            if exitCode != 0:
                print(command)
                raise NameError(cyan + "createMnh() : " + bold + red + "An error occured during otbcli_BandMath command to compute MNH Final" + image_mnh_output + ". See error message above." + endC)

    # SUPPRESIONS FICHIERS INTERMEDIAIRES INUTILES

    # Suppression des fichiers intermédiaires
    if not save_results_intermediate :
        if bd_build_vector_input_list != []:
            removeFile(image_mnh_road)
        removeFile(image_threshold_cut)
        removeFile(image_threshold_mask)
        removeFile(raster_bd_bati)
        removeVectorFile(vector_bd_road_temp)
        removeVectorFile(vector_bd_bati_temp)
        removeVectorFile(vector_bd_bati) # A confirmer!!!
        removeFile(raster_bd_road_mask)
        removeFile(image_mnh_tmp)
        deleteDir(sub_repertory_raster_temp)
        deleteDir(sub_repertory_vector_temp)

    print(endC)
    print(bold + green + "## END : MNH CREATION" + endC)
    print(endC)

    # Mise à jour du Log
    ending_event = "createMnh() : MNH creation ending : "
    timeLine(path_time_log,ending_event)

    return
コード例 #7
0
def skyViewFactor(grid_input,
                  grid_output,
                  mns_input,
                  classif_input,
                  class_build_list,
                  dim_grid_x,
                  dim_grid_y,
                  svf_radius,
                  svf_method,
                  svf_dlevel,
                  svf_ndirs,
                  epsg,
                  no_data_value,
                  path_time_log,
                  format_raster='GTiff',
                  format_vector='ESRI Shapefile',
                  extension_raster=".tif",
                  extension_vector=".shp",
                  save_results_intermediate=False,
                  overwrite=True):

    print(bold + yellow + "Début du calcul de l'indicateur Sky View Factor." +
          endC + "\n")
    timeLine(path_time_log,
             "Début du calcul de l'indicateur Sky View Factor : ")

    if debug >= 3:
        print(bold + green + "skyViewFactor() : Variables dans la fonction" +
              endC)
        print(cyan + "skyViewFactor() : " + endC + "grid_input : " +
              str(grid_input) + endC)
        print(cyan + "skyViewFactor() : " + endC + "grid_output : " +
              str(grid_output) + endC)
        print(cyan + "skyViewFactor() : " + endC + "mns_input : " +
              str(mns_input) + endC)
        print(cyan + "skyViewFactor() : " + endC + "class_build_list : " +
              str(class_build_list) + endC)
        print(cyan + "skyViewFactor() : " + endC + "classif_input : " +
              str(classif_input) + endC)
        print(cyan + "skyViewFactor() : " + endC + "dim_grid_x : " +
              str(dim_grid_x) + endC)
        print(cyan + "skyViewFactor() : " + endC + "dim_grid_y : " +
              str(dim_grid_y) + endC)
        print(cyan + "skyViewFactor() : " + endC + "svf_radius : " +
              str(svf_radius) + endC)
        print(cyan + "skyViewFactor() : " + endC + "svf_method : " +
              str(svf_method) + endC)
        print(cyan + "skyViewFactor() : " + endC + "svf_dlevel : " +
              str(svf_dlevel) + endC)
        print(cyan + "skyViewFactor() : " + endC + "svf_ndirs : " +
              str(svf_ndirs) + endC)
        print(cyan + "skyViewFactor() : " + endC + "epsg : " + str(epsg) +
              endC)
        print(cyan + "skyViewFactor() : " + endC + "no_data_value : " +
              str(no_data_value) + endC)
        print(cyan + "skyViewFactor() : " + endC + "path_time_log : " +
              str(path_time_log) + endC)
        print(cyan + "skyViewFactor() : " + endC + "format_raster : " +
              str(format_raster) + endC)
        print(cyan + "skyViewFactor() : " + endC + "format_vector : " +
              str(format_vector) + endC)
        print(cyan + "skyViewFactor() : " + endC + "extension_raster : " +
              str(extension_raster) + endC)
        print(cyan + "skyViewFactor() : " + endC + "extension_vector : " +
              str(extension_vector) + endC)
        print(cyan + "skyViewFactor() : " + endC +
              "save_results_intermediate : " + str(save_results_intermediate) +
              endC)
        print(cyan + "skyViewFactor() : " + endC + "overwrite : " +
              str(overwrite) + endC)

    # Constantes liées aux fichiers
    SKY_VIEW_FIELD = 'SkyView'

    BASE_FILE_TILE = 'tile_'
    BASE_FILE_POLY = 'poly_'
    SUFFIX_VECTOR_BUFF = '_buff'
    SUFFIX_VECTOR_TEMP = '_temp'

    # Constantes liées à l'arborescence
    FOLDER_SHP = 'SHP'
    FOLDER_SGRD = 'SGRD'
    FOLDER_TIF = 'TIF'
    SUB_FOLDER_DEM = 'DEM'
    SUB_FOLDER_SVF = 'SVF'
    SUB_SUB_FOLDER_BUF = 'BUF'

    if not os.path.exists(grid_output) or overwrite:

        ############################################
        ### Préparation générale des traitements ###
        ############################################

        if os.path.exists(grid_output):
            removeVectorFile(grid_output)

        temp_path = os.path.dirname(grid_output) + os.sep + "SkyViewFactor"
        sky_view_factor_raster = temp_path + os.sep + "sky_view_factor" + extension_raster

        cleanTempData(temp_path)
        os.makedirs(temp_path + os.sep + FOLDER_SHP)
        os.makedirs(temp_path + os.sep + FOLDER_SGRD + os.sep + SUB_FOLDER_DEM)
        os.makedirs(temp_path + os.sep + FOLDER_SGRD + os.sep + SUB_FOLDER_SVF)
        os.makedirs(temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_DEM)
        os.makedirs(temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF)
        os.makedirs(temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF +
                    os.sep + SUB_SUB_FOLDER_BUF)

        # Récupération de la résolution du raster d'entrée
        pixel_size_x, pixel_size_y = getPixelWidthXYImage(mns_input)
        print(bold + "Taille de pixel du fichier '%s' :" % (mns_input) + endC)
        print("    pixel_size_x = " + str(pixel_size_x))
        print("    pixel_size_y = " + str(pixel_size_y) + "\n")

        ###############################################
        ### Création des fichiers emprise et grille ###
        ###############################################

        print(bold + cyan + "Création des fichiers emprise et grille :" + endC)
        timeLine(path_time_log,
                 "    Création des fichiers emprise et grille : ")

        emprise_file = temp_path + os.sep + "emprise" + extension_vector
        quadrillage_file = temp_path + os.sep + "quadrillage" + extension_vector

        # Création du fichier d'emprise
        createVectorMask(mns_input, emprise_file, no_data_value, format_vector)

        # Création du fichier grille
        createGridVector(emprise_file, quadrillage_file, dim_grid_x,
                         dim_grid_y, None, overwrite, epsg, format_vector)

        #############################################################
        ### Extraction des carreaux de découpage et bufferisation ###
        #############################################################

        print(bold + cyan + "Extraction des carreaux de découpage :" + endC)
        timeLine(path_time_log, "    Extraction des carreaux de découpage : ")

        split_tile_vector_list = splitVector(quadrillage_file,
                                             temp_path + os.sep + FOLDER_SHP,
                                             "", epsg, format_vector,
                                             extension_vector)

        split_tile_vector_buff_list = []

        # Boucle sur les fichiers polygones quadrillage
        for split_tile_vector in split_tile_vector_list:
            repertory_temp_output = os.path.dirname(split_tile_vector)
            base_name = os.path.splitext(
                os.path.basename(split_tile_vector))[0]
            split_tile_buff_vector = repertory_temp_output + os.sep + base_name + SUFFIX_VECTOR_BUFF + extension_vector
            split_tile_buff_vector_temp = repertory_temp_output + os.sep + base_name + SUFFIX_VECTOR_BUFF + SUFFIX_VECTOR_TEMP + extension_vector

            # Bufferisation
            bufferVector(split_tile_vector, split_tile_buff_vector_temp,
                         svf_radius, "", 1.0, 10, format_vector)

            # Re-découpage avec l'emprise si la taille intersecte avec l'emprise
            if cutVector(emprise_file, split_tile_buff_vector_temp,
                         split_tile_buff_vector, overwrite, format_vector):
                split_tile_vector_buff_list.append(split_tile_buff_vector)

        ##########################################################
        ### Découpage du MNS/MNH à l'emprise de chaque carreau ###
        ##########################################################

        print(bold + cyan + "Découpage du raster en tuiles :" + endC)
        timeLine(path_time_log, "    Découpage du raster en tuiles : ")

        # Boucle sur les fichiers polygones quadrillage bufferisés
        for i in range(len(split_tile_vector_list)):
            print("Traitement de la tuile " + str(int(i) + 1) +
                  str(len(split_tile_vector_list)) + "...")

            split_tile_vector = split_tile_vector_list[i]
            repertory_temp_output = os.path.dirname(split_tile_vector)
            base_name = os.path.splitext(
                os.path.basename(split_tile_vector))[0]
            split_tile_buff_vector = repertory_temp_output + os.sep + base_name + SUFFIX_VECTOR_BUFF + extension_vector
            dem_tif_file = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_DEM + os.sep + BASE_FILE_TILE + str(
                i) + extension_raster

            if os.path.exists(split_tile_buff_vector):
                cutImageByVector(split_tile_buff_vector, mns_input,
                                 dem_tif_file, pixel_size_x, pixel_size_y,
                                 no_data_value, epsg, format_raster,
                                 format_vector)

        ##################################################
        ### Calcul du SVF pour chaque dalle du MNS/MNH ###
        ##################################################

        print(bold + cyan + "Calcul du SVF pour chaque tuile via SAGA :" +
              endC)
        timeLine(path_time_log,
                 "    Calcul du SVF pour chaque tuile via SAGA : ")

        svf_buf_tif_file_list = []

        # Boucle sur les tuiles du raster d'entrée créées par chaque polygone quadrillage
        for i in range(len(split_tile_vector_list)):
            # Calcul de Sky View Factor par SAGA
            dem_tif_file = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_DEM + os.sep + BASE_FILE_TILE + str(
                i) + extension_raster
            svf_buf_tif_file = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF + os.sep + SUB_SUB_FOLDER_BUF + os.sep + BASE_FILE_TILE + str(
                i) + extension_raster

            if os.path.exists(dem_tif_file):
                computeSkyViewFactor(dem_tif_file, svf_buf_tif_file,
                                     svf_radius, svf_method, svf_dlevel,
                                     svf_ndirs, save_results_intermediate)
                svf_buf_tif_file_list.append(svf_buf_tif_file)

        ###################################################################
        ### Re-découpage des tuiles du SVF avec les tuilles sans tampon ###
        ###################################################################

        print(bold + cyan +
              "Re-découpage des tuiles du SVF avec les tuilles sans tampon :" +
              endC)
        timeLine(
            path_time_log,
            "    Re-découpage des tuiles du SVF avec les tuilles sans tampon : "
        )

        folder_output_svf = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF + os.sep

        # Boucle sur les tuiles du SVF bufferisées
        for i in range(len(split_tile_vector_list)):
            print("Traitement de la tuile " + str(int(i) + 1) + "/" +
                  str(len(split_tile_vector_list)) + "...")

            split_tile_vector = split_tile_vector_list[i]
            svf_buf_tif_file = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF + os.sep + SUB_SUB_FOLDER_BUF + os.sep + BASE_FILE_TILE + str(
                i) + extension_raster
            base_name = os.path.splitext(os.path.basename(svf_buf_tif_file))[0]
            svf_tif_file = folder_output_svf + os.sep + base_name + extension_raster
            if os.path.exists(svf_buf_tif_file):
                cutImageByVector(split_tile_vector, svf_buf_tif_file,
                                 svf_tif_file, pixel_size_x, pixel_size_y,
                                 no_data_value, epsg, format_raster,
                                 format_vector)

        ####################################################################
        ### Assemblage des tuiles du SVF et calcul de l'indicateur final ###
        ####################################################################

        print(
            bold + cyan +
            "Assemblage des tuiles du SVF et calcul de l'indicateur final :" +
            endC)
        timeLine(
            path_time_log,
            "    Assemblage des tuiles du SVF et calcul de l'indicateur final : "
        )

        classif_input_temp = temp_path + os.sep + FOLDER_TIF + os.sep + "classif_input" + SUFFIX_VECTOR_TEMP + extension_raster
        sky_view_factor_temp = temp_path + os.sep + FOLDER_TIF + os.sep + "sky_view_factor" + SUFFIX_VECTOR_TEMP + extension_raster  # Issu de l'assemblage des dalles
        sky_view_factor_temp_temp = temp_path + os.sep + FOLDER_TIF + os.sep + "sky_view_factor" + SUFFIX_VECTOR_TEMP + SUFFIX_VECTOR_TEMP + extension_raster  # Issu du redécoupage pour entrer correctement dans le BandMath
        sky_view_factor_temp_temp_temp = temp_path + os.sep + FOLDER_TIF + os.sep + "sky_view_factor" + SUFFIX_VECTOR_TEMP + SUFFIX_VECTOR_TEMP + SUFFIX_VECTOR_TEMP + extension_raster  # Issu de la suppression des pixels bâti

        # Assemblage des tuiles du SVF créées précédemment pour ne former qu'un seul raster SVF
        selectAssembyImagesByHold(
            emprise_file, [folder_output_svf], sky_view_factor_temp, False,
            False, epsg, False, False, False, False, 1.0, pixel_size_x,
            pixel_size_y, no_data_value, "_", 2, 8, "", path_time_log,
            "_error", "_merge", "_clean", "_stack", format_raster,
            format_vector, extension_raster, extension_vector,
            save_results_intermediate, overwrite)

        # Suppression des valeurs de SVF pour les bâtiments
        cutImageByVector(emprise_file, classif_input, classif_input_temp,
                         pixel_size_x, pixel_size_y, no_data_value, epsg,
                         format_raster, format_vector)
        cutImageByVector(emprise_file, sky_view_factor_temp,
                         sky_view_factor_temp_temp, pixel_size_x, pixel_size_y,
                         no_data_value, epsg, format_raster, format_vector)

        expression = ""
        for id_class in class_build_list:
            expression += "im1b1==%s or " % (str(id_class))
        expression = expression[:-4]
        command = "otbcli_BandMath -il %s %s -out %s float -exp '%s ? -1 : im2b1'" % (
            classif_input_temp, sky_view_factor_temp_temp,
            sky_view_factor_temp_temp_temp, expression)
        if debug >= 3:
            print(command)
        exit_code = os.system(command)
        if exit_code != 0:
            print(command)
            print(
                cyan + "skyViewFactor() : " + bold + red +
                "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : "
                + command + ". Voir message d'erreur." + endC,
                file=sys.stderr)
            raise

        command = "gdal_translate -a_srs EPSG:%s -a_nodata %s -of %s %s %s" % (
            str(epsg), str(no_data_value), format_raster,
            sky_view_factor_temp_temp_temp, sky_view_factor_raster)
        if debug >= 3:
            print(command)
        exit_code = os.system(command)
        if exit_code != 0:
            print(command)
            print(
                cyan + "skyViewFactor() : " + bold + red +
                "!!! Une erreur c'est produite au cours de la commande gdal_translate : "
                + command + ". Voir message d'erreur." + endC,
                file=sys.stderr)
            raise

        # Croisement vecteur-raster pour récupérer la moyenne de SVF par polygone du fichier maillage d'entrée
        col_to_delete_list = [
            "min", "max", "median", "sum", "std", "unique", "range"
        ]
        statisticsVectorRaster(
            sky_view_factor_raster, grid_input, grid_output, 1, False, False,
            True, col_to_delete_list, [], {}, path_time_log, True,
            format_vector, save_results_intermediate, overwrite
        )  ## Erreur NaN pour polygones entièrement bâtis (soucis pour la suite ?)

        renameFieldsVector(grid_output, ['mean'], [SKY_VIEW_FIELD],
                           format_vector)

        ##########################################
        ### Nettoyage des fichiers temporaires ###
        ##########################################

        if not save_results_intermediate:
            deleteDir(temp_path)

    else:
        print(bold + magenta + "Le calcul du Sky View Factor a déjà eu lieu." +
              endC + "\n")

    print(bold + yellow + "Fin du calcul de l'indicateur Sky View Factor." +
          endC + "\n")
    timeLine(path_time_log, "Fin du calcul de l'indicateur Sky View Factor : ")

    return
コード例 #8
0
def computeRoughness(classif_input,
                     mnh_input,
                     vector_grid_input,
                     vector_grid_output,
                     class_label_dico,
                     epsg,
                     path_time_log,
                     format_raster='GTiff',
                     format_vector='ESRI Shapefile',
                     extension_raster=".tif",
                     extension_vector=".shp",
                     save_results_intermediate=False,
                     overwrite=True):

    # Constante
    FIELD_NAME_HRE = "mean_h"

    # Mise à jour du Log
    timeLine(
        path_time_log,
        "Début du calcul de l'indicateur Height of Roughness Elements par OCS et MNT starting : "
    )
    print(
        cyan + "computeRoughness() : " + endC +
        "Début du calcul de l'indicateur Height of Roughness Elements par OCS et MNT."
        + endC + "\n")

    if debug >= 3:
        print(bold + green +
              "computeRoughness() : Variables dans la fonction" + endC)
        print(cyan + "computeRoughness() : " + endC + "classif_input : " +
              str(classif_input) + endC)
        print(cyan + "computeRoughness() : " + endC + "mnh_input : " +
              str(mnh_input) + endC)
        print(cyan + "computeRoughness() : " + endC + "vector_grid_input : " +
              str(vector_grid_input) + endC)
        print(cyan + "computeRoughness() : " + endC + "vector_grid_output : " +
              str(vector_grid_output) + endC)
        print(cyan + "computeRoughness() : " + endC + "class_label_dico : " +
              str(class_label_dico) + endC)
        print(cyan + "computeRoughness() : " + endC + "epsg : " + str(epsg) +
              endC)
        print(cyan + "computeRoughness() : " + endC + "path_time_log : " +
              str(path_time_log) + endC)
        print(cyan + "computeRoughness() : " + endC + "format_vector : " +
              str(format_vector) + endC)
        print(cyan + "computeRoughness() : " + endC +
              "save_results_intermediate : " + str(save_results_intermediate) +
              endC)
        print(cyan + "computeRoughness() : " + endC + "overwrite : " +
              str(overwrite) + endC)

    # Test si le vecteur de sortie existe déjà et si il doit être écrasés
    check = os.path.isfile(vector_grid_output)

    if check and not overwrite:  # Si le fichier de sortie existent deja et que overwrite n'est pas activé
        print(cyan + "computeRoughness() : " + bold + yellow +
              "Le calcul de Roughness par OCS et MNT a déjà eu lieu." + endC +
              "\n")
        print(cyan + "computeRoughness() : " + bold + yellow +
              "Grid vector output : " + vector_grid_output +
              " already exists and will not be created again." + endC)
    else:
        if check:
            try:
                removeVectorFile(vector_grid_output)
            except Exception:
                pass  # si le fichier n'existe pas, il ne peut pas être supprimé : cette étape est ignorée

        ############################################
        ### Préparation générale des traitements ###
        ############################################

        # Récuperation de la projection de l'image
        epsg_proj = getProjectionImage(classif_input)
        if epsg_proj == 0:
            epsg_proj = epsg

        # Liste des classes
        #key_class_label_list = list(class_label_dico.keys())

        # Préparation des fichiers temporaires
        temp_path = os.path.dirname(vector_grid_output) + os.sep + "TEMP_HRE"

        # Nettoyage du repertoire temporaire si il existe
        if os.path.exists(temp_path):
            shutil.rmtree(temp_path)
        os.makedirs(temp_path)

        buit_height_temp = temp_path + os.sep + "hauteur_bati_temp" + extension_raster
        buit_height = temp_path + os.sep + "hauteur_bati" + extension_raster

        ##############################
        ### Calcul de l'indicateur ###
        ##############################

        # Récupération de la hauteur du bati
        #code_bati = [c for c,v in class_label_dico.items() if v=="bati"][0]
        code_bati = list(class_label_dico.keys())[list(
            class_label_dico.values()).index("bati")]
        command = "otbcli_BandMath -il %s %s -out %s float -exp 'im1b1==%s ? im2b1 : 0'" % (
            classif_input, mnh_input, buit_height_temp, str(code_bati))
        exit_code = os.system(command)
        if exit_code != 0:
            print(command)
            print(
                cyan + "computeRoughness() : " + bold + red +
                "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : "
                + command + ". Voir message d'erreur." + endC,
                file=sys.stderr)
            raise

        command = "gdal_translate -a_srs EPSG:%s -a_nodata 0 -of %s %s %s" % (
            str(epsg_proj), format_raster, buit_height_temp, buit_height)
        exit_code = os.system(command)
        if exit_code != 0:
            print(command)
            print(
                cyan + "computeRoughness() : " + bold + red +
                "!!! Une erreur c'est produite au cours de la comande : gdal_translate : "
                + command + ". Voir message d'erreur." + endC,
                file=sys.stderr)
            raise

        # Récupération de la hauteur moyenne du bati de chaque maille
        statisticsVectorRaster(
            buit_height, vector_grid_input, vector_grid_output, 1, False,
            False, True,
            ["min", "max", "median", "sum", "std", "unique", "range"], [], {},
            path_time_log, True, format_vector, save_results_intermediate,
            overwrite)

        # Renomer le champ 'mean' en FIELD_NAME_HRE
        renameFieldsVector(vector_grid_output, ['mean'], [FIELD_NAME_HRE],
                           format_vector)

        ##########################################
        ### Nettoyage des fichiers temporaires ###
        ##########################################
        if not save_results_intermediate:
            if os.path.exists(temp_path):
                shutil.rmtree(temp_path)

    print(
        cyan + "computeRoughness() : " + endC +
        "Fin du calcul de l'indicateur Height of Roughness Elements par OCS et MNT."
        + endC + "\n")
    timeLine(
        path_time_log,
        "Fin du calcul de l'indicateur Height of Roughness Elements par OCS et MNT  ending : "
    )

    return
コード例 #9
0
def occupationIndicator(classif_input,
                        mnh_input,
                        vector_grid_input,
                        vector_grid_output,
                        class_label_dico,
                        epsg,
                        path_time_log,
                        format_raster='GTiff',
                        format_vector='ESRI Shapefile',
                        extension_raster=".tif",
                        extension_vector=".shp",
                        save_results_intermediate=False,
                        overwrite=True):

    # Mise à jour du Log
    starting_event = "occupationIndicator() : Calcul de l'indicateur occupation du sol/hauteur de végétation starting : "
    timeLine(path_time_log, starting_event)
    print(
        bold + green +
        "Début du calcul de l'indicateur 'occupation du sol/hauteur de végétation'."
        + endC + "\n")

    if debug >= 3:
        print(bold + green +
              "occupationIndicator() : Variables dans la fonction" + endC)
        print(cyan + "occupationIndicator() : " + endC + "classif_input : " +
              str(classif_input) + endC)
        print(cyan + "occupationIndicator() : " + endC + "mnh_input : " +
              str(mnh_input) + endC)
        print(cyan + "occupationIndicator() : " + endC +
              "vector_grid_input : " + str(vector_grid_input) + endC)
        print(cyan + "occupationIndicator() : " + endC +
              "vector_grid_output : " + str(vector_grid_output) + endC)
        print(cyan + "occupationIndicator() : " + endC +
              "class_label_dico : " + str(class_label_dico) + endC)
        print(cyan + "occupationIndicator() : " + endC + "epsg : " +
              str(epsg) + endC)
        print(cyan + "occupationIndicator() : " + endC + "path_time_log : " +
              str(path_time_log) + endC)
        print(cyan + "occupationIndicator() : " + endC + "format_raster : " +
              str(format_raster) + endC)
        print(cyan + "occupationIndicator() : " + endC + "format_vector : " +
              str(format_vector) + endC)
        print(cyan + "occupationIndicator() : " + endC +
              "extension_raster : " + str(extension_raster) + endC)
        print(cyan + "occupationIndicator() : " + endC +
              "extension_vector : " + str(extension_vector) + endC)
        print(cyan + "occupationIndicator() : " + endC +
              "save_results_intermediate : " + str(save_results_intermediate) +
              endC)
        print(cyan + "occupationIndicator() : " + endC + "overwrite : " +
              str(overwrite) + endC)

    # Constante
    FIELD_OCS_NAME = 'class_OCS'
    FIELD_OCS_TYPE = ogr.OFTInteger
    FIELD_MAJORITY_NAME = 'majority'

    # Test si le vecteur de sortie existe déjà et si il doit être écrasés
    check = os.path.isfile(vector_grid_output)

    if check and not overwrite:  # Si le fichier de sortie existent deja et que overwrite n'est pas activé
        print(
            bold + yellow +
            "Le calcul de l'indicateur occupation du sol/hauteur de végétation a déjà eu lieu. \n"
            + endC)
        print(bold + yellow + "Grid vector output : " + vector_grid_output +
              " already exists and will not be created again." + endC)
    else:
        if check:
            try:
                removeVectorFile(vector_grid_output)
            except Exception:
                pass  # si le fichier n'existe pas, il ne peut pas être supprimé : cette étape est ignorée

        ############################################
        ### Préparation générale des traitements ###
        ############################################

        # Récuperation de la projection de l'image
        epsg_proj = getProjectionImage(classif_input)
        if epsg_proj == 0:
            epsg_proj = epsg

        # Liste des classes
        key_class_label_list = list(class_label_dico.keys())

        # Préparation des fichiers temporaires
        temp_path = os.path.dirname(vector_grid_output) + os.sep + "TEMP_OCS"

        # Nettoyage du repertoire temporaire si il existe
        if os.path.exists(temp_path):
            shutil.rmtree(temp_path)
        os.makedirs(temp_path)

        tempOCS = temp_path + os.sep + "occupation_du_sol" + extension_vector
        tempHveg = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation" + extension_vector

        temp_class0 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class0" + extension_vector
        temp_class1 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class1" + extension_vector
        temp_class2 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class2" + extension_vector
        temp_class3 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class3" + extension_vector
        temp_class4 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class4" + extension_vector

        vegetation_height_temp = temp_path + os.sep + "hauteur_vegetation_temp" + extension_raster
        vegetation_height = temp_path + os.sep + "hauteur_vegetation" + extension_raster

        ##############################
        ### Calcul de l'indicateur ###
        ##############################

        # Récupération de l'occupation du sol de chaque maille
        statisticsVectorRaster(classif_input, vector_grid_input, tempOCS, 1,
                               True, True, False, [], [], class_label_dico,
                               path_time_log, True, format_vector,
                               save_results_intermediate, overwrite)

        # Récupération de la hauteur moyenne et la hauteur max de la végétation de chaque maille
        command = "otbcli_BandMath -il %s %s -out %s float -exp 'im1b1==%s ? im2b1 : 0'" % (
            classif_input, mnh_input, vegetation_height_temp,
            str(key_class_label_list[4]))
        exit_code = os.system(command)
        if exit_code != 0:
            print(command)
            print(
                cyan + "occupationIndicator() : " + bold + red +
                "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : "
                + command + ". Voir message d'erreur." + endC,
                file=sys.stderr)
            raise

        command = "gdal_translate -a_srs EPSG:%s -a_nodata 0 -of %s %s %s" % (
            str(epsg_proj), format_raster, vegetation_height_temp,
            vegetation_height)
        exit_code = os.system(command)
        if exit_code != 0:
            print(command)
            print(
                cyan + "occupationIndicator() : " + bold + red +
                "!!! Une erreur c'est produite au cours de la comande : gdal_translate : "
                + command + ". Voir message d'erreur." + endC,
                file=sys.stderr)
            raise

        statisticsVectorRaster(vegetation_height, tempOCS, tempHveg, 1, False,
                               False, True, [], [], {}, path_time_log, True,
                               format_vector, save_results_intermediate,
                               overwrite)

        # Définir le nom des champs
        temp_class_list = []
        list_class_str = ""

        for class_str in key_class_label_list:
            list_class_str += "%s, " % (str(class_label_dico[class_str]))
        built_str = class_label_dico[key_class_label_list[0]]
        road_str = class_label_dico[key_class_label_list[1]]
        water_str = class_label_dico[key_class_label_list[2]]
        baresoil_str = class_label_dico[key_class_label_list[3]]
        vegetation_str = class_label_dico[key_class_label_list[4]]
        vegetation_height_medium_str = "H_moy_" + vegetation_str[0:3]
        vegetation_height_max_str = "H_max_" + vegetation_str[0:3]

        if debug >= 3:
            print("built_str = " + built_str)
            print("road_str = " + road_str)
            print("water_str = " + water_str)
            print("baresoil_str = " + baresoil_str)
            print("vegetation_str = " + vegetation_str)
            print("vegetation_height_medium_str = " +
                  vegetation_height_medium_str)
            print("vegetation_height_max_str = " + vegetation_height_max_str)

        column = "'ID, majority, minority, %s%s, %s, %s'" % (
            list_class_str, vegetation_height_max_str,
            vegetation_height_medium_str, FIELD_OCS_NAME)

        # Ajout d'un champ renvoyant la classe d'OCS attribué à chaque polygone et renomer le champ 'mean'
        renameFieldsVector(tempHveg, ['max'], [vegetation_height_max_str],
                           format_vector)
        renameFieldsVector(tempHveg, ['mean'], [vegetation_height_medium_str],
                           format_vector)
        addNewFieldVector(tempHveg, FIELD_OCS_NAME, FIELD_OCS_TYPE, 0, None,
                          None, format_vector)

        # Attribution de la classe 0 => classe majoritaire de bâti ou route ou eau
        #expression = "(" + built_str + " >= " + baresoil_str + " AND " + built_str + " >= " + vegetation_str + ") OR (" + road_str + " >= " + baresoil_str + " AND " + road_str + " >= " + vegetation_str + ") OR (" + water_str + " >= " + baresoil_str + " AND " + water_str + " >= " + vegetation_str + ")"
        expression = "(" + FIELD_MAJORITY_NAME + " = '" + built_str + "') OR (" + FIELD_MAJORITY_NAME + " = '" + road_str + "') OR (" + FIELD_MAJORITY_NAME + " = '" + water_str + "')"
        if debug >= 3:
            print(expression)
        ret = filterSelectDataVector(tempHveg, temp_class0, column, expression,
                                     format_vector)
        if not ret:
            raise NameError(
                cyan + "occupationIndicator() : " + bold + red +
                "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte"
                % (expression) + endC)
        updateFieldVector(temp_class0, FIELD_OCS_NAME, 0, format_vector)
        temp_class_list.append(temp_class0)

        # Attribution de la classe 1 => classe majoritaire de sol nu
        #expression = "(" + baresoil_str + " > " + built_str + " AND " + baresoil_str + " > " + road_str + " AND " + baresoil_str + " > " + water_str + " AND " + baresoil_str + " >= " + vegetation_str + ")"
        expression = "(" + FIELD_MAJORITY_NAME + " = '" + baresoil_str + "')"
        if debug >= 3:
            print(expression)
        ret = filterSelectDataVector(tempHveg, temp_class1, column, expression,
                                     format_vector)
        if not ret:
            raise NameError(
                cyan + "occupationIndicator() : " + bold + red +
                "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte"
                % (expression) + endC)
        updateFieldVector(temp_class1, FIELD_OCS_NAME, 1, format_vector)
        temp_class_list.append(temp_class1)

        # Attribution de la classe 2 => classe majoritaire de végétation avec Hauteur inferieur à 1
        #expression = "(" + vegetation_str + " > " + built_str + " AND " + vegetation_str + " > " + road_str + " AND " + vegetation_str + " > " + water_str + " AND " + vegetation_str + " > " + baresoil_str + ") AND (" + vegetation_height_medium_str + " < 1)"
        expression = "(" + FIELD_MAJORITY_NAME + " = '" + vegetation_str + "') AND (" + vegetation_height_medium_str + " < 1)"
        if debug >= 3:
            print(expression)
        ret = filterSelectDataVector(tempHveg, temp_class2, column, expression,
                                     format_vector)
        if not ret:
            raise NameError(
                cyan + "occupationIndicator() : " + bold + red +
                "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte"
                % (expression) + endC)
        updateFieldVector(temp_class2, FIELD_OCS_NAME, 2, format_vector)
        temp_class_list.append(temp_class2)

        # Attribution de la classe 3 => classe majoritaire de végétation avec Hauteur entre 1 et 5
        #expression = "(" + vegetation_str + " > " + built_str + " AND " + vegetation_str + " > " + road_str + " AND " + vegetation_str + " > " + water_str + " AND " + vegetation_str + " > " + baresoil_str + ") AND (" + vegetation_height_medium_str + " >= 1 AND " + vegetation_height_medium_str + " < 5)"
        expression = "(" + FIELD_MAJORITY_NAME + " = '" + vegetation_str + "') AND (" + vegetation_height_medium_str + " >= 1 AND " + vegetation_height_medium_str + " < 5)"
        if debug >= 3:
            print(expression)
        ret = filterSelectDataVector(tempHveg, temp_class3, column, expression,
                                     format_vector)
        if not ret:
            raise NameError(
                cyan + "occupationIndicator() : " + bold + red +
                "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte"
                % (expression) + endC)
        updateFieldVector(temp_class3, FIELD_OCS_NAME, 3, format_vector)
        temp_class_list.append(temp_class3)

        # Attribution de la classe 4 => classe majoritaire de végétation avec Hauteur > 5
        #expression = "(" + vegetation_str + " > " + built_str + " AND " + vegetation_str + " > " + road_str + " AND " + vegetation_str + " > " + water_str + " AND " + vegetation_str + " > " + baresoil_str + ") AND (" + vegetation_height_medium_str + " >= 5)"
        expression = "(" + FIELD_MAJORITY_NAME + " = '" + vegetation_str + "') AND (" + vegetation_height_medium_str + " >= 5)"
        if debug >= 3:
            print(expression)
        ret = filterSelectDataVector(tempHveg, temp_class4, column, expression,
                                     format_vector)
        if not ret:
            raise NameError(
                cyan + "occupationIndicator() : " + bold + red +
                "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte"
                % (expression) + endC)
        updateFieldVector(temp_class4, FIELD_OCS_NAME, 4, format_vector)
        temp_class_list.append(temp_class4)

        fusionVectors(temp_class_list, vector_grid_output, format_vector)

        ##########################################
        ### Nettoyage des fichiers temporaires ###
        ##########################################

        if not save_results_intermediate:
            if os.path.exists(temp_path):
                shutil.rmtree(temp_path)

    # Mise à jour du Log
    print(
        bold + green +
        "Fin du calcul de l'indicateur 'occupation du sol/hauteur de végétation'."
        + endC + "\n")
    ending_event = "occupationIndicator() : Calcul de l'indicateur occupation du sol/hauteur de végétation ending : "
    timeLine(path_time_log, ending_event)

    return
コード例 #10
0
def main(gui=False):

    # Définition des arguments possibles pour l'appel en ligne de commande
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter,
        prog="BuiltDifference",
        description="\
    Info : Create macro samples. \n\
    Objectif : Realiser identifier des differences entre la BT topo partie Batie et un MNS. \n\
    Example : python BuiltDifference.py -i /mnt/hgfs/Data_Image_Saturn/Test_Methode_CUB_zone_test_NE_1/CUB_zone_test_NE_1.tif \n\
                                        -imns /mnt/hgfs/Data_Image_Saturn/Test_Methode_CUB_zone_test_NE_1/MNS_CUB_zone_test_NE_1.tif \n\
                                        -imnt /mnt/hgfs/Data_Image_Saturn/Test_Methode_CUB_zone_test_NE_1/MNT_CUB_zone_test_NE_1.tif \n\
                                        -o /mnt/hgfs/Data_Image_Saturn/Test_Methode_CUB_zone_test_NE_1/Result/CUB_zone_test_NE_1_diff.tif \n\
                                        -v /mnt/hgfs/Data_Image_Saturn/Test_Methode_CUB_zone_test_NE_1/Result/CUB_zone_test_NE_1_diff_mns.shp \n\
                                        -ibdl /mnt/hgfs/Data_Image_Saturn/BD/BATI_INDIFFERENCIE_033.shp \n\
                                              /mnt/hgfs/Data_Image_Saturn/BD/BATI_INDUSTRIEL_033.shp \n\
                                        -dep 033 \n\
                                        -tndvi 0.3 -tdiff 8.0 -fdif0 5 -fdif1 10 \n\
                                        -log  /mnt/hgfs/Data_Image_Saturn/Test_Methode_CUB_zone_test_NE_1/fichierTestLog.txt"
    )

    # Paramètres généraux
    parser.add_argument('-i',
                        '--image_input',
                        default="",
                        help="Image input to treat",
                        type=str,
                        required=True)
    parser.add_argument('-imns',
                        '--image_mns',
                        default="",
                        help="Image input of MNS",
                        type=str,
                        required=True)
    parser.add_argument('-imnt',
                        '--image_mnt',
                        default="",
                        help="Image input of MNT",
                        type=str,
                        required=True)
    parser.add_argument('-o',
                        '--image_output',
                        help="Image output result difference",
                        type=str,
                        required=False)
    parser.add_argument('-v',
                        '--vector_output',
                        help="Vector output result difference",
                        type=str,
                        required=False)
    parser.add_argument(
        '-ibdl',
        '--bd_vector_input_list',
        default="",
        nargs="+",
        help="List containt bd vector input concatened to create vector sample",
        type=str,
        required=True)
    parser.add_argument('-field',
                        '--fileld_bd_raster',
                        default="HAUTEUR",
                        help="Filled value used to rasterize shape BD",
                        type=str,
                        required=False)
    parser.add_argument(
        '-zone',
        '--zone_buff_dico',
        nargs="+",
        default=["Bati:BATI_INDIFFERENCIE,0:BATI_INDUSTRIEL,0"],
        help=
        "Dictionary of zone containt bd and buffer, (format : zone:[BD,sizeBuffer][..]), ex. Bati:BATI_INDIFFERENCIE,0:BATI_INDUSTRIEL,0",
        type=str,
        required=False)
    parser.add_argument(
        '-dep',
        '--departments_list',
        default="",
        nargs="+",
        help=
        "List sources departements selected (add a 0 before dep begining by 0), ex. 001 33.",
        type=str,
        required=True)
    parser.add_argument(
        '-simp',
        '--simple_param_vector',
        default=2.0,
        help="Parameter of polygons simplification. By default : 2.0",
        type=float,
        required=False)
    parser.add_argument('-tndvi',
                        '--threshold_ndvi',
                        default=0.25,
                        help="Parameter of threshold ndvi. By default : 0.25",
                        type=float,
                        required=False)
    parser.add_argument(
        '-tdiff',
        '--threshold_difference',
        default=6.0,
        help="Parameter of threshold difference mns. By default : 6.0",
        type=float,
        required=False)
    parser.add_argument(
        '-fdif0',
        '--filter_difference_0',
        default=5,
        help=
        "Parameter of filter clean 0 value, result difference. By default : 5",
        type=int,
        required=False)
    parser.add_argument(
        '-fdif1',
        '--filter_difference_1',
        default=15,
        help=
        "Parameter of filter clean 1 value, result difference. By default : 15",
        type=int,
        required=False)
    parser.add_argument(
        '-chao',
        '--channel_order',
        nargs="+",
        default=['Red', 'Green', 'Blue', 'NIR'],
        help=
        "Type of multispectral image : rapideye or spot6 or pleiade. By default : [Red,Green,Blue,NIR]",
        type=str,
        required=False)
    parser.add_argument('-vef',
                        '--format_vector',
                        default="ESRI Shapefile",
                        help="Format of the output file.",
                        type=str,
                        required=False)
    parser.add_argument(
        '-rae',
        '--extension_raster',
        default=".tif",
        help="Option : Extension file for image raster. By default : '.tif'",
        type=str,
        required=False)
    parser.add_argument(
        '-vee',
        '--extension_vector',
        default=".shp",
        help="Option : Extension file for vector. By default : '.shp'",
        type=str,
        required=False)
    parser.add_argument('-log',
                        '--path_time_log',
                        default="",
                        help="Name of log",
                        type=str,
                        required=False)
    parser.add_argument(
        '-sav',
        '--save_results_inter',
        action='store_true',
        default=False,
        help=
        "Save or delete intermediate result after the process. By default, False",
        required=False)
    parser.add_argument(
        '-now',
        '--overwrite',
        action='store_false',
        default=True,
        help="Overwrite files with same names. By default, True",
        required=False)
    parser.add_argument(
        '-debug',
        '--debug',
        default=3,
        help="Option : Value of level debug trace, default : 3 ",
        type=int,
        required=False)
    args = displayIHM(gui, parser)

    # RECUPERATION DES ARGUMENTS

    # Récupération des arguments du parser images d'entrées
    if args.image_input != None:
        image_input = args.image_input
        if not os.path.isfile(image_input):
            raise NameError(cyan + "BuiltDifference : " + bold + red +
                            "File %s not existe!" % (image_input) + endC)

    if args.image_mns != None:
        image_mns = args.image_mns
        if not os.path.isfile(image_mns):
            raise NameError(cyan + "BuiltDifference : " + bold + red +
                            "File %s not existe!" % (image_mns) + endC)

    if args.image_mnt != None:
        image_mnt = args.image_mnt
        if not os.path.isfile(image_mnt):
            raise NameError(cyan + "BuiltDifference : " + bold + red +
                            "File %s not existe!" % (image_mnt) + endC)

    # Récupération des vecteurs de bd exogenes
    if args.bd_vector_input_list != None:
        bd_vector_input_list = args.bd_vector_input_list

    # Récupération des arguments du parser images de sorties
    if args.image_output != None:
        image_output = args.image_output

    if args.vector_output != None:
        vector_output = args.vector_output

    # Récupération des info données
    if args.departments_list != None:
        departments_list = args.departments_list

    if args.fileld_bd_raster != None:
        fileld_bd_raster = args.fileld_bd_raster

    # creation du dictionaire table macro class contenant la BD et le buffer
    if args.zone_buff_dico != None:
        zone_buffer_dico = extractDico(args.zone_buff_dico)

    # Parametres de filtrage
    if args.simple_param_vector != None:
        simplifie_param = args.simple_param_vector

    if args.threshold_ndvi != None:
        threshold_ndvi = args.threshold_ndvi

    if args.threshold_difference != None:
        threshold_difference = args.threshold_difference

    if args.filter_difference_0 != None:
        filter_difference_0 = args.filter_difference_0

    if args.filter_difference_1 != None:
        filter_difference_1 = args.filter_difference_1

    # Ordre des canaux de l'image ortho
    if args.channel_order != None:
        channel_order = args.channel_order

    # Récupération du format du fichier de sortie
    if args.format_vector != None:
        format_vector = args.format_vector

    # Paramètre de l'extension des images rasters
    if args.extension_raster != None:
        extension_raster = args.extension_raster

    # Récupération de l'extension des fichiers vecteurs
    if args.extension_vector != None:
        extension_vector = args.extension_vector

    # Récupération du nom du fichier log
    if args.path_time_log != None:
        path_time_log = args.path_time_log

    # Ecrasement des fichiers
    if args.save_results_inter != None:
        save_results_intermediate = args.save_results_inter

    if args.overwrite != None:
        overwrite = args.overwrite

    # Récupération de l'option niveau de debug
    if args.debug != None:
        global debug
        debug = args.debug

    if debug >= 3:
        print(bold + green + "Variables dans le parser" + endC)
        print(cyan + "BuiltDifference : " + endC + "image_input : " +
              str(image_input) + endC)
        print(cyan + "BuiltDifference : " + endC + "image_mns : " +
              str(image_mns) + endC)
        print(cyan + "BuiltDifference : " + endC + "image_mnt : " +
              str(image_mnt) + endC)
        print(cyan + "BuiltDifference : " + endC + "image_output : " +
              str(image_output) + endC)
        print(cyan + "BuiltDifference : " + endC + "bd_vector_input_list : " +
              str(bd_vector_input_list) + endC)
        print(cyan + "BuiltDifference : " + endC + "vector_output : " +
              str(vector_output) + endC)
        print(cyan + "BuiltDifference : " + endC + "zone_buffer_dico : " +
              str(zone_buffer_dico) + endC)
        print(cyan + "BuiltDifference : " + endC + "departments_list : " +
              str(departments_list) + endC)
        print(cyan + "BuiltDifference : " + endC + "fileld_bd_raster : " +
              str(fileld_bd_raster) + endC)
        print(cyan + "BuiltDifference : " + endC + "simple_param_vector : " +
              str(simplifie_param) + endC)
        print(cyan + "BuiltDifference : " + endC + "threshold_ndvi : " +
              str(threshold_ndvi) + endC)
        print(cyan + "BuiltDifference : " + endC + "threshold_difference : " +
              str(threshold_difference) + endC)
        print(cyan + "BuiltDifference : " + endC + "filter_difference_0 : " +
              str(filter_difference_0) + endC)
        print(cyan + "BuiltDifference : " + endC + "filter_difference_1 : " +
              str(filter_difference_1) + endC)
        print(cyan + "BuiltDifference : " + endC + "channel_order : " +
              str(channel_order) + endC)
        print(cyan + "BuiltDifference : " + endC + "format_vector : " +
              str(format_vector) + endC)
        print(cyan + "BuiltDifference : " + endC + "extension_raster : " +
              str(extension_raster) + endC)
        print(cyan + "BuiltDifference : " + endC + "extension_vector : " +
              str(extension_vector) + endC)
        print(cyan + "BuiltDifference : " + endC + "path_time_log : " +
              str(path_time_log) + endC)
        print(cyan + "BuiltDifference : " + endC + "save_results_inter : " +
              str(save_results_intermediate) + endC)
        print(cyan + "BuiltDifference : " + endC + "overwrite: " +
              str(overwrite) + endC)
        print(cyan + "BuiltDifference : " + endC + "debug: " + str(debug) +
              endC)

    # EXECUTION DE LA FONCTION
    # Si les dossiers de sortie n'existent pas, on les crées

    repertory_output = os.path.dirname(image_output)
    if not os.path.isdir(repertory_output):
        os.makedirs(repertory_output)
    repertory_output = os.path.dirname(vector_output)
    if not os.path.isdir(repertory_output):
        os.makedirs(repertory_output)

    # execution de la fonction pour une image
    createDifference(image_input, image_mns, image_mnt, bd_vector_input_list,
                     zone_buffer_dico, departments_list, image_output,
                     vector_output, fileld_bd_raster, simplifie_param,
                     threshold_ndvi, threshold_difference, filter_difference_0,
                     filter_difference_1, path_time_log, format_vector,
                     extension_raster, extension_vector,
                     save_results_intermediate, channel_order, overwrite)
    # ajouter les valeurs des hauteurs en champs suplementaire au shape
    statisticsVectorRaster(image_output, vector_output, "", 1, False, False,
                           True, [], [], {}, path_time_log, True,
                           format_vector, save_results_intermediate, overwrite)
def indicateurSI(urbanatlas_input, ucz_output, emprise_file, mask_file,
                 enter_with_mask, image_file, mnh_file, built_files_list,
                 hydrography_file, roads_files_list, rpg_file,
                 indicators_method, ucz_method, dbms_choice, threshold_ndvi,
                 threshold_ndvi_water, threshold_ndwi2, threshold_bi_bottom,
                 threshold_bi_top, path_time_log, temp_directory,
                 extension_raster, extension_vector):

    print(
        bold + yellow +
        "Début de la préparation au calcul de l'indicateur de pourcentage de surfaces imperméables."
        + endC)
    step = "    Début de la préparation au calcul de l'indicateur de pourcentage de surfaces imperméables : "
    timeLine(path_time_log, step)

    grid_ready_cleaned = temp_directory + os.sep + os.path.splitext(
        os.path.basename(
            urbanatlas_input))[0] + "_cut_cleaned" + extension_vector
    permeability = temp_directory + os.sep + "permeability" + extension_raster
    logCVR = temp_directory + os.sep + "logCVR.txt"

    if indicators_method == "BD_exogenes":  # Élaboration de la carte d'imperméabilité pour la 1ère méthode de calcul des indicateurs

        neochannels = temp_directory + os.sep + os.path.splitext(
            os.path.basename(image_file))[0] + "_NDVI" + extension_raster
        hydro_shape = temp_directory + os.sep + "eau" + extension_vector
        RPG_shape = temp_directory + os.sep + "RPG" + extension_vector
        hydro_mask = temp_directory + os.sep + "hydro_mask" + extension_raster
        RPG_mask = temp_directory + os.sep + "RPG_mask" + extension_raster
        vegetation_mask = mask_file

        if not enter_with_mask:
            vegetation_mask = temp_directory + os.sep + "vegetation_mask" + extension_raster
            print(bold + cyan + "    Création du masque de végétation :" +
                  endC)
            os.system(
                "otbcli_BandMath -il %s -out %s uint8 -exp 'im1b1>=%s ? 10 : 1'"
                % (neochannels, vegetation_mask,
                   threshold_ndvi))  # Création du masque de végétation
        print(bold + cyan + "    Création du masque RPG :" + endC)
        os.system(
            "otbcli_Rasterization -in %s -out %s uint8 -im %s -background 1 -mode binary -mode.binary.foreground 10"
            % (RPG_shape, RPG_mask,
               vegetation_mask))  # Création du masque RPG (~ sol nu)
        print(bold + cyan + "    Création du masque d'eau :" + endC)
        os.system(
            "otbcli_Rasterization -in %s -out %s uint8 -im %s -background 1 -mode binary -mode.binary.foreground 10"
            % (hydro_shape, hydro_mask,
               vegetation_mask))  # Création du masque d'eau
        print(bold + cyan + "    Création de la carte d'imperméabilité :" +
              endC)
        os.system(
            "otbcli_BandMath -il %s %s %s -out %s uint8 -exp 'im1b1+im2b1+im3b1>=10 ? 10 : 1'"
            % (vegetation_mask, RPG_mask, hydro_mask,
               permeability))  # Création de la carte d'imperméabilité

    elif indicators_method == "SI_seuillage":  # Élaboration de la carte d'imperméabilité pour la 2ème méthode de calcul des indicateurs

        neochannels = temp_directory + os.sep + os.path.splitext(
            os.path.basename(
                image_file))[0] + "_NDVI_NDWI2_BI" + extension_raster
        built_shape = temp_directory + os.sep + "bati" + extension_vector
        roads_shape = temp_directory + os.sep + "route" + extension_vector
        built_mask = temp_directory + os.sep + "built_mask" + extension_raster
        roads_mask = temp_directory + os.sep + "roads_mask" + extension_raster

        print(bold + cyan + "    Création du masque bâti pour nettoyage :" +
              endC)
        os.system(
            "otbcli_Rasterization -in %s -out %s uint8 -im %s -background 1 -mode binary -mode.binary.foreground 10"
            % (built_shape, built_mask,
               neochannels))  # Création du masque bâti pour nettoyage
        print(bold + cyan + "    Création du masque route pour nettoyage :" +
              endC)
        os.system(
            "otbcli_Rasterization -in %s -out %s uint8 -im %s -background 1 -mode binary -mode.binary.foreground 10"
            % (roads_shape, roads_mask,
               neochannels))  # Création du masque route pour nettoyage
        print(bold + cyan + "    Création de la carte d'imperméabilité :" +
              endC)
        expression = "((im1b1>=%s) or (im1b1<%s and im1b2>=%s) or (im1b1>=%s and im1b1<%s and im1b3>=%s and im1b3<%s)) and (im2b1==1 and im3b1==1) ? 10 : 1" % (
            threshold_ndvi, threshold_ndvi_water, threshold_ndwi2,
            threshold_ndvi_water, threshold_ndvi, threshold_bi_bottom,
            threshold_bi_top)
        os.system("otbcli_BandMath -il %s %s %s -out %s uint8 -exp '%s'" %
                  (neochannels, built_mask, roads_mask, permeability,
                   expression))  # Création de la carte d'imperméabilité

    else:  # Élaboration de la carte d'imperméabilité pour les méthodes 3 et 4 de calcul des indicateurs (utilisant la classif)

        image_cut = temp_directory + os.sep + os.path.splitext(
            os.path.basename(image_file))[0] + "_cut" + extension_raster

        print(bold + cyan + "    Création de la carte d'imperméabilité :" +
              endC)
        os.system(
            "otbcli_BandMath -il %s -out %s uint8 -exp 'im1b1>=12000 ? 10 : 1'"
            %
            (image_cut, permeability))  # Création de la carte d'imperméabilité

    print(
        bold + cyan +
        "    Récupération du pourcentage de surfaces imperméables par polygone du maillage :"
        + endC)
    statisticsVectorRaster(
        permeability, grid_ready_cleaned, "", 1, True, True, False, [], [], {
            1: 'Imperm',
            10: 'Perm'
        }, path_time_log, True, 'ESRI Shapefile', False, True
    )  # Récupération du pourcentage de surfaces imperméables par polygone du maillage
    time.sleep(
        10
    )  # Pause de 10 secondes pour que le système récupère toute la RAM qui a pu être utilisée pour le CVR

    step = "    Fin de la préparation au calcul de l'indicateur de pourcentage de surfaces imperméables : "
    timeLine(path_time_log, step)
    print(
        bold + yellow +
        "Fin de la préparation au calcul de l'indicateur de pourcentage de surfaces imperméables."
        + endC)
    print("\n")

    return
def indicateurRug(urbanatlas_input, ucz_output, emprise_file, mask_file,
                  enter_with_mask, image_file, mnh_file, built_files_list,
                  hydrography_file, roads_files_list, rpg_file,
                  indicators_method, ucz_method, dbms_choice, threshold_ndvi,
                  threshold_ndvi_water, threshold_ndwi2, threshold_bi_bottom,
                  threshold_bi_top, path_time_log, temp_directory,
                  extension_raster, extension_vector):

    print(
        bold + yellow +
        "Début de la préparation au calcul de l'indicateur de classe de rugosité."
        + endC)
    step = "    Début de la préparation au calcul de l'indicateur de classe de rugosité : "
    timeLine(path_time_log, step)

    grid_ready_cleaned = temp_directory + os.sep + os.path.splitext(
        os.path.basename(
            urbanatlas_input))[0] + "_cut_cleaned" + extension_vector
    long_rugosite = temp_directory + os.sep + "z0" + extension_raster
    logCVR = temp_directory + os.sep + "logCVR.txt"

    if indicators_method == "Resultats_classif":  # Élaboration du raster longueur de rugosité pour la 4ème méthode de calcul des indicateurs

        image_cut = temp_directory + os.sep + os.path.splitext(
            os.path.basename(image_file))[0] + "_cut" + extension_raster
        MNH_cut = temp_directory + os.sep + os.path.splitext(
            os.path.basename(mnh_file))[0] + "_cut" + extension_raster

        print(bold + cyan + "    Calcul de la longueur de rugosité :" + endC)
        os.system(
            "otbcli_BandMath -il %s %s -out %s -exp 'im1b1==11100 ? (im2b1*0.7)*100 : 0.001'"
            % (image_cut, MNH_cut,
               long_rugosite))  # Calcul de la longueur de rugosité

    else:  # Élaboration du raster longueur de rugosité pour les 3 premières méthodes de calcul des indicateurs

        permeability = temp_directory + os.sep + "permeability" + extension_raster
        built_shape = temp_directory + os.sep + "bati" + extension_vector
        built_height = temp_directory + os.sep + "built_height" + extension_raster

        print(
            bold + cyan +
            "    Rastérisation du bâti issu de la BD TOPO (avec information de hauteur) :"
            + endC)
        os.system(
            "otbcli_Rasterization -in %s -out %s -im %s -background 0.001 -mode attribute -mode.attribute.field HAUTEUR"
            % (built_shape, built_height, permeability)
        )  # Rastérisation du bâti issu de la BD TOPO (avec information de hauteur)
        print(bold + cyan + "    Calcul de la longueur de rugosité :" + endC)
        os.system(
            "otbcli_BandMath -il %s -out %s -exp '(im1b1*0.7)*100'" %
            (built_height, long_rugosite))  # Calcul de la longueur de rugosité

    print(
        bold + cyan +
        "    Récupération de la longueur de rugosité moyenne par polygone du maillage :"
        + endC)
    statisticsVectorRaster(
        long_rugosite, grid_ready_cleaned, "", 1, False, False, True, [], [],
        {}, logCVR, True, True
    )  # Récupération de la longueur de rugosité moyenne (~ hauteur de bâti moyenne) par polygone du maillage
    time.sleep(
        10
    )  # Pause de 10 secondes pour que le système récupère toute la RAM qui a pu être utilisée pour le CVR

    step = "    Fin de la préparation au calcul de l'indicateur de classe de rugosité : "
    timeLine(path_time_log, step)
    print(
        bold + yellow +
        "Fin de la préparation au calcul de l'indicateur de classe de rugosité."
        + endC)
    print("\n")

    return
def indicateurRA(urbanatlas_input, ucz_output, emprise_file, mask_file,
                 enter_with_mask, image_file, mnh_file, built_files_list,
                 hydrography_file, roads_files_list, rpg_file,
                 indicators_method, ucz_method, dbms_choice, threshold_ndvi,
                 threshold_ndvi_water, threshold_ndwi2, threshold_bi_bottom,
                 threshold_bi_top, path_time_log, temp_directory,
                 extension_raster, extension_vector):

    print(
        bold + yellow +
        "Début de la préparation au calcul de l'indicateur de rapport d'aspect."
        + endC)
    step = "    Début de la préparation au calcul de l'indicateur de rapport d'aspect : "
    timeLine(path_time_log, step)

    grid_ready_cleaned = temp_directory + os.sep + os.path.splitext(
        os.path.basename(
            urbanatlas_input))[0] + "_cut_cleaned" + extension_vector
    permeability = temp_directory + os.sep + "permeability" + extension_raster
    built_shape = temp_directory + os.sep + "bati" + extension_vector
    built_RA = temp_directory + os.sep + "built_RA" + extension_raster
    logCVR = temp_directory + os.sep + "logCVR.txt"

    if indicators_method == "Resultats_classif":  # Croisement du bâti vectorisé avec le MNH pour récupérer la hauteur moyenne de chaque bâtiment

        MNH_cut = temp_directory + os.sep + os.path.splitext(
            os.path.basename(mnh_file))[0] + "_cut" + extension_raster
        MNH_centimeters = temp_directory + os.sep + "MNH_centimeters" + extension_raster

        print(
            bold + cyan +
            "    Basculement des valeurs du MNH des mètres aux centimètres :" +
            endC)
        os.system(
            "otbcli_BandMath -il %s -out %s uint16 -exp 'im1b1*100'" %
            (MNH_cut, MNH_centimeters)
        )  # Basculement des valeurs du MNH des mètres aux centimètres (pour obtenir un raster codé en entier et non en flottant)
        print(
            bold + cyan +
            "    Récupération de l'information de hauteur du bâti à partir du MNH :"
            + endC)
        statisticsVectorRaster(
            MNH_centimeters, built_shape, "", 1, False, False, True, [], [],
            {}, logCVR, True, 'ESRI Shapefile', False, True
        )  # Récupération de l'information de hauteur du bâti à partir du MNH
        time.sleep(
            10
        )  # Pause de 10 secondes pour que le système récupère toute la RAM qui a pu être utilisée pour le CVR

    print(bold + cyan + "    Rastérisation du bâti :" + endC)
    pixel_size_x, pixel_size_y = getPixelWidthXYImage(permeability)
    os.system(
        "gdal_rasterize -burn 10 -init 1 -tr %s %s %s %s" %
        (pixel_size_x, pixel_size_y, built_shape, built_RA)
    )  # Rastérisation du bâti via GDAL plutôt qu'OTB : mauvaise gestion des valeurs de background pour l'OTB (devient NoData)
    print(
        bold + cyan +
        "    Récupération de la surface non-bâtie par polygone du maillage :" +
        endC)
    statisticsVectorRaster(
        built_RA, grid_ready_cleaned, "", 1, True, True, False, [], [], {
            1: 'NonBati',
            10: 'Bati'
        }, path_time_log, True, 'ESRI Shapefile', False,
        True)  # Récupération de la surface non-bâtie par polygone du maillage
    time.sleep(
        10
    )  # Pause de 10 secondes pour que le système récupère toute la RAM qui a pu être utilisée pour le CVR

    step = "    Fin de la préparation au calcul de l'indicateur de rapport d'aspect : "
    timeLine(path_time_log, step)
    print(
        bold + yellow +
        "Fin de la préparation au calcul de l'indicateur de rapport d'aspect."
        + endC)
    print("\n")

    return