def estimateQualityMns(image_input,
                       vector_cut_input,
                       vector_sample_input_list,
                       vector_sample_points_input,
                       raster_input_dico,
                       vector_output,
                       no_data_value,
                       path_time_log,
                       format_raster='GTiff',
                       epsg=2154,
                       format_vector='ESRI Shapefile',
                       extension_raster=".tif",
                       extension_vector=".shp",
                       save_results_intermediate=False,
                       overwrite=True):

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

    print(endC)
    print(bold + green + "## START : CREATE HEIGHT POINTS FILE FROM MNS" +
          endC)
    print(endC)

    if debug >= 2:
        print(bold + green +
              "estimateQualityMns() : Variables dans la fonction" + endC)
        print(cyan + "estimateQualityMns() : " + endC + "image_input : " +
              str(image_input) + endC)
        print(cyan + "estimateQualityMns() : " + endC + "vector_cut_input : " +
              str(vector_cut_input) + endC)
        print(cyan + "estimateQualityMns() : " + endC +
              "vector_sample_input_list : " + str(vector_sample_input_list) +
              endC)
        print(cyan + "estimateQualityMns() : " + endC +
              "vector_sample_points_input : " +
              str(vector_sample_points_input) + endC)
        print(cyan + "estimateQualityMns() : " + endC +
              "raster_input_dico : " + str(raster_input_dico) + endC)
        print(cyan + "estimateQualityMns() : " + endC + "vector_output : " +
              str(vector_output) + endC)
        print(cyan + "estimateQualityMns() : " + endC + "no_data_value : " +
              str(no_data_value))
        print(cyan + "estimateQualityMns() : " + endC + "path_time_log : " +
              str(path_time_log) + endC)
        print(cyan + "estimateQualityMns() : " + endC + "epsg  : " +
              str(epsg) + endC)
        print(cyan + "estimateQualityMns() : " + endC + "format_raster : " +
              str(format_raster) + endC)
        print(cyan + "estimateQualityMns() : " + endC + "format_vector : " +
              str(format_vector) + endC)
        print(cyan + "estimateQualityMns() : " + endC + "extension_raster : " +
              str(extension_raster) + endC)
        print(cyan + "estimateQualityMns() : " + endC + "extension_vector : " +
              str(extension_vector) + endC)
        print(cyan + "estimateQualityMns() : " + endC +
              "save_results_intermediate : " + str(save_results_intermediate) +
              endC)
        print(cyan + "estimateQualityMns() : " + endC + "overwrite : " +
              str(overwrite) + endC)

    # Définion des constantes
    EXT_DBF = '.dbf'
    EXT_CSV = '.csv'

    CODAGE = "uint16"

    SUFFIX_STUDY = '_study'
    SUFFIX_CUT = '_cut'
    SUFFIX_TEMP = '_temp'
    SUFFIX_CLEAN = '_clean'
    SUFFIX_SAMPLE = '_sample'

    ATTRIBUTE_ID = "ID"
    ATTRIBUTE_Z_INI = "Z_INI"
    ATTRIBUTE_Z_FIN = "Z_FIN"
    ATTRIBUTE_PREC_ALTI = "PREC_ALTI"
    ATTRIBUTE_Z_REF = "Z_Ref"
    ATTRIBUTE_Z_MNS = "Z_Mns"
    ATTRIBUTE_Z_DELTA = "Z_Delta"

    ERODE_EDGE_POINTS = -1.0

    ERROR_VALUE = -99.0
    ERROR_MIN_VALUE = -9999
    ERROR_MAX_VALUE = 9999

    # ETAPE 0 : PREPARATION DES FICHIERS INTERMEDIAIRES

    # Si le fichier de sortie existe on ecrase
    check = os.path.isfile(vector_output)
    if check and not overwrite:  # Si un fichier de sortie avec le même nom existe déjà, et si l'option ecrasement est à false, alors FIN
        print(cyan + "estimateQualityMns() : " + bold + yellow +
              "Create  file %s already exist : no actualisation" %
              (vector_output) + endC)
        return

    if os.path.isfile(os.path.splitext(vector_output)[0] + EXT_CSV):
        removeFile(os.path.splitext(vector_output)[0] + EXT_CSV)

    repertory_output = os.path.dirname(vector_output)
    base_name = os.path.splitext(os.path.basename(vector_output))[0]

    vector_output_temp = repertory_output + os.sep + base_name + SUFFIX_TEMP + extension_vector
    raster_study = repertory_output + os.sep + base_name + SUFFIX_STUDY + extension_raster
    vector_study = repertory_output + os.sep + base_name + SUFFIX_STUDY + extension_vector
    vector_study_clean = repertory_output + os.sep + base_name + SUFFIX_STUDY + SUFFIX_CLEAN + extension_vector
    image_cut = repertory_output + os.sep + base_name + SUFFIX_CUT + extension_raster
    vector_sample_temp = repertory_output + os.sep + base_name + SUFFIX_SAMPLE + SUFFIX_TEMP + extension_vector
    vector_sample_temp_clean = repertory_output + os.sep + base_name + SUFFIX_SAMPLE + SUFFIX_TEMP + SUFFIX_CLEAN + extension_vector

    # Utilisation des données raster externes
    raster_cut_dico = {}
    for raster_input in raster_input_dico:
        base_name_raster = os.path.splitext(os.path.basename(raster_input))[0]
        raster_cut = repertory_output + os.sep + base_name_raster + SUFFIX_CUT + extension_raster
        raster_cut_dico[raster_input] = raster_cut
        if os.path.exists(raster_cut):
            removeFile(raster_cut)

    # ETAPE 1 : DEFINIR UN SHAPE ZONE D'ETUDE

    if (not vector_cut_input is None) and (vector_cut_input != "") and (
            os.path.isfile(vector_cut_input)):
        cutting_action = True
        vector_study = vector_cut_input

    else:
        cutting_action = False
        createVectorMask(image_input, vector_study)

    # ETAPE 2 : DECOUPAGE DU RASTEUR PAR LE VECTEUR D'ETUDE SI BESOIN ET REECHANTILLONAGE SI BESOIN

    if cutting_action:
        # Identification de la tailles de pixels en x et en y du fichier MNS de reference
        pixel_size_x, pixel_size_y = getPixelWidthXYImage(image_input)

        # Si le fichier de sortie existe deja le supprimer
        if os.path.exists(image_cut):
            removeFile(image_cut)

        # Commande de découpe
        if not cutImageByVector(vector_study, image_input, image_cut,
                                pixel_size_x, pixel_size_y, no_data_value, 0,
                                format_raster, format_vector):
            print(
                cyan + "estimateQualityMns() : " + bold + red +
                "Une erreur c'est produite au cours du decoupage de l'image : "
                + image_input + endC,
                file=sys.stderr)
            raise

        if debug >= 2:
            print(cyan + "estimateQualityMns() : " + bold + green +
                  "DECOUPAGE DU RASTER %s AVEC LE VECTEUR %s" %
                  (image_input, vector_study) + endC)
    else:
        image_cut = image_input

    # Definir l'emprise du fichier MNS de reference

    # Decoupage de chaque raster de la liste des rasters
    for raster_input in raster_input_dico:
        raster_cut = raster_cut_dico[raster_input]
        if not cutImageByVector(vector_study, raster_input, raster_cut,
                                pixel_size_x, pixel_size_y, no_data_value, 0,
                                format_raster, format_vector):
            raise NameError(
                cyan + "estimateQualityMns() : " + bold + red +
                "Une erreur c'est produite au cours du decoupage du raster : "
                + raster_input + endC)

    # Gémotrie de l'image
    pixel_size_x, pixel_size_y = getPixelWidthXYImage(image_cut)
    cols, rows, bands = getGeometryImage(image_cut)
    xmin, xmax, ymin, ymax = getEmpriseImage(image_cut)

    if debug >= 3:
        print("Geometrie Image : ")
        print("  cols = " + str(cols))
        print("  rows = " + str(rows))
        print("  xmin = " + str(xmin))
        print("  xmax = " + str(xmax))
        print("  ymin = " + str(ymin))
        print("  ymax = " + str(ymax))
        print("  pixel_size_x = " + str(pixel_size_x))
        print("  pixel_size_y = " + str(pixel_size_y))
        print("\n")

    # Création du dico coordonnées des points en systeme cartographique
    points_random_value_dico = {}
    # liste coordonnées des points au format matrice image brute
    points_coordonnees_image_list = []

    # Selon que l'on utilise le fichier de points d'echantillons ou que l'on recréé a partir des sommets des vecteurs lignes
    if (vector_sample_points_input is None) or (vector_sample_points_input
                                                == ""):

        # ETAPE 3 : DECOUPAGES DES VECTEURS DE REFERENCE D'ENTREE PAR LE VECTEUR D'ETUDE ET LEUR FUSION ET
        #           LECTURE D'UN VECTEUR DE LIGNES ET SAUVEGARDE DES COORDONNEES POINTS DES EXTREMITEES ET LEUR HAUTEUR

        # Découpage des vecteurs de bd réference avec le vecteur zone d'étude
        vector_sample_input_cut_list = []
        for vector_sample in vector_sample_input_list:
            vector_name = os.path.splitext(os.path.basename(vector_sample))[0]
            vector_sample_cut = repertory_output + os.sep + vector_name + SUFFIX_CUT + extension_vector
            vector_sample_input_cut_list.append(vector_sample_cut)
        cutoutVectors(vector_study, vector_sample_input_list,
                      vector_sample_input_cut_list, format_vector)

        # Fusion des vecteurs de bd réference découpés
        fusionVectors(vector_sample_input_cut_list, vector_sample_temp,
                      format_vector)

        # Preparation des colonnes
        names_column_start_point_list = [
            ATTRIBUTE_ID, ATTRIBUTE_Z_INI, ATTRIBUTE_PREC_ALTI
        ]
        names_column_end_point_list = [
            ATTRIBUTE_ID, ATTRIBUTE_Z_FIN, ATTRIBUTE_PREC_ALTI
        ]
        fields_list = [
            ATTRIBUTE_ID, ATTRIBUTE_PREC_ALTI, ATTRIBUTE_Z_INI, ATTRIBUTE_Z_FIN
        ]

        multigeometries2geometries(vector_sample_temp,
                                   vector_sample_temp_clean, fields_list,
                                   "MULTILINESTRING", format_vector)
        points_coordinates_dico = readVectorFileLinesExtractTeminalsPoints(
            vector_sample_temp_clean, names_column_start_point_list,
            names_column_end_point_list, format_vector)

    else:
        # ETAPE 3_BIS : DECOUPAGE DE VECTEURS D'ECHANTILLONS POINTS PAR LE VECTEUR D'EMPRISE ET
        #               LECTURE DES COORDONNES D'ECHANTILLONS DURECTEMENT DANS LE FICHIER VECTEUR POINTS

        # Liste coordonnées des points au format matrice image brute
        cutVectorAll(vector_study, vector_sample_points_input,
                     vector_sample_temp, format_vector)
        points_coordinates_dico = readVectorFilePoints(vector_sample_temp,
                                                       format_vector)

    # ETAPE 4 : PREPARATION DU VECTEUR DE POINTS

    for index_key in points_coordinates_dico:
        # Recuperer les valeurs des coordonnees
        coord_info_list = points_coordinates_dico[index_key]
        coor_x = coord_info_list[0]
        coor_y = coord_info_list[1]
        attribut_dico = coord_info_list[2]

        # Coordonnées des points au format matrice image
        pos_x = int(round((coor_x - xmin) / abs(pixel_size_x)) - 1)
        pos_y = int(round((ymax - coor_y) / abs(pixel_size_y)) - 1)

        if pos_x < 0:
            pos_x = 0
        if pos_x >= cols:
            pos_x = cols - 1
        if pos_y < 0:
            pos_y = 0
        if pos_y >= rows:
            pos_y = rows - 1

        coordonnees_list = [pos_x, pos_y]
        points_coordonnees_image_list.append(coordonnees_list)

        value_ref = 0.0
        if ATTRIBUTE_Z_INI in attribut_dico.keys():
            value_ref = float(attribut_dico[ATTRIBUTE_Z_INI])
        if ATTRIBUTE_Z_FIN in attribut_dico.keys():
            value_ref = float(attribut_dico[ATTRIBUTE_Z_FIN])

        precision_alti = 0.0
        if ATTRIBUTE_PREC_ALTI in attribut_dico.keys():
            precision_alti = float(attribut_dico[ATTRIBUTE_PREC_ALTI])

        point_attr_dico = {
            ATTRIBUTE_ID: index_key,
            ATTRIBUTE_Z_REF: value_ref,
            ATTRIBUTE_PREC_ALTI: precision_alti,
            ATTRIBUTE_Z_MNS: 0.0,
            ATTRIBUTE_Z_DELTA: 0.0
        }

        for raster_input in raster_input_dico:
            field_name = raster_input_dico[raster_input][0][0]
            point_attr_dico[field_name] = 0.0

        points_random_value_dico[index_key] = [[coor_x, coor_y],
                                               point_attr_dico]

    # ETAPE 5 : LECTURE DES DONNEES DE HAUTEURS ISSU DU MNS et autre raster

    # Lecture dans le fichier raster des valeurs
    values_height_list = getPixelsValueListImage(
        image_cut, points_coordonnees_image_list)
    values_others_dico = {}
    for raster_input in raster_input_dico:
        raster_cut = raster_cut_dico[raster_input]
        values_list = getPixelsValueListImage(raster_cut,
                                              points_coordonnees_image_list)
        values_others_dico[raster_input] = values_list

    for i in range(len(points_random_value_dico)):
        value_mns = values_height_list[i]
        value_ref = points_random_value_dico[i][1][ATTRIBUTE_Z_REF]

        points_random_value_dico[i][1][ATTRIBUTE_Z_MNS] = float(value_mns)
        precision_alti = points_random_value_dico[i][1][ATTRIBUTE_PREC_ALTI]
        points_random_value_dico[i][1][ATTRIBUTE_PREC_ALTI] = float(
            precision_alti)
        value_diff = value_ref - value_mns
        points_random_value_dico[i][1][ATTRIBUTE_Z_DELTA] = float(value_diff)

        for raster_input in raster_input_dico:
            field_name = raster_input_dico[raster_input][0][0]
            value_other = values_others_dico[raster_input][i]
            points_random_value_dico[i][1][field_name] = float(value_other)

    # ETAPE 6 : CREATION D'UN VECTEUR DE POINTS AVEC DONNEE COORDONNES POINT ET HAUTEUR REFERENCE ET MNS

    # Suppression des points contenant des valeurs en erreur et en dehors du filtrage
    points_random_value_dico_clean = {}
    for i in range(len(points_random_value_dico)):
        value_ref = points_random_value_dico[i][1][ATTRIBUTE_Z_REF]
        if value_ref != ERROR_VALUE and value_ref > ERROR_MIN_VALUE and value_ref < ERROR_MAX_VALUE:

            points_is_valid = True
            for raster_input in raster_input_dico:
                if len(raster_input_dico[raster_input]) > 1 and len(
                        raster_input_dico[raster_input][1]) > 1:
                    threshold_min = float(
                        raster_input_dico[raster_input][1][0])
                    threshold_max = float(
                        raster_input_dico[raster_input][1][1])
                    field_name = raster_input_dico[raster_input][0][0]
                    value_raster = float(
                        points_random_value_dico[i][1][field_name])
                    if value_raster < threshold_min or value_raster > threshold_max:
                        points_is_valid = False

            if points_is_valid:
                points_random_value_dico_clean[i] = points_random_value_dico[i]

    # Définir les attibuts du fichier résultat
    attribute_dico = {
        ATTRIBUTE_ID: ogr.OFTInteger,
        ATTRIBUTE_PREC_ALTI: ogr.OFTReal,
        ATTRIBUTE_Z_REF: ogr.OFTReal,
        ATTRIBUTE_Z_MNS: ogr.OFTReal,
        ATTRIBUTE_Z_DELTA: ogr.OFTReal
    }

    for raster_input in raster_input_dico:
        field_name = raster_input_dico[raster_input][0][0]
        attribute_dico[field_name] = ogr.OFTReal

    createPointsFromCoordList(attribute_dico, points_random_value_dico_clean,
                              vector_output_temp, epsg, format_vector)

    # Suppression des points en bord de zone d'étude
    bufferVector(vector_study, vector_study_clean, ERODE_EDGE_POINTS, "", 1.0,
                 10, format_vector)
    cutVectorAll(vector_study_clean, vector_output_temp, vector_output, True,
                 format_vector)

    # ETAPE 7 : TRANSFORMATION DU FICHIER .DBF EN .CSV
    dbf_file = repertory_output + os.sep + base_name + EXT_DBF
    csv_file = repertory_output + os.sep + base_name + EXT_CSV

    if debug >= 2:
        print(cyan + "estimateQualityMns() : " + bold + green +
              "Conversion du fichier DBF %s en fichier CSV %s" %
              (dbf_file, csv_file) + endC)

    convertDbf2Csv(dbf_file, csv_file)

    # ETAPE 8 : SUPPRESIONS FICHIERS INTERMEDIAIRES INUTILES

    # Suppression des données intermédiaires
    if not save_results_intermediate:
        if cutting_action:
            if os.path.isfile(image_cut):
                removeFile(image_cut)
        else:
            if os.path.isfile(vector_study):
                removeVectorFile(vector_study)

        for raster_input in raster_input_dico:
            raster_cut = raster_cut_dico[raster_input]
            if os.path.isfile(raster_cut):
                removeFile(raster_cut)

        if os.path.isfile(vector_output_temp):
            removeVectorFile(vector_output_temp)

        if os.path.isfile(vector_study_clean):
            removeVectorFile(vector_study_clean)

        if os.path.isfile(vector_sample_temp):
            removeVectorFile(vector_sample_temp)

        if os.path.isfile(vector_sample_temp_clean):
            removeVectorFile(vector_sample_temp_clean)

        for vector_file in vector_sample_input_cut_list:
            if os.path.isfile(vector_file):
                removeVectorFile(vector_file)

    print(bold + green + "## END : CREATE HEIGHT POINTS FILE FROM MNSE" + endC)

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

    return
Beispiel #2
0
def addDataBaseExo(image_input,
                   image_classif_add_output,
                   class_file_dico,
                   class_buffer_dico,
                   class_sql_dico,
                   path_time_log,
                   format_vector='ESRI Shapefile',
                   extension_raster=".tif",
                   extension_vector=".shp",
                   save_results_intermediate=False,
                   overwrite=True,
                   simplifie_param=10.0):

    # Mise à jour du Log
    starting_event = "addDataBaseExo() : Add data base exogene to classification starting : "
    timeLine(path_time_log, starting_event)

    # Print
    if debug >= 3:
        print(bold + green + "Variables dans la fonction" + endC)
        print(cyan + "addDataBaseExo() : " + endC + "image_input : " +
              str(image_input) + endC)
        print(cyan + "addDataBaseExo() : " + endC +
              "image_classif_add_output : " + str(image_classif_add_output) +
              endC)
        print(cyan + "addDataBaseExo() : " + endC + "class_file_dico : " +
              str(class_file_dico) + endC)
        print(cyan + "addDataBaseExo() : " + endC + "class_buffer_dico : " +
              str(class_buffer_dico) + endC)
        print(cyan + "addDataBaseExo() : " + endC + "class_sql_dico : " +
              str(class_sql_dico) + endC)
        print(cyan + "addDataBaseExo() : " + endC + "path_time_log : " +
              str(path_time_log) + endC)
        print(cyan + "addDataBaseExo() : " + endC + "format_vector : " +
              str(format_vector) + endC)
        print(cyan + "addDataBaseExo() : " + endC + "extension_raster : " +
              str(extension_raster) + endC)
        print(cyan + "addDataBaseExo() : " + endC + "extension_vector : " +
              str(extension_vector) + endC)
        print(cyan + "addDataBaseExo() : " + endC +
              "save_results_intermediate : " + str(save_results_intermediate) +
              endC)
        print(cyan + "addDataBaseExo() : " + endC + "overwrite : " +
              str(overwrite) + endC)

    # Constantes
    FOLDER_MASK_TEMP = 'Mask_'
    FOLDER_FILTERING_TEMP = 'Filt_'
    FOLDER_CUTTING_TEMP = 'Cut_'
    FOLDER_BUFF_TEMP = 'Buff_'

    SUFFIX_MASK_CRUDE = '_mcrude'
    SUFFIX_MASK = '_mask'
    SUFFIX_FUSION = '_info'
    SUFFIX_VECTOR_FILTER = "_filt"
    SUFFIX_VECTOR_CUT = '_decoup'
    SUFFIX_VECTOR_BUFF = '_buff'

    CODAGE = "uint16"

    # ETAPE 1 : NETTOYER LES DONNEES EXISTANTES
    if debug >= 2:
        print(cyan + "addDataBaseExo() : " + bold + green +
              "NETTOYAGE ESPACE DE TRAVAIL..." + endC)

    # Nom de base de l'image
    image_name = os.path.splitext(os.path.basename(image_input))[0]

    # Nettoyage d'anciennes données résultat

    # Si le fichier résultat existent deja et que overwrite n'est pas activé
    check = os.path.isfile(image_classif_add_output)
    if check and not overwrite:
        print(bold + yellow + "addDataBaseExo() : " + endC +
              image_classif_add_output +
              " has already added bd exo and will not be added again." + endC)
    else:
        if check:
            try:
                removeFile(image_classif_add_output
                           )  # Tentative de suppression du fichier
            except Exception:
                pass  # Si le fichier ne peut pas être supprimé, on suppose qu'il n'existe pas et on passe à la suite

        # Définition des répertoires temporaires
        repertory_output = os.path.dirname(image_classif_add_output)
        repertory_mask_temp = repertory_output + os.sep + FOLDER_MASK_TEMP + image_name
        repertory_samples_filtering_temp = repertory_output + os.sep + FOLDER_FILTERING_TEMP + image_name
        repertory_samples_cutting_temp = repertory_output + os.sep + FOLDER_CUTTING_TEMP + image_name
        repertory_samples_buff_temp = repertory_output + os.sep + FOLDER_BUFF_TEMP + image_name

        if debug >= 4:
            print(repertory_mask_temp)
            print(repertory_samples_filtering_temp)
            print(repertory_samples_cutting_temp)
            print(repertory_samples_buff_temp)

        # Creer les répertoires temporaire si ils n'existent pas
        if not os.path.isdir(repertory_output):
            os.makedirs(repertory_output)
        if not os.path.isdir(repertory_mask_temp):
            os.makedirs(repertory_mask_temp)
        if not os.path.isdir(repertory_samples_filtering_temp):
            os.makedirs(repertory_samples_filtering_temp)
        if not os.path.isdir(repertory_samples_cutting_temp):
            os.makedirs(repertory_samples_cutting_temp)
        if not os.path.isdir(repertory_samples_buff_temp):
            os.makedirs(repertory_samples_buff_temp)

        # Nettoyer les répertoires temporaire si ils ne sont pas vide
        cleanTempData(repertory_mask_temp)
        cleanTempData(repertory_samples_filtering_temp)
        cleanTempData(repertory_samples_cutting_temp)
        cleanTempData(repertory_samples_buff_temp)

        if debug >= 2:
            print(cyan + "addDataBaseExo() : " + bold + green +
                  "... FIN NETTOYAGE" + endC)

        # ETAPE 2 : CREER UN SHAPE DE DECOUPE

        if debug >= 2:
            print(cyan + "addDataBaseExo() : " + bold + green +
                  "SHAPE DE DECOUPE..." + endC)

        # 2.1 : Création des masques délimitant l'emprise de la zone par image

        vector_mask = repertory_mask_temp + os.sep + image_name + SUFFIX_MASK_CRUDE + extension_vector
        createVectorMask(image_input, vector_mask)

        # 2.2 : Simplification du masque global

        vector_simple_mask_cut = repertory_mask_temp + os.sep + image_name + SUFFIX_MASK + extension_vector
        simplifyVector(vector_mask, vector_simple_mask_cut, simplifie_param,
                       format_vector)

        if debug >= 2:
            print(cyan + "addDataBaseExo() : " + bold + green +
                  "...FIN SHAPE DE DECOUPEE" + endC)

        # ETAPE 3 : DECOUPER BUFFERISER LES VECTEURS ET FUSIONNER

        if debug >= 2:
            print(cyan + "addDataBaseExo() : " + bold + green +
                  "MISE EN PLACE DES TAMPONS..." + endC)

        image_combined_list = []
        # Parcours du dictionnaire associant les macroclasses aux noms de fichiers
        for macroclass_label in class_file_dico:
            vector_fusion_list = []
            for index_info in range(len(class_file_dico[macroclass_label])):
                input_vector = class_file_dico[macroclass_label][index_info]
                vector_name = os.path.splitext(
                    os.path.basename(input_vector))[0]
                output_vector_filtered = repertory_samples_filtering_temp + os.sep + vector_name + SUFFIX_VECTOR_FILTER + extension_vector
                output_vector_cut = repertory_samples_cutting_temp + os.sep + vector_name + SUFFIX_VECTOR_CUT + extension_vector
                output_vector_buff = repertory_samples_buff_temp + os.sep + vector_name + SUFFIX_VECTOR_BUFF + extension_vector
                sql_expression = class_sql_dico[macroclass_label][index_info]
                buffer_str = class_buffer_dico[macroclass_label][index_info]
                buff = 0.0
                col_name_buf = ""
                try:
                    buff = float(buffer_str)
                except:
                    col_name_buf = buffer_str
                    print(
                        cyan + "addDataBaseExo() : " + bold + green +
                        "Pas de valeur buffer mais un nom de colonne pour les valeur à bufferiser : "
                        + endC + col_name_buf)

                if os.path.isfile(input_vector):
                    if debug >= 3:
                        print(cyan + "addDataBaseExo() : " + endC +
                              "input_vector : " + str(input_vector) + endC)
                        print(cyan + "addDataBaseExo() : " + endC +
                              "output_vector_filtered : " +
                              str(output_vector_filtered) + endC)
                        print(cyan + "addDataBaseExo() : " + endC +
                              "output_vector_cut : " + str(output_vector_cut) +
                              endC)
                        print(cyan + "addDataBaseExo() : " + endC +
                              "output_vector_buff : " +
                              str(output_vector_buff) + endC)
                        print(cyan + "addDataBaseExo() : " + endC + "buff : " +
                              str(buff) + endC)
                        print(cyan + "addDataBaseExo() : " + endC + "sql : " +
                              str(sql_expression) + endC)

                    # 3.0 : Recuperer les vecteurs d'entrée et filtree selon la requete sql par ogr2ogr
                    if sql_expression != "":
                        names_attribut_list = getAttributeNameList(
                            input_vector, format_vector)
                        column = "'"
                        for name_attribut in names_attribut_list:
                            column += name_attribut + ", "
                        column = column[0:len(column) - 2]
                        column += "'"
                        ret = filterSelectDataVector(input_vector,
                                                     output_vector_filtered,
                                                     column, sql_expression,
                                                     format_vector)
                        if not ret:
                            print(
                                cyan + "addDataBaseExo() : " + bold + yellow +
                                "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte"
                                % (sql_expression) + endC)
                            output_vector_filtered = input_vector
                    else:
                        print(cyan + "addDataBaseExo() : " + bold + green +
                              "Pas de filtrage sur le fichier du nom : " +
                              endC + output_vector_filtered)
                        output_vector_filtered = input_vector

                    # 3.1 : Découper le vecteur selon l'empise de l'image d'entrée
                    cutoutVectors(vector_simple_mask_cut,
                                  [output_vector_filtered],
                                  [output_vector_cut], format_vector)

                    # 3.2 : Bufferiser lesvecteurs découpé avec la valeur défini dans le dico ou trouver dans la base du vecteur lui même si le nom de la colonne est passée dans le dico
                    if os.path.isfile(output_vector_cut) and (
                        (buff != 0) or (col_name_buf != "")):
                        bufferVector(output_vector_cut, output_vector_buff,
                                     buff, col_name_buf, 1.0, 10,
                                     format_vector)
                    else:
                        print(cyan + "addDataBaseExo() : " + bold + green +
                              "Pas de buffer sur le fichier du nom : " + endC +
                              output_vector_cut)
                        output_vector_buff = output_vector_cut

                    # 3.3 : Si un shape résulat existe l'ajouté à la liste de fusion
                    if os.path.isfile(output_vector_buff):
                        vector_fusion_list.append(output_vector_buff)
                        if debug >= 3:
                            print("file for fusion : " + output_vector_buff)
                    else:
                        print(bold + yellow +
                              "pas de fichiers avec ce nom : " + endC +
                              output_vector_buff)

                else:
                    print(cyan + "addDataBaseExo() : " + bold + yellow +
                          "Pas de fichier du nom : " + endC + input_vector)

            # 3.4 : Fusionner les shapes transformés d'une même classe, rasterization et labelisations des vecteurs
            # Si une liste de fichier shape existe
            if not vector_fusion_list:
                print(bold + yellow + "Pas de fusion sans donnee a fusionnee" +
                      endC)
            else:
                # Rasterization et BandMath des fichiers shapes
                raster_list = []
                for vector in vector_fusion_list:
                    if debug >= 3:
                        print(cyan + "addDataBaseExo() : " + endC +
                              "Rasterization : " + vector + " label : " +
                              macroclass_label)
                    raster_output = os.path.splitext(
                        vector)[0] + extension_raster

                    # Rasterisation
                    rasterizeBinaryVector(vector, image_input, raster_output,
                                          macroclass_label, CODAGE)
                    raster_list.append(raster_output)

                if debug >= 3:
                    print(cyan + "addDataBaseExo() : " + endC +
                          "nombre d'images a combiner : " +
                          str(len(raster_list)))

                # Liste les images raster combined and sample
                image_combined = repertory_output + os.sep + image_name + '_' + str(
                    macroclass_label) + SUFFIX_FUSION + extension_raster
                image_combined_list.append(image_combined)

                # Fusion des images raster en une seule
                mergeListRaster(raster_list, image_combined, CODAGE)

        if debug >= 2:
            print(cyan + "addDataBaseExo() : " + bold + green +
                  "FIN DE L AFFECTATION DES TAMPONS" + endC)

        # ETAPE 4 : ASSEMBLAGE DE L'IMAGE CLASSEE ET DES BD EXOS
        if debug >= 2:
            print(cyan + "addDataBaseExo() : " + bold + green +
                  "ASSEMBLAGE..." + endC)

        # Ajout de l'image de classification a la liste des image bd conbinées
        image_combined_list.append(image_input)
        # Fusion les images avec la classification
        mergeListRaster(image_combined_list, image_classif_add_output, CODAGE)
        if debug >= 2:
            print(cyan + "addDataBaseExo() : " + bold + green + "FIN" + endC)

    # ETAPE 5 : SUPPRESIONS FICHIERS INTERMEDIAIRES INUTILES

    # Suppression des données intermédiaires
    if not save_results_intermediate:

        image_combined_list.remove(image_input)
        for to_delete in image_combined_list:
            removeFile(to_delete)

        # Suppression des repertoires temporaires
        deleteDir(repertory_mask_temp)
        deleteDir(repertory_samples_filtering_temp)
        deleteDir(repertory_samples_cutting_temp)
        deleteDir(repertory_samples_buff_temp)

    # Mise à jour du Log
    ending_event = "addDataBaseExo() : Add data base exogene to classification ending : "
    timeLine(path_time_log, ending_event)

    return
Beispiel #3
0
def comparareClassificationToReferenceGrid(image_input,
                                           vector_cut_input,
                                           vector_sample_input,
                                           vector_grid_input,
                                           vector_grid_output,
                                           size_grid,
                                           field_value_verif,
                                           no_data_value,
                                           path_time_log,
                                           epsg=2154,
                                           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 = "comparareClassificationToReferenceGrid() : starting : "
    timeLine(path_time_log, starting_event)

    print(endC)
    print(bold + green +
          "## START : COMPARE QUALITY FROM CLASSIF IMAGE BY GRID" + endC)
    print(endC)

    if debug >= 2:
        print(
            bold + green +
            "comparareClassificationToReferenceGrid() : Variables dans la fonction"
            + endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "image_input : " + str(image_input) + endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "vector_cut_input : " + str(vector_cut_input) + endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "vector_sample_input : " + str(vector_sample_input) + endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "vector_grid_input : " + str(vector_grid_input) + endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "vector_grid_output : " + str(vector_grid_output) + endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "size_grid : " + str(size_grid) + endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "field_value_verif : " + str(field_value_verif))
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "no_data_value : " + str(no_data_value))
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "path_time_log : " + str(path_time_log) + endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "epsg  : " + str(epsg) + endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "format_raster : " + str(format_raster) + endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "format_vector : " + str(format_vector) + endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "extension_raster : " + str(extension_raster) + endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "extension_vector : " + str(extension_vector) + endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "save_results_intermediate : " + str(save_results_intermediate) +
              endC)
        print(cyan + "comparareClassificationToReferenceGrid() : " + endC +
              "overwrite : " + str(overwrite) + endC)

    # ETAPE 0 : PREPARATION DES FICHIERS INTERMEDIAIRES'

    CODAGE = "uint16"
    SUFFIX_STUDY = '_study'
    SUFFIX_TEMP = '_temp'
    SUFFIX_FUSION = '_other_fusion'

    NONE_VALUE_QUANTITY = -1.0
    FIELD_VALUE_OTHER = 65535

    FIELD_NAME_ID = "id"
    FIELD_NAME_RATE_BUILD = "rate_build"
    FIELD_NAME_RATE_OTHER = "rate_other"
    FIELD_NAME_SREF_BUILD = "sref_build"
    FIELD_NAME_SCLA_BUILD = "scla_build"
    FIELD_NAME_SREF_OTHER = "sref_other"
    FIELD_NAME_SCLA_OTHER = "scla_other"
    FIELD_NAME_KAPPA = "kappa"
    FIELD_NAME_ACCURACY = "accuracy"

    pixel_size_x, pixel_size_y = getPixelWidthXYImage(image_input)

    repertory_output = os.path.dirname(vector_grid_output)
    base_name = os.path.splitext(os.path.basename(vector_grid_output))[0]

    vector_study = repertory_output + os.sep + base_name + SUFFIX_STUDY + extension_vector
    vector_grid_temp = repertory_output + os.sep + base_name + SUFFIX_TEMP + extension_vector
    image_raster_other_fusion = repertory_output + os.sep + base_name + SUFFIX_FUSION + extension_raster

    # ETAPE 0 : VERIFICATION

    # Verification de la valeur de la nomemclature à verifier
    if field_value_verif >= FIELD_VALUE_OTHER:
        print(
            cyan + "comparareClassificationToReferenceGrid() : " + bold + red +
            "Attention de valeur de nomenclature à vérifier  : " +
            str(field_value_verif) +
            " doit être inferieur à la valeur de fusion des valeur autre arbitraire de : "
            + str(FIELD_VALUE_OTHER) + endC,
            file=sys.stderr)
        sys.exit(1)  #exit with an error code

    # ETAPE 1 : DEFINIR UN SHAPE ZONE D'ETUDE

    if (not vector_cut_input is None) and (vector_cut_input != "") and (
            os.path.isfile(vector_cut_input)):
        cutting_action = True
        vector_study = vector_cut_input
    else:
        cutting_action = False
        createVectorMask(image_input, vector_study)

    # ETAPE 2 : UNIFORMISATION DE LA ZONE OTHER

    # Réalocation des valeurs de classification pour les valeurs autre que le bati
    change_reaff_value_list = []
    reaff_value_list = identifyPixelValues(image_input)
    if field_value_verif in reaff_value_list:
        reaff_value_list.remove(field_value_verif)
    if no_data_value in reaff_value_list:
        reaff_value_list.remove(no_data_value)
    for elem in reaff_value_list:
        change_reaff_value_list.append(FIELD_VALUE_OTHER)
    reallocateClassRaster(image_input, image_raster_other_fusion,
                          reaff_value_list, change_reaff_value_list)

    # ETAPE 3 : CREATION DE LA GRILLE SUR LA ZONE D'ETUDE

    # Définir les attibuts du fichier
    attribute_dico = {
        FIELD_NAME_ID: ogr.OFTInteger,
        FIELD_NAME_RATE_BUILD: ogr.OFTReal,
        FIELD_NAME_RATE_OTHER: ogr.OFTReal,
        FIELD_NAME_SREF_BUILD: ogr.OFTReal,
        FIELD_NAME_SCLA_BUILD: ogr.OFTReal,
        FIELD_NAME_SREF_OTHER: ogr.OFTReal,
        FIELD_NAME_SCLA_OTHER: ogr.OFTReal,
        FIELD_NAME_KAPPA: ogr.OFTReal,
        FIELD_NAME_ACCURACY: ogr.OFTReal
    }
    nb_polygon = 0

    if (not vector_grid_input is None) and (vector_grid_input != "") and (
            os.path.isfile(vector_grid_input)):
        # Utilisation du fichier grille d'entrée

        # Recopie du fichier grille d'entrée vers le fichier grille de sortie
        copyVectorFile(vector_grid_input, vector_grid_output)

        # Ajout des champs au fichier grille de sortie
        for field_name in attribute_dico:
            addNewFieldVector(vector_grid_output, field_name,
                              attribute_dico[field_name], None, None, None,
                              format_vector)

        # Mettre le champs "id" identifiant du carré de l'élément de la grille
        nb_polygon = updateIndexVector(vector_grid_output, FIELD_NAME_ID,
                                       format_vector)

    else:
        # Si il n'existe pas de fichier grille on en créer un avec la valeur de size_grid

        # Creer le fichier grille
        nb_polygon = createGridVector(vector_study, vector_grid_temp,
                                      size_grid, size_grid, attribute_dico,
                                      overwrite, epsg, format_vector)

        # Découper la grille avec le shape zone d'étude
        cutVectorAll(vector_study, vector_grid_temp, vector_grid_output,
                     format_vector)

    # ETAPE 4 : CALCUL DE L'INDICATEUR DE QUALITE POUR CHAQUE CASE DE LA GRILLE

    if debug >= 2:
        print(bold + "nb_polygon = " + endC + str(nb_polygon) + "\n")

    # Pour chaque polygone existant
    sum_rate_quantity_build = 0
    nb_rate_sum = 0
    size_area_pixel = abs(pixel_size_x * pixel_size_y)

    for id_polygon in range(nb_polygon):
        geom_list = getGeomPolygons(vector_grid_output, FIELD_NAME_ID,
                                    id_polygon, format_vector)
        if geom_list is not None and geom_list != []:  # and (id_polygon == 24 or id_polygon == 30):

            if debug >= 1:
                print(cyan + "comparareClassificationToReferenceGrid() : " +
                      bold + green +
                      "Calcul de la matrice pour le polygon n°: " +
                      str(id_polygon) + endC)

            geom = geom_list[0]
            class_ref_list, class_pro_list, rate_quantity_list, kappa, accuracy, matrix = computeQualityIndiceRateQuantity(
                image_raster_other_fusion, vector_sample_input,
                repertory_output, base_name + str(id_polygon), geom, size_grid,
                pixel_size_x, pixel_size_y, field_value_verif,
                FIELD_VALUE_OTHER, no_data_value, epsg, format_raster,
                format_vector, extension_raster, extension_vector, overwrite,
                save_results_intermediate)

            # Si les calculs indicateurs de qualité sont ok
            if debug >= 2:
                print(matrix)
            if matrix != None and matrix != [] and matrix[0] != []:

                # Récuperer la quantité de bati et calcul de la surface de référence et de la surface de classification (carreau entier ou pas!)
                if len(class_ref_list) == 2 and len(
                        class_pro_list
                ) == 2:  # Cas ou l'on a des pixels de build et other (en ref et en prod)
                    rate_quantity_build = rate_quantity_list[0]
                    rate_quantity_other = rate_quantity_list[1]
                    size_area_ref_build = (matrix[0][0] +
                                           matrix[0][1]) * size_area_pixel
                    size_area_classif_build = (matrix[0][0] +
                                               matrix[1][0]) * size_area_pixel
                    size_area_ref_other = (matrix[1][0] +
                                           matrix[1][1]) * size_area_pixel
                    size_area_classif_other = (matrix[0][1] +
                                               matrix[1][1]) * size_area_pixel
                    sum_rate_quantity_build += rate_quantity_build
                    nb_rate_sum += 1

                else:  # Cas ou l'on a uniquement des pixels de build OU uniquement des pixels de other

                    if class_ref_list[
                            0] == field_value_verif:  # Cas ou l'on a uniquement des pixels references build
                        rate_quantity_build = rate_quantity_list[0]
                        rate_quantity_other = NONE_VALUE_QUANTITY
                        size_area_ref_other = 0

                        if len(
                                class_pro_list
                        ) == 2:  # Cas ou l'on a des pixels de prod build et other
                            size_area_ref_build = (
                                matrix[0][0] + matrix[0][1]) * size_area_pixel
                            size_area_classif_build = matrix[0][
                                0] * size_area_pixel
                            size_area_classif_other = matrix[0][
                                1] * size_area_pixel

                        else:
                            size_area_ref_build = matrix[0][0] * size_area_pixel
                            if class_pro_list[
                                    0] == field_value_verif:  # Cas ou l'on a uniquement des pixels prod build
                                size_area_classif_build = matrix[0][
                                    0] * size_area_pixel
                                size_area_classif_other = 0

                            else:  # Cas ou l'on a uniquement des pixels prod other
                                size_area_classif_build = 0
                                size_area_classif_other = matrix[0][
                                    0] * size_area_pixel

                    else:  # Cas ou l'on a uniquement des pixels references other
                        rate_quantity_build = NONE_VALUE_QUANTITY
                        rate_quantity_other = rate_quantity_list[0]
                        size_area_ref_build = 0

                        if len(
                                class_pro_list
                        ) == 2:  # Cas ou l'on a des pixels de prod build et other
                            size_area_ref_other = (
                                matrix[0][0] + matrix[0][1]) * size_area_pixel
                            size_area_classif_build = matrix[0][
                                0] * size_area_pixel
                            size_area_classif_other = matrix[0][
                                1] * size_area_pixel

                        else:
                            size_area_ref_other = matrix[0][0] * size_area_pixel
                            if class_pro_list[
                                    0] == field_value_verif:  # Cas ou l'on a uniquement des pixels prod build
                                size_area_classif_build = matrix[0][
                                    0] * size_area_pixel
                                size_area_classif_other = 0

                            else:  # Cas ou l'on a uniquement des pixels prod other
                                size_area_classif_build = 0
                                size_area_classif_other = matrix[0][
                                    0] * size_area_pixel

                # Mettre à jour ses éléments du carré de la grille
                setAttributeValues(
                    vector_grid_output, FIELD_NAME_ID, id_polygon, {
                        FIELD_NAME_RATE_BUILD: rate_quantity_build,
                        FIELD_NAME_RATE_OTHER: rate_quantity_other,
                        FIELD_NAME_SREF_BUILD: size_area_ref_build,
                        FIELD_NAME_SCLA_BUILD: size_area_classif_build,
                        FIELD_NAME_SREF_OTHER: size_area_ref_other,
                        FIELD_NAME_SCLA_OTHER: size_area_classif_other,
                        FIELD_NAME_KAPPA: kappa,
                        FIELD_NAME_ACCURACY: accuracy
                    }, format_vector)

    # Calcul de la moyenne
    if nb_rate_sum != 0:
        average_quantity_build = sum_rate_quantity_build / nb_rate_sum
    else:
        average_quantity_build = 0
    if debug >= 2:
        print(bold + "nb_polygon_used = " + endC + str(nb_rate_sum))
        print(bold + "average_quantity_build = " + endC +
              str(average_quantity_build) + "\n")

    # ETAPE 5 : SUPPRESIONS FICHIERS INTERMEDIAIRES INUTILES

    # Suppression des données intermédiairess
    if not save_results_intermediate:

        if not cutting_action:
            if os.path.isfile(vector_study):
                removeVectorFile(vector_study)

        if os.path.isfile(image_raster_other_fusion):
            removeFile(image_raster_other_fusion)

        if os.path.isfile(vector_grid_temp):
            removeVectorFile(vector_grid_temp)

    print(endC)
    print(bold + green +
          "## END : COMPARE QUALITY FROM CLASSIF IMAGE BY GRID" + endC)
    print(endC)

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

    return average_quantity_build
Beispiel #4
0
def estimateQualityClassification(image_input,
                                  vector_cut_input,
                                  vector_sample_input,
                                  vector_output,
                                  nb_dot,
                                  no_data_value,
                                  column_name_vector,
                                  column_name_ref,
                                  column_name_class,
                                  path_time_log,
                                  epsg=2154,
                                  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 = "estimateQualityClassification() : Masks creation starting : "
    timeLine(path_time_log, starting_event)

    print(endC)
    print(bold + green +
          "## START : CREATE PRINT POINTS FILE FROM CLASSIF IMAGE" + endC)
    print(endC)

    if debug >= 2:
        print(bold + green +
              "estimateQualityClassification() : Variables dans la fonction" +
              endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "image_input : " + str(image_input) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "vector_cut_input : " + str(vector_cut_input) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "vector_sample_input : " + str(vector_sample_input) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "vector_output : " + str(vector_output) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "nb_dot : " + str(nb_dot) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "no_data_value : " + str(no_data_value) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "column_name_vector : " + str(column_name_vector) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "column_name_ref : " + str(column_name_ref) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "column_name_class : " + str(column_name_class) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "path_time_log : " + str(path_time_log) + endC)
        print(cyan + "estimateQualityClassification() : " + endC + "epsg  : " +
              str(epsg) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "format_raster : " + str(format_raster) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "format_vector : " + str(format_vector) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "extension_raster : " + str(extension_raster) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "extension_vector : " + str(extension_vector) + endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "save_results_intermediate : " + str(save_results_intermediate) +
              endC)
        print(cyan + "estimateQualityClassification() : " + endC +
              "overwrite : " + str(overwrite) + endC)

    # ETAPE 0 : PREPARATION DES FICHIERS INTERMEDIAIRES

    CODAGE = "uint16"

    SUFFIX_STUDY = '_study'
    SUFFIX_CUT = '_cut'
    SUFFIX_TEMP = '_temp'
    SUFFIX_SAMPLE = '_sample'

    repertory_output = os.path.dirname(vector_output)
    base_name = os.path.splitext(os.path.basename(vector_output))[0]

    vector_output_temp = repertory_output + os.sep + base_name + SUFFIX_TEMP + extension_vector
    raster_study = repertory_output + os.sep + base_name + SUFFIX_STUDY + extension_raster
    vector_study = repertory_output + os.sep + base_name + SUFFIX_STUDY + extension_vector
    raster_cut = repertory_output + os.sep + base_name + SUFFIX_CUT + extension_raster
    vector_sample_temp = repertory_output + os.sep + base_name + SUFFIX_SAMPLE + SUFFIX_TEMP + extension_vector

    # Mise à jour des noms de champs
    input_ref_col = ""
    val_ref = 0
    if (column_name_vector != "") and (not column_name_vector is None):
        input_ref_col = column_name_vector
    if (column_name_ref != "") and (not column_name_ref is None):
        val_ref_col = column_name_ref
    if (column_name_class != "") and (not column_name_class is None):
        val_class_col = column_name_class

    # ETAPE 1 : DEFINIR UN SHAPE ZONE D'ETUDE

    if (not vector_cut_input is None) and (vector_cut_input != "") and (
            os.path.isfile(vector_cut_input)):
        cutting_action = True
        vector_study = vector_cut_input

    else:
        cutting_action = False
        createVectorMask(image_input, vector_study)

    # ETAPE 2 : DECOUPAGE DU RASTEUR PAR LE VECTEUR D'EMPRISE SI BESOIN

    if cutting_action:
        # Identification de la tailles de pixels en x et en y
        pixel_size_x, pixel_size_y = getPixelWidthXYImage(image_input)

        # Si le fichier de sortie existe deja le supprimer
        if os.path.exists(raster_cut):
            removeFile(raster_cut)

        # Commande de découpe
        if not cutImageByVector(vector_study, image_input, raster_cut,
                                pixel_size_x, pixel_size_y, no_data_value, 0,
                                format_raster, format_vector):
            raise NameError(
                cyan + "estimateQualityClassification() : " + bold + red +
                "Une erreur c'est produite au cours du decoupage de l'image : "
                + image_input + endC)
        if debug >= 2:
            print(cyan + "estimateQualityClassification() : " + bold + green +
                  "DECOUPAGE DU RASTER %s AVEC LE VECTEUR %s" %
                  (image_input, vector_study) + endC)
    else:
        raster_cut = image_input

    # ETAPE 3 : CREATION DE LISTE POINTS AVEC DONNEE ISSU D'UN FICHIER RASTER

    # Gémotrie de l'image
    cols, rows, bands = getGeometryImage(raster_cut)
    xmin, xmax, ymin, ymax = getEmpriseImage(raster_cut)
    pixel_width, pixel_height = getPixelWidthXYImage(raster_cut)

    if debug >= 2:
        print("cols : " + str(cols))
        print("rows : " + str(rows))
        print("bands : " + str(bands))
        print("xmin : " + str(xmin))
        print("ymin : " + str(ymin))
        print("xmax : " + str(xmax))
        print("ymax : " + str(ymax))
        print("pixel_width : " + str(pixel_width))
        print("pixel_height : " + str(pixel_height))

    # ETAPE 3-1 : CAS CREATION D'UN FICHIER DE POINTS PAR TIRAGE ALEATOIRE DANS LA MATRICE IMAGE
    if (vector_sample_input is None) or (vector_sample_input == ""):
        is_sample_file = False

        # Les dimensions de l'image
        nb_pixels = abs(cols * rows)

        # Tirage aléatoire des points
        drawn_dot_list = []
        while len(drawn_dot_list) < nb_dot:
            val = random.randint(0, nb_pixels)
            if not val in drawn_dot_list:
                drawn_dot_list.append(val)

        # Creation d'un dico index valeur du tirage et attibuts pos_x, pos_y et value pixel
        points_random_value_dico = {}

        points_coordonnees_list = []
        for point in drawn_dot_list:
            pos_y = point // cols
            pos_x = point % cols
            coordonnees_list = [pos_x, pos_y]
            points_coordonnees_list.append(coordonnees_list)

        # Lecture dans le fichier raster des valeurs
        values_list = getPixelsValueListImage(raster_cut,
                                              points_coordonnees_list)
        print(values_list)
        for idx_point in range(len(drawn_dot_list)):
            val_class = values_list[idx_point]
            coordonnees_list = points_coordonnees_list[idx_point]
            pos_x = coordonnees_list[0]
            pos_y = coordonnees_list[1]
            coor_x = xmin + (pos_x * abs(pixel_width))
            coor_y = ymax - (pos_y * abs(pixel_height))
            point_attr_dico = {
                "Ident": idx_point,
                val_ref_col: int(val_ref),
                val_class_col: int(val_class)
            }
            points_random_value_dico[idx_point] = [[coor_x, coor_y],
                                                   point_attr_dico]

            if debug >= 4:
                print("idx_point : " + str(idx_point))
                print("pos_x : " + str(pos_x))
                print("pos_y : " + str(pos_y))
                print("coor_x : " + str(coor_x))
                print("coor_y : " + str(coor_y))
                print("val_class : " + str(val_class))
                print("")

    # ETAPE 3-2 : CAS D'UN FICHIER DE POINTS DEJA EXISTANT MISE A JOUR DE LA DONNEE ISSU Du RASTER
    else:
        # Le fichier de points d'analyses existe
        is_sample_file = True
        cutVectorAll(vector_study, vector_sample_input, vector_sample_temp,
                     format_vector)
        if input_ref_col != "":
            points_coordinates_dico = readVectorFilePoints(
                vector_sample_temp, [input_ref_col], format_vector)
        else:
            points_coordinates_dico = readVectorFilePoints(
                vector_sample_temp, [], format_vector)

        # Création du dico
        points_random_value_dico = {}

        points_coordonnees_list = []
        for index_key in points_coordinates_dico:
            # Recuperer les valeurs des coordonnees
            coord_info_list = points_coordinates_dico[index_key]
            coor_x = coord_info_list[0]
            coor_y = coord_info_list[1]
            pos_x = int(round((coor_x - xmin) / abs(pixel_width)))
            pos_y = int(round((ymax - coor_y) / abs(pixel_height)))
            coordonnees_list = [pos_x, pos_y]
            points_coordonnees_list.append(coordonnees_list)

        # Lecture dans le fichier raster des valeurs
        values_list = getPixelsValueListImage(raster_cut,
                                              points_coordonnees_list)

        for index_key in points_coordinates_dico:
            # Récuperer les valeurs des coordonnees
            coord_info_list = points_coordinates_dico[index_key]
            coor_x = coord_info_list[0]
            coor_y = coord_info_list[1]
            # Récupérer la classe de référence dans le vecteur d'entrée
            if input_ref_col != "":
                label = coord_info_list[2]
                val_ref = label.get(input_ref_col)
            # Récupérer la classe issue du raster d'entrée
            val_class = values_list[index_key]
            # Création du dico contenant identifiant du point, valeur de référence, valeur du raster d'entrée
            point_attr_dico = {
                "Ident": index_key,
                val_ref_col: int(val_ref),
                val_class_col: int(val_class)
            }
            if debug >= 4:
                print("point_attr_dico: " + str(point_attr_dico))
            points_random_value_dico[index_key] = [[coor_x, coor_y],
                                                   point_attr_dico]

    # ETAPE 4 : CREATION ET DECOUPAGE DU FICHIER VECTEUR RESULTAT PAR LE SHAPE D'ETUDE

    # Creer le fichier de points
    if is_sample_file and os.path.exists(vector_sample_temp):

        attribute_dico = {val_class_col: ogr.OFTInteger}
        # Recopie du fichier
        removeVectorFile(vector_output_temp)
        copyVectorFile(vector_sample_temp, vector_output_temp)

        # Ajout des champs au fichier de sortie
        for field_name in attribute_dico:
            addNewFieldVector(vector_output_temp, field_name,
                              attribute_dico[field_name], 0, None, None,
                              format_vector)

        # Préparation des donnees
        field_new_values_list = []
        for index_key in points_random_value_dico:
            point_attr_dico = points_random_value_dico[index_key][1]
            point_attr_dico.pop(val_ref_col, None)
            field_new_values_list.append(point_attr_dico)

        # Ajout des donnees
        setAttributeValuesList(vector_output_temp, field_new_values_list,
                               format_vector)

    else:
        # Définir les attibuts du fichier résultat
        attribute_dico = {
            "Ident": ogr.OFTInteger,
            val_ref_col: ogr.OFTInteger,
            val_class_col: ogr.OFTInteger
        }

        createPointsFromCoordList(attribute_dico, points_random_value_dico,
                                  vector_output_temp, epsg, format_vector)

    # Découpage du fichier de points d'echantillons
    cutVectorAll(vector_study, vector_output_temp, vector_output,
                 format_vector)

    # ETAPE 5 : SUPPRESIONS FICHIERS INTERMEDIAIRES INUTILES

    # Suppression des données intermédiaires
    if not save_results_intermediate:
        if cutting_action:
            removeFile(raster_cut)
        else:
            removeVectorFile(vector_study)
            removeFile(raster_study)
        if is_sample_file:
            removeVectorFile(vector_sample_temp)
        removeVectorFile(vector_output_temp)

    print(endC)
    print(bold + green +
          "## END : CREATE PRINT POINTS FILE FROM CLASSIF IMAGE" + endC)
    print(endC)

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

    return
Beispiel #5
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
Beispiel #6
0
def createDifference(image_ortho_input,
                     image_mns_input,
                     image_mnt_input,
                     bd_vector_input_list,
                     zone_buffer_dico,
                     departments_list,
                     image_difference_output,
                     vector_difference_output,
                     fileld_bd_raster,
                     simplifie_param,
                     threshold_ndvi,
                     threshold_difference,
                     filter_difference_0,
                     filter_difference_1,
                     path_time_log,
                     format_vector='ESRI Shapefile',
                     extension_raster=".tif",
                     extension_vector=".shp",
                     save_results_intermediate=False,
                     channel_order=['Red', 'Green', 'Blue', 'NIR'],
                     overwrite=True):

    # Mise à jour du Log
    starting_event = "createDifference() : create macro samples starting : "
    timeLine(path_time_log, starting_event)

    # constantes
    CODAGE = "float"

    FOLDER_MASK_TEMP = 'Mask_'
    FOLDER_CUTTING_TEMP = 'Cut_'
    FOLDER_BUFF_TEMP = 'Buff_'
    FOLDER_RESULT_TEMP = 'Tmp_'

    SUFFIX_MASK_CRUDE = '_mcrude'
    SUFFIX_MASK = '_mask'
    SUFFIX_FILTERED = '_filtered'
    SUFFIX_VECTOR_CUT = '_decoup'
    SUFFIX_VECTOR_BUFF = '_buff'
    SUFFIX_NEW_MNS = '_new_mns'
    SUFFIX_DIFF_MNS = '_diff_mns'
    SUFFIX_NDVI = '_ndvi'

    # print
    if debug >= 3:
        print(bold + green + "Variables dans la fonction" + endC)
        print(cyan + "createDifference() : " + endC + "image_ortho_input : " +
              str(image_ortho_input) + endC)
        print(cyan + "createDifference() : " + endC + "image_mns_input : " +
              str(image_mns_input) + endC)
        print(cyan + "createDifference() : " + endC + "image_mnt_input : " +
              str(image_mnt_input) + endC)
        print(cyan + "createDifference() : " + endC +
              "bd_vector_input_list : " + str(bd_vector_input_list) + endC)
        print(cyan + "createDifference() : " + endC + "zone_buffer_dico : " +
              str(zone_buffer_dico) + endC)
        print(cyan + "createDifference() : " + endC + "departments_list : " +
              str(departments_list) + endC)
        print(cyan + "createDifference() : " + endC +
              "image_difference_output : " + str(image_difference_output) +
              endC)
        print(cyan + "createDifference() : " + endC +
              "vector_difference_output : " + str(vector_difference_output) +
              endC)
        print(cyan + "createDifference() : " + endC + "fileld_bd_raster : " +
              str(fileld_bd_raster) + endC)
        print(cyan + "createDifference() : " + endC + "simplifie_param : " +
              str(simplifie_param) + endC)
        print(cyan + "createDifference() : " + endC + "threshold_ndvi : " +
              str(threshold_ndvi) + endC)
        print(cyan + "createDifference() : " + endC +
              "threshold_difference : " + str(threshold_difference) + endC)
        print(cyan + "createDifference() : " + endC +
              "filter_difference_0 : " + str(filter_difference_0) + endC)
        print(cyan + "createDifference() : " + endC +
              "filter_difference_1 : " + str(filter_difference_1) + endC)
        print(cyan + "createDifference() : " + endC + "path_time_log : " +
              str(path_time_log) + endC)
        print(cyan + "createDifference() : " + endC + "channel_order : " +
              str(channel_order) + endC)
        print(cyan + "createDifference() : " + endC + "format_vector : " +
              str(format_vector) + endC)
        print(cyan + "createDifference() : " + endC + "extension_raster : " +
              str(extension_raster) + endC)
        print(cyan + "createDifference() : " + endC + "extension_vector : " +
              str(extension_vector) + endC)
        print(cyan + "createDifference() : " + endC +
              "save_results_intermediate : " + str(save_results_intermediate) +
              endC)
        print(cyan + "createDifference() : " + endC + "overwrite : " +
              str(overwrite) + endC)

    # ETAPE 1 : NETTOYER LES DONNEES EXISTANTES

    print(cyan + "createDifference() : " + bold + green +
          "NETTOYAGE ESPACE DE TRAVAIL..." + endC)

    # Nom de base de l'image
    image_name = os.path.splitext(os.path.basename(image_ortho_input))[0]

    # Test si le fichier résultat différence existe déjà et si il doit être écrasés
    check = os.path.isfile(vector_difference_output)

    if check and not overwrite:  # Si le fichier difference existe deja et que overwrite n'est pas activé
        print(cyan + "createDifference() : " + bold + yellow +
              "File difference  " + vector_difference_output +
              " already exists and will not be created again." + endC)
    else:
        if check:
            try:
                removeFile(vector_difference_output)
            except Exception:
                pass  # si le fichier n'existe pas, il ne peut pas être supprimé : cette étape est ignorée

        # Définition des répertoires temporaires
        repertory_output = os.path.dirname(vector_difference_output)
        repertory_output_temp = repertory_output + os.sep + FOLDER_RESULT_TEMP + image_name
        repertory_mask_temp = repertory_output + os.sep + FOLDER_MASK_TEMP + image_name
        repertory_samples_cutting_temp = repertory_output + os.sep + FOLDER_CUTTING_TEMP + image_name
        repertory_samples_buff_temp = repertory_output + os.sep + FOLDER_BUFF_TEMP + image_name

        print(repertory_output_temp)
        print(repertory_mask_temp)
        print(repertory_samples_cutting_temp)
        print(repertory_samples_buff_temp)

        # Création des répertoires temporaire qui n'existent pas
        if not os.path.isdir(repertory_output_temp):
            os.makedirs(repertory_output_temp)
        if not os.path.isdir(repertory_mask_temp):
            os.makedirs(repertory_mask_temp)
        if not os.path.isdir(repertory_samples_cutting_temp):
            os.makedirs(repertory_samples_cutting_temp)
        if not os.path.isdir(repertory_samples_buff_temp):
            os.makedirs(repertory_samples_buff_temp)

        # Nettoyage des répertoires temporaire qui ne sont pas vide
        cleanTempData(repertory_mask_temp)
        cleanTempData(repertory_samples_cutting_temp)
        cleanTempData(repertory_samples_buff_temp)
        cleanTempData(repertory_output_temp)

        BD_topo_layers_list = []
        #zone = zone_buffer_dico.keys()[0]
        zone = list(zone_buffer_dico)[0]
        # Creation liste des couches des bd exogenes utilisées
        for layers_buffer in zone_buffer_dico[zone]:
            BD_topo_layers_list.append(layers_buffer[0])

        print(cyan + "createDifference() : " + bold + green +
              "... FIN NETTOYAGE" + endC)

        # ETAPE 2 : DECOUPER LES VECTEURS

        print(cyan + "createDifference() : " + bold + green +
              "DECOUPAGE ECHANTILLONS..." + endC)

        # 2.1 : Création du masque délimitant l'emprise de la zone par image
        vector_mask = repertory_mask_temp + os.sep + image_name + SUFFIX_MASK_CRUDE + extension_vector
        createVectorMask(image_ortho_input, vector_mask)

        # 2.2 : Simplification du masque
        vector_simple_mask = repertory_mask_temp + os.sep + image_name + SUFFIX_MASK + extension_vector
        simplifyVector(vector_mask, vector_simple_mask, simplifie_param,
                       format_vector)

        # 2.3 : Découpage des vecteurs copiés en local avec le masque
        vector_output_list = []
        for vector_input in bd_vector_input_list:
            vector_name = os.path.splitext(os.path.basename(vector_input))[0]
            extension = os.path.splitext(os.path.basename(vector_input))[1]
            vector_output = repertory_samples_cutting_temp + os.sep + vector_name + SUFFIX_VECTOR_CUT + extension
            vector_output_list.append(vector_output)
        cutoutVectors(vector_simple_mask, bd_vector_input_list,
                      vector_output_list, format_vector)

        print(cyan + "createDifference() : " + bold + green +
              "...FIN DECOUPAGE" + endC)

        # ETAPE 3 : BUFFERISER LES VECTEURS

        print(cyan + "createDifference() : " + bold + green +
              "MISE EN PLACE DES TAMPONS..." + endC)

        # Parcours du dictionnaire associant la zone aux noms de fichiers et aux tampons associés
        for elem_buff in zone_buffer_dico[zone]:
            # Parcours des départements
            for dpt in departments_list:

                input_shape = repertory_samples_cutting_temp + os.sep + elem_buff[
                    0] + "_" + dpt + SUFFIX_VECTOR_CUT + extension_vector
                output_shape = repertory_samples_buff_temp + os.sep + elem_buff[
                    0] + "_" + dpt + SUFFIX_VECTOR_BUFF + extension_vector
                buff = elem_buff[1]
                if os.path.isfile(input_shape):
                    if debug >= 3:
                        print(cyan + "createDifference() : " + endC +
                              "input_shape : " + str(input_shape) + endC)
                        print(cyan + "createDifference() : " + endC +
                              "output_shape : " + str(output_shape) + endC)
                        print(cyan + "createDifference() : " + endC +
                              "buff : " + str(buff) + endC)
                    bufferVector(input_shape, output_shape, buff, "", 1.0, 10,
                                 format_vector)
                else:
                    print(cyan + "createDifference() : " + bold + yellow +
                          "Pas de fichier du nom : " + endC + input_shape)

        print(cyan + "createDifference() : " + bold + green +
              "FIN DE L AFFECTATION DES TAMPONS" + endC)

        # ETAPE 4 : FUSION DES SHAPES DE LA BD TOPO

        print(cyan + "createDifference() : " + bold + green +
              "FUSION DATA BD..." + endC)

        shape_buff_list = []
        # Parcours du dictionnaire associant la zone au nom du fichier
        for elem_buff in zone_buffer_dico[zone]:
            # Parcours des départements
            for dpt in departments_list:
                shape_file = repertory_samples_buff_temp + os.sep + elem_buff[
                    0] + "_" + dpt + SUFFIX_VECTOR_BUFF + extension_vector

                if os.path.isfile(shape_file):
                    shape_buff_list.append(shape_file)
                    print("file for fusion : " + shape_file)
                else:
                    print(bold + yellow + "pas de fichiers avec ce nom : " +
                          endC + shape_file)

            # si une liste de fichier shape existe
            if not shape_buff_list:
                print(bold + yellow + "Pas de fusion sans donnee a fusionnee" +
                      endC)
            else:
                # Fusion des fichiers shape
                image_zone_shape = repertory_output_temp + os.sep + image_name + '_' + zone + extension_vector
                fusionVectors(shape_buff_list, image_zone_shape)

        print("File BD : " + image_zone_shape)
        print(cyan + "createDifference() : " + bold + green +
              "FIN DE LA FUSION" + endC)

    # ETAPE 5 : RASTERISER LE FICHIER SHAPE DE ZONE BD
    print(cyan + "createDifference() : " + bold + green +
          "RASTERIZATION DE LA FUSION..." + endC)
    image_zone_raster = repertory_output_temp + os.sep + image_name + '_' + zone + extension_raster
    rasterizeVector(image_zone_shape,
                    image_zone_raster,
                    image_ortho_input,
                    fileld_bd_raster,
                    codage=CODAGE)
    print(cyan + "createDifference() : " + bold + green +
          "FIN DE LA RASTERIZATION" + endC)

    # ETAPE 6 : CREER UN NOUVEAU MMS ISSU DU MNT + DATA BD_TOPO
    print(cyan + "createDifference() : " + bold + green +
          "CREATION NOUVEAU MNS..." + endC)
    image_new_mns_output = repertory_output_temp + os.sep + image_name + SUFFIX_NEW_MNS + extension_raster
    createMNS(image_ortho_input, image_mnt_input, image_zone_raster,
              image_new_mns_output)
    print(cyan + "createDifference() : " + bold + green +
          "FIN DE LA CREATION MNS" + endC)

    # ETAPE 7 : CREER D'UN MASQUE SUR LES ZONES VEGETALES
    print(cyan + "createDifference() : " + bold + green +
          "CREATION DU NDVI..." + endC)
    image_ndvi_output = repertory_output_temp + os.sep + image_name + SUFFIX_NDVI + extension_raster
    createNDVI(image_ortho_input, image_ndvi_output, channel_order)
    print(cyan + "createDifference() : " + bold + green +
          "FIN DE LA CREATION DU NDVI" + endC)

    print(cyan + "createDifference() : " + bold + green +
          "CREATION DU MASQUE NDVI..." + endC)
    image_ndvi_mask_output = repertory_output_temp + os.sep + image_name + SUFFIX_NDVI + SUFFIX_MASK + extension_raster
    createBinaryMask(image_ndvi_output, image_ndvi_mask_output, threshold_ndvi,
                     False)
    print(cyan + "createDifference() : " + bold + green +
          "FIN DE LA CREATION DU MASQUE NDVI" + endC)

    # ETAPE 8 : CREER UN FICHIER DE DIFFERENCE DES MNS AVEC MASQUAGE DES ZONES VEGETALES
    print(cyan + "createDifference() : " + bold + green +
          "CREATION DIFFERENCE MNS..." + endC)
    #image_diff_mns_output = repertory_output + os.sep + image_name + SUFFIX_DIFF_MNS + extension_raster
    image_diff_mns_output = image_difference_output
    createDifferenceFile(image_mns_input, image_new_mns_output,
                         image_ndvi_mask_output, image_diff_mns_output)
    print(cyan + "createDifference() : " + bold + green +
          "FIN DE LA CREATION DE LA DIFFERENCE MNS" + endC)

    print(cyan + "createDifference() : " + bold + green +
          "CREATION DU MASQUE DE DIFFERENCE..." + endC)
    image_diff_mns_mask_output = repertory_output_temp + os.sep + image_name + SUFFIX_DIFF_MNS + SUFFIX_MASK + extension_raster
    createBinaryMask(image_diff_mns_output, image_diff_mns_mask_output,
                     threshold_difference, True)
    print(cyan + "createDifference() : " + bold + green +
          "FIN DE LA CREATION DU MASQUE DE DIFFERENCE" + endC)

    print(cyan + "createDifference() : " + bold + green +
          "FILTRAGE DU MASQUE DE DIFFERENCE..." + endC)
    image_diff_mns_filtered_output = repertory_output_temp + os.sep + image_name + SUFFIX_DIFF_MNS + SUFFIX_FILTERED + extension_raster
    filterBinaryRaster(image_diff_mns_mask_output,
                       image_diff_mns_filtered_output, filter_difference_0,
                       filter_difference_1)
    print(cyan + "createDifference() : " + bold + green +
          "FIN DU FILTRAGE DU MASQUE DE DIFFERENCE" + endC)

    # ETAPE 9 : RASTERISER LE FICHIER DE DIFFERENCE DES MNS
    print(cyan + "createDifference() : " + bold + green +
          "VECTORISATION DU RASTER DE DIFFERENCE..." + endC)
    vector_diff_mns_filtered_output = repertory_output_temp + os.sep + image_name + SUFFIX_DIFF_MNS + SUFFIX_FILTERED + extension_vector
    polygonizeRaster(image_diff_mns_filtered_output,
                     vector_diff_mns_filtered_output,
                     image_name,
                     field_name="DN")
    print(cyan + "createDifference() : " + bold + green +
          "FIN DE VECTORISATION DU RASTER DE DIFFERENCE" + endC)

    print(cyan + "createDifference() : " + bold + green +
          "SIMPLIFICATION VECTEUR DE DIFFERENCE..." + endC)
    simplifyVector(vector_diff_mns_filtered_output, vector_difference_output,
                   simplifie_param, format_vector)
    print(cyan + "createDifference() : " + bold + green +
          "FIN DE SIMPLIFICATION DI VECTEUR DE DIFFERENCE" + endC)

    # ETAPE 10 : SUPPRESIONS FICHIERS INTERMEDIAIRES INUTILES
    if not save_results_intermediate:

        # Supression des .geom dans le dossier
        for to_delete in glob.glob(repertory_mask_temp + os.sep + "*.geom"):
            removeFile(to_delete)

        # Suppression des repertoires temporaires
        deleteDir(repertory_mask_temp)
        deleteDir(repertory_samples_cutting_temp)
        deleteDir(repertory_samples_buff_temp)
        deleteDir(repertory_output_temp)

    # Mise à jour du Log
    ending_event = "createDifference() : create macro samples ending : "
    timeLine(path_time_log, ending_event)

    return
def createMacroSamples(image_input, vector_to_cut_input, vector_sample_output, raster_sample_output, bd_vector_input_list, bd_buff_list, sql_expression_list, path_time_log, macro_sample_name="", simplify_vector_param=10.0, format_vector='ESRI Shapefile', extension_vector=".shp", save_results_intermediate=False, overwrite=True) :

    # Mise à jour du Log
    starting_event = "createMacroSamples() : create macro samples starting : "
    timeLine(path_time_log,starting_event)

    if debug >= 3:
        print(bold + green + "createMacroSamples() : Variables dans la fonction" + endC)
        print(cyan + "createMacroSamples() : " + endC + "image_input : " + str(image_input) + endC)
        print(cyan + "createMacroSamples() : " + endC + "vector_to_cut_input : " + str(vector_to_cut_input) + endC)
        print(cyan + "createMacroSamples() : " + endC + "vector_sample_output : " + str(vector_sample_output) + endC)
        print(cyan + "createMacroSamples() : " + endC + "raster_sample_output : " + str(raster_sample_output) + endC)
        print(cyan + "createMacroSamples() : " + endC + "bd_vector_input_list : " + str(bd_vector_input_list) + endC)
        print(cyan + "createMacroSamples() : " + endC + "bd_buff_list : " + str(bd_buff_list) + endC)
        print(cyan + "createMacroSamples() : " + endC + "sql_expression_list : " + str(sql_expression_list) + endC)
        print(cyan + "createMacroSamples() : " + endC + "path_time_log : " + str(path_time_log) + endC)
        print(cyan + "createMacroSamples() : " + endC + "macro_sample_name : " + str(macro_sample_name) + endC)
        print(cyan + "createMacroSamples() : " + endC + "simplify_vector_param : " + str(simplify_vector_param) + endC)
        print(cyan + "createMacroSamples() : " + endC + "format_vector : " + str(format_vector))
        print(cyan + "createMacroSamples() : " + endC + "extension_vector : " + str(extension_vector) + endC)
        print(cyan + "createMacroSamples() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC)
        print(cyan + "createMacroSamples() : " + endC + "overwrite : " + str(overwrite) + endC)

    # Constantes
    FOLDER_MASK_TEMP = "Mask_"
    FOLDER_CUTTING_TEMP = "Cut_"
    FOLDER_FILTERING_TEMP = "Filter_"
    FOLDER_BUFF_TEMP = "Buff_"

    SUFFIX_MASK_CRUDE = "_crude"
    SUFFIX_MASK = "_mask"
    SUFFIX_VECTOR_CUT = "_cut"
    SUFFIX_VECTOR_FILTER = "_filt"
    SUFFIX_VECTOR_BUFF = "_buff"

    CODAGE = "uint8"

    # ETAPE 1 : NETTOYER LES DONNEES EXISTANTES

    print(cyan + "createMacroSamples() : " + bold + green + "Nettoyage de l'espace de travail..." + endC)

    # Nom du repertoire de calcul
    repertory_macrosamples_output = os.path.dirname(vector_sample_output)

    # Test si le vecteur echantillon existe déjà et si il doit être écrasés
    check = os.path.isfile(vector_sample_output) or os.path.isfile(raster_sample_output)

    if check and not overwrite: # Si les fichiers echantillons existent deja et que overwrite n'est pas activé
        print(bold + yellow + "File sample : " + vector_sample_output + " already exists and will not be created again." + endC)
    else :
        if check:
            try:
                removeVectorFile(vector_sample_output)
                removeFile(raster_sample_output)
            except Exception:
                pass # si le fichier n'existe pas, il ne peut pas être supprimé : cette étape est ignorée

        # Définition des répertoires temporaires
        repertory_mask_temp = repertory_macrosamples_output + os.sep + FOLDER_MASK_TEMP + macro_sample_name
        repertory_samples_cutting_temp = repertory_macrosamples_output + os.sep + FOLDER_CUTTING_TEMP + macro_sample_name
        repertory_samples_filtering_temp = repertory_macrosamples_output + os.sep + FOLDER_FILTERING_TEMP + macro_sample_name
        repertory_samples_buff_temp = repertory_macrosamples_output + os.sep + FOLDER_BUFF_TEMP + macro_sample_name

        if debug >= 4:
            print(cyan + "createMacroSamples() : " + endC + "Création du répertoire : " + str(repertory_mask_temp))
            print(cyan + "createMacroSamples() : " + endC + "Création du répertoire : " + str(repertory_samples_cutting_temp))
            print(cyan + "createMacroSamples() : " + endC + "Création du répertoire : " + str(repertory_samples_buff_temp))

        # Création des répertoires temporaire qui n'existent pas
        if not os.path.isdir(repertory_macrosamples_output):
            os.makedirs(repertory_macrosamples_output)
        if not os.path.isdir(repertory_mask_temp):
            os.makedirs(repertory_mask_temp)
        if not os.path.isdir(repertory_samples_cutting_temp):
            os.makedirs(repertory_samples_cutting_temp)
        if not os.path.isdir(repertory_samples_filtering_temp):
            os.makedirs(repertory_samples_filtering_temp)
        if not os.path.isdir(repertory_samples_buff_temp):
            os.makedirs(repertory_samples_buff_temp)

        # Nettoyage des répertoires temporaire qui ne sont pas vide
        cleanTempData(repertory_mask_temp)
        cleanTempData(repertory_samples_cutting_temp)
        cleanTempData(repertory_samples_filtering_temp)
        cleanTempData(repertory_samples_buff_temp)

        print(cyan + "createMacroSamples() : " + bold + green + "... fin du nettoyage" + endC)

        # ETAPE 2 : DECOUPAGE DES VECTEURS

        print(cyan + "createMacroSamples() : " + bold + green + "Decoupage des echantillons ..." + endC)

        if vector_to_cut_input == None :
            # 2.1 : Création du masque délimitant l'emprise de la zone par image
            image_name = os.path.splitext(os.path.basename(image_input))[0]
            vector_mask = repertory_mask_temp + os.sep + image_name + SUFFIX_MASK_CRUDE + extension_vector
            createVectorMask(image_input, vector_mask)

            # 2.2 : Simplification du masque
            vector_simple_mask = repertory_mask_temp + os.sep + image_name + SUFFIX_MASK + extension_vector
            simplifyVector(vector_mask, vector_simple_mask, simplify_vector_param, format_vector)
        else :
            vector_simple_mask = vector_to_cut_input

        # 2.3 : Découpage des vecteurs de bd exogenes avec le masque
        vectors_cut_list = []
        for vector_input in bd_vector_input_list :
            vector_name = os.path.splitext(os.path.basename(vector_input))[0]
            vector_cut = repertory_samples_cutting_temp + os.sep + vector_name + SUFFIX_VECTOR_CUT + extension_vector
            vectors_cut_list.append(vector_cut)
        cutoutVectors(vector_simple_mask, bd_vector_input_list, vectors_cut_list, format_vector)

        print(cyan + "createMacroSamples() : " + bold + green + "... fin du decoupage" + endC)

        # ETAPE 3 : FILTRAGE DES VECTEURS

        print(cyan + "createMacroSamples() : " + bold + green + "Filtrage des echantillons ..." + endC)

        vectors_filtered_list = []
        if sql_expression_list != [] :
            for idx_vector in range (len(bd_vector_input_list)):
                vector_name = os.path.splitext(os.path.basename(bd_vector_input_list[idx_vector]))[0]
                vector_cut = vectors_cut_list[idx_vector]
                if idx_vector < len(sql_expression_list) :
                    sql_expression = sql_expression_list[idx_vector]
                else :
                    sql_expression = ""
                vector_filtered = repertory_samples_filtering_temp + os.sep + vector_name + SUFFIX_VECTOR_FILTER + extension_vector
                vectors_filtered_list.append(vector_filtered)

                # Filtrage par ogr2ogr
                if sql_expression != "":
                    names_attribut_list = getAttributeNameList(vector_cut, format_vector)
                    column = "'"
                    for name_attribut in names_attribut_list :
                        column += name_attribut + ", "
                    column = column[0:len(column)-2]
                    column += "'"
                    ret = filterSelectDataVector(vector_cut, vector_filtered, column, sql_expression, format_vector)
                    if not ret :
                        print(cyan + "createMacroSamples() : " + bold + yellow + "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte" %(sql_expression) + endC)
                        copyVectorFile(vector_cut, vector_filtered)
                else :
                    print(cyan + "createMacroSamples() : " + bold + yellow + "Pas de filtrage sur le fichier du nom : " + endC + vector_filtered)
                    copyVectorFile(vector_cut, vector_filtered)

        else :
            print(cyan + "createMacroSamples() : " + bold + yellow + "Pas de filtrage demandé" + endC)
            for idx_vector in range (len(bd_vector_input_list)):
                vector_cut = vectors_cut_list[idx_vector]
                vectors_filtered_list.append(vector_cut)

        print(cyan + "createMacroSamples() : " + bold + green + "... fin du filtrage" + endC)

        # ETAPE 4 : BUFFERISATION DES VECTEURS

        print(cyan + "createMacroSamples() : " + bold + green + "Mise en place des tampons..." + endC)

        vectors_buffered_list = []
        if bd_buff_list != [] :
            # Parcours des vecteurs d'entrée
            for idx_vector in range (len(bd_vector_input_list)):
                vector_name = os.path.splitext(os.path.basename(bd_vector_input_list[idx_vector]))[0]
                buff = bd_buff_list[idx_vector]
                vector_filtered = vectors_filtered_list[idx_vector]
                vector_buffered = repertory_samples_buff_temp + os.sep + vector_name + SUFFIX_VECTOR_BUFF + extension_vector

                if buff != 0:
                    if os.path.isfile(vector_filtered):
                        if debug >= 3:
                            print(cyan + "createMacroSamples() : " + endC + "vector_filtered : " + str(vector_filtered) + endC)
                            print(cyan + "createMacroSamples() : " + endC + "vector_buffered : " + str(vector_buffered) + endC)
                            print(cyan + "createMacroSamples() : " + endC + "buff : " + str(buff) + endC)
                        bufferVector(vector_filtered, vector_buffered, buff, "", 1.0, 10, format_vector)
                    else :
                        print(cyan + "createMacroSamples() : " + bold + yellow + "Pas de fichier du nom : " + endC + vector_filtered)

                else :
                    print(cyan + "createMacroSamples() : " + bold + yellow + "Pas de tampon sur le fichier du nom : " + endC + vector_filtered)
                    copyVectorFile(vector_filtered, vector_buffered)

                vectors_buffered_list.append(vector_buffered)

        else :
            print(cyan + "createMacroSamples() : " + bold + yellow + "Pas de tampon demandé" + endC)
            for idx_vector in range (len(bd_vector_input_list)):
                vector_filtered = vectors_filtered_list[idx_vector]
                vectors_buffered_list.append(vector_filtered)

        print(cyan + "createMacroSamples() : " + bold + green + "... fin de la mise en place des tampons" + endC)

        # ETAPE 5 : FUSION DES SHAPES

        print(cyan + "createMacroSamples() : " + bold + green + "Fusion par macroclasse ..." + endC)

        # si une liste de fichier shape à fusionner existe
        if not vectors_buffered_list:
            print(cyan + "createMacroSamples() : " + bold + yellow + "Pas de fusion sans donnee à fusionner" + endC)
        # s'il n'y a qu'un fichier shape en entrée
        elif len(vectors_buffered_list) == 1:
            print(cyan + "createMacroSamples() : " + bold + yellow + "Pas de fusion pour une seule donnee à fusionner" + endC)
            copyVectorFile(vectors_buffered_list[0], vector_sample_output)
        else :
            # Fusion des fichiers shape
            vectors_buffered_controled_list = []
            for vector_buffered in vectors_buffered_list :
                if os.path.isfile(vector_buffered) and (getGeometryType(vector_buffered, format_vector) in ('POLYGON', 'MULTIPOLYGON')) and (getNumberFeature(vector_buffered, format_vector) > 0):
                    vectors_buffered_controled_list.append(vector_buffered)
                else :
                    print(cyan + "createMacroSamples() : " + bold + red + "Attention fichier bufferisé est vide il ne sera pas fusionné : " + endC + vector_buffered, file=sys.stderr)

            fusionVectors(vectors_buffered_controled_list, vector_sample_output, format_vector)

        print(cyan + "createMacroSamples() : " + bold + green + "... fin de la fusion" + endC)

    # ETAPE 6 : CREATION DU FICHIER RASTER RESULTAT SI DEMANDE

    # Creation d'un masque binaire
    if raster_sample_output != "" and image_input != "" :
        repertory_output = os.path.dirname(raster_sample_output)
        if not os.path.isdir(repertory_output):
            os.makedirs(repertory_output)
        rasterizeBinaryVector(vector_sample_output, image_input, raster_sample_output, 1, CODAGE)

    # ETAPE 7 : SUPPRESIONS FICHIERS INTERMEDIAIRES INUTILES

    # Suppression des données intermédiaires
    if not save_results_intermediate:

        # Supression du fichier de decoupe si celui ci a été créer
        if vector_simple_mask != vector_to_cut_input :
            if os.path.isfile(vector_simple_mask) :
                removeVectorFile(vector_simple_mask)

        # Suppression des repertoires temporaires
        deleteDir(repertory_mask_temp)
        deleteDir(repertory_samples_cutting_temp)
        deleteDir(repertory_samples_filtering_temp)
        deleteDir(repertory_samples_buff_temp)

    # Mise à jour du Log
    ending_event = "createMacroSamples() : create macro samples ending : "
    timeLine(path_time_log,ending_event)

    return