def binaryMaskVect(input_image,
                   output_dir,
                   threshold,
                   input_cut_vector,
                   attributes_list,
                   no_data_value,
                   epsg,
                   format_raster="GTiff",
                   format_vector="ESRI Shapefile",
                   extension_raster=".tif",
                   extension_vector=".shp",
                   save_results_intermediate=False,
                   overwrite=True):

    # Affichage des paramètres
    if debug >= 3:
        print(bold + green +
              "Variables dans le binaryMaskVect - Variables générales" + endC)
        print(cyan + "binaryMaskVect() : " + endC + "input_image : " +
              str(input_image) + endC)
        print(cyan + "binaryMaskVect() : " + endC + "output_dir : " +
              str(output_dir) + endC)
        print(cyan + "binaryMaskVect() : " + endC + "threshold : " +
              str(threshold) + endC)
        print(cyan + "binaryMaskVect() : " + endC + "input_cut_vector : " +
              str(input_cut_vector) + endC)
        print(cyan + "binaryMaskVect() : " + endC + "format_raster : " +
              str(format_raster) + endC)
        print(cyan + "binaryMaskVect() : " + endC + "format_vector : " +
              str(format_vector) + endC)
        print(cyan + "binaryMaskVect() : " + endC + "extension_raster : " +
              str(extension_raster) + endC)
        print(cyan + "binaryMaskVect() : " + endC + "extension_vector : " +
              str(extension_vector) + endC)
        print(cyan + "binaryMaskVect() : " + endC +
              "save_results_intermediate : " + str(save_results_intermediate) +
              endC)
        print(cyan + "binaryMaskVect() : " + endC + "overwrite : " +
              str(overwrite) + endC)

    image_name = os.path.splitext(os.path.basename(input_image))[0]
    binary_mask = output_dir + os.sep + "bin_mask_" + image_name + "_" + str(
        threshold).replace('.', '_') + extension_raster
    binary_mask_decoup = output_dir + os.sep + "bin_mask_decoup_" + image_name + "_" + str(
        threshold).replace('.', '_') + extension_raster
    binary_mask_vector = output_dir + os.sep + "bin_mask_vect_" + image_name + "_" + str(
        threshold).replace('.', '_') + extension_vector

    # Création du répertoire de sortie s'il n'existe pas déjà
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # Suppression des fichiers temporaires pour les calculs
    if os.path.exists(binary_mask):
        removeFile(binary_mask)

    if os.path.exists(binary_mask_decoup):
        removeFile(binary_mask_decoup)

    if os.path.exists(binary_mask_vector):
        if overwrite:
            removeVectorFile(binary_mask_vector, format_vector)
        else:
            return binary_mask_vector

    # Création du masque binaire
    createBinaryMask(input_image, binary_mask, threshold, False)

    if input_cut_vector != "":
        # Découpe du raster
        cutImageByVector(input_cut_vector, binary_mask, binary_mask_decoup,
                         None, None, no_data_value, epsg, format_raster,
                         format_vector)
    else:
        binary_mask_decoup = binary_mask

    # Vectorisation du masque binaire découpé
    polygonizeRaster(binary_mask_decoup, binary_mask_vector, image_name, "id",
                     format_vector)

    # Ajout des champs au fichier vecteur créé
    for attribute in attributes_list:
        addNewFieldVector(binary_mask_vector, attribute.name,
                          attribute.ogrType, attribute.value, attribute.width,
                          None, format_vector)

    # Suppresions des fichiers intermediaires inutiles et reperoire temporaire
    if not save_results_intermediate:
        removeFile(binary_mask)
        removeFile(binary_mask_decoup)

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

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

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

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

    # LES CONSTANTES
    PRECISION = 0.0000001

    CODAGE_8B = "uint8"
    CODAGE_F = "float"

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

        if pixelNodataCount > 0 :

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

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

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

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

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


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

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

        if pixelNodataCount > 0 :

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

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

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

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

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

        # CALLER LE FICHIER MNT AU FORMAT DU FICHIER MNS

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

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

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

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

        # INCRUSTATION DANS LE MNH DES DONNEES VECTEURS ROUTES

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

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

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

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

        # CALCUL DU MNH

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

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

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

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

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

        # DECOUPAGE DU MNH

        if bd_build_vector_input_list == []:
            image_mnh_road = image_mnh_output

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

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

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

        # INCRUSTATION DANS LE MNH DES DONNEES VECTEURS BATIS

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    # SUPPRESIONS FICHIERS INTERMEDIAIRES INUTILES

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

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

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

    return
def sobelToOuvrages(input_im_seuils_dico, output_dir, input_cut_vector, no_data_value, path_time_log, format_raster='GTiff', format_vector="ESRI Shapefile", extension_raster=".tif", extension_vector=".shp", save_results_intermediate=True, overwrite=True):

    # Constantes
    REPERTORY_TEMP = "temp_sobel"
    CODAGE_8B = "uint8"
    ID = "id"

    # Mise à jour du Log
    starting_event = "sobelToOuvrages() : Select Sobel to ouvrages starting : "
    timeLine(path_time_log,starting_event)

    # Création du répertoire de sortie s'il n'existe pas déjà
    if not os.path.exists(output_dir + os.sep + REPERTORY_TEMP):
        os.makedirs(output_dir + os.sep + REPERTORY_TEMP)

    # Affichage des paramètres
    if debug >= 3:
        print(bold + green + "Variables dans SobelToOuvrages - Variables générales" + endC)
        print(cyan + "sobelToOuvrages() : " + endC + "input_im_seuils_dico : " + str(input_im_seuils_dico) + endC)
        print(cyan + "sobelToOuvrages() : " + endC + "output_dir : " + str(output_dir) + endC)
        print(cyan + "sobelToOuvrages() : " + endC + "input_cut_vector : " + str(input_cut_vector) + endC)
        print(cyan + "sobelToOuvrages() : " + endC + "path_time_log : " + str(path_time_log) + endC)
        print(cyan + "sobelToOuvrages() : " + endC + "format_raster : " + str(format_raster) + endC)
        print(cyan + "sobelToOuvrages() : " + endC + "format_vector : " + str(format_vector) + endC)
        print(cyan + "sobelToOuvrages() : " + endC + "extension_raster : " + str(extension_raster) + endC)
        print(cyan + "sobelToOuvrages() : " + endC + "extension_vector : " + str(extension_vector) + endC)
        print(cyan + "sobelToOuvrages() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC)
        print(cyan + "sobelToOuvrages() : " + endC + "overwrite : " + str(overwrite) + endC)

    sobel_ouvrages_shp_list = []

    for elt in input_im_seuils_dico.split():
        raw_image = elt.split(":")[0]
        sobel_image = elt.split(":")[1].split(",")[0]

        for i in range(1,len(elt.split(":")[1].split(","))):
            seuil = elt.split(":")[1].split(",")[i]

            # Initialisation des noms des fichiers en sortie
            image_name = os.path.splitext(os.path.basename(raw_image))[0]
            sobel_binary_mask = output_dir + os.sep + REPERTORY_TEMP + os.sep + "bin_mask_sobel_" + image_name + "_" + str(seuil) + extension_raster
            sobel_binary_mask_vector_name = "bin_mask_vect_sobel_" + image_name + "_" + str(seuil)
            sobel_binary_mask_vector = output_dir + os.sep + REPERTORY_TEMP + os.sep + sobel_binary_mask_vector_name + extension_vector
            sobel_binary_mask_vector_cleaned = output_dir + os.sep + REPERTORY_TEMP + os.sep + "bin_mask_vect_sobel_cleaned_" + image_name + "_" + str(seuil) + extension_vector
            sobel_decoup = output_dir + os.sep + "sobel_decoup_" + image_name + "_" + str(seuil) + extension_vector

            binary_mask_zeros_name = "b_mask_zeros_vect_" + image_name
            binary_mask_zeros_raster = output_dir + os.sep + REPERTORY_TEMP + os.sep + "b_mask_zeros_" + image_name + extension_raster
            binary_mask_zeros_vector = output_dir + os.sep + REPERTORY_TEMP + os.sep + binary_mask_zeros_name + extension_vector
            binary_mask_zeros_vector_simpl = output_dir + os.sep + REPERTORY_TEMP + os.sep + "b_mask_zeros_vect_simpl_" + image_name + extension_vector
            true_values_buffneg = output_dir + os.sep + REPERTORY_TEMP + os.sep + "true_values_buffneg_" + image_name + extension_vector
            ouvrages_decoup_final = output_dir + os.sep + "ouvrages_sobel_" + image_name + "_" + str(seuil) + extension_vector

            # Création du masque binaire
            createBinaryMask(sobel_image, sobel_binary_mask, float(seuil), True)

            # Découpe du masque binaire par le shapefile de découpe en entrée
            cutImageByVector(input_cut_vector, sobel_binary_mask, sobel_decoup, None, None, no_data_value, 0, format_raster, format_vector)

            # Vectorisation du masque binaire Sobel découpé
            polygonizeRaster(sobel_decoup, sobel_binary_mask_vector, sobel_binary_mask_vector_name)

            # Création masque binaire pour séparer les no data des vraies valeurs
            nodata_value = getNodataValueImage(raw_image)
            if no_data_value == None :
                no_data_value = 0
            createBinaryMaskMultiBand(raw_image, binary_mask_zeros_raster, no_data_value, CODAGE_8B)

            # Vectorisation du masque binaire true data/false data -> polygone avec uniquement les vraies valeurs
            if os.path.exists(binary_mask_zeros_vector):
                removeVectorFile(binary_mask_zeros_vector, format_vector)

            # Polygonisation
            polygonizeRaster(binary_mask_zeros_raster, binary_mask_zeros_vector, binary_mask_zeros_name, ID, format_vector)

            # Simplification du masque obtenu
            simplifyVector(binary_mask_zeros_vector, binary_mask_zeros_vector_simpl, 2, format_vector)

            # Buffer négatif sur ce polygone
            bufferVector(binary_mask_zeros_vector_simpl, true_values_buffneg, -2, "", 1.0, 10, format_vector)
            cleanMiniAreaPolygons(sobel_binary_mask_vector, sobel_binary_mask_vector_cleaned, 15, ID, format_vector)

            # Découpe par le buffer négatif autour des true data
            cutVectorAll(true_values_buffneg, sobel_binary_mask_vector_cleaned, ouvrages_decoup_final, overwrite, format_vector)
            sobel_ouvrages_shp_list.append(ouvrages_decoup_final)

        return sobel_ouvrages_shp_list
def postTraitementsRaster(image_input,
                          image_output,
                          vector_input,
                          enable_cutting_ask,
                          post_treatment_raster_dico,
                          no_data_value,
                          path_time_log,
                          format_raster='GTiff',
                          format_vector='ESRI Shapefile',
                          extension_raster=".tif",
                          save_results_intermediate=False,
                          overwrite=True):

    # Print
    if debug >= 3:
        print(bold + green + "Variables dans la fonction" + endC)
        print(cyan + "postTraitementsRaster() : " + endC + "image_input : " +
              str(image_input) + endC)
        print(cyan + "postTraitementsRaster() : " + endC + "image_output : " +
              str(image_output) + endC)
        print(cyan + "postTraitementsRaster() : " + endC + "vector_input : " +
              str(vector_input) + endC)
        print(cyan + "postTraitementsRaster() : " + endC +
              "enable_cutting_ask : " + str(enable_cutting_ask) + endC)
        print(cyan + "postTraitementsRaster() : " + endC +
              "post_treatment_raster_dico : " +
              str(post_treatment_raster_dico) + endC)
        print(cyan + "postTraitementsRaster() : " + endC + "no_data_value : " +
              str(no_data_value) + endC)
        print(cyan + "postTraitementsRaster() : " + endC + "path_time_log : " +
              str(path_time_log) + endC)
        print(cyan + "postTraitementsRaster() : " + endC + "format_raster : " +
              str(format_raster) + endC)
        print(cyan + "postTraitementsRaster() : " + endC + "format_vector : " +
              str(format_vector) + endC)
        print(cyan + "postTraitementsRaster() : " + endC +
              "extension_raster : " + str(extension_raster) + endC)
        print(cyan + "postTraitementsRaster() : " + endC +
              "save_results_intermediate : " + str(save_results_intermediate) +
              endC)
        print(cyan + "postTraitementsRaster() : " + endC + "overwrite : " +
              str(overwrite) + endC)

    # Mise à jour du Log
    starting_event = "postTraitementsRaster() : Past traitements raster starting : "
    timeLine(path_time_log, starting_event)

    # Constantes
    CODAGE = "uint16"

    FOLDER_TEMP = "TempPtRaster_"
    SUFFIX_TEMP = "_tmp"
    SUFFIX_MASK = '_mask'
    SUFFIX_DILATED = '_dilated'
    SUFFIX_TOAPPLY = '_to_apply'

    # ETAPE 1 : NETTOYAGE DES DONNEES EXISTANTES

    print(cyan + "postTraitementsRaster() : " + bold + green +
          "NETTOYAGE DE L 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
    check = os.path.isfile(image_output)
    if check and not overwrite:  # Si le fichier résultat existe deja et que overwrite n'est pas activéptrd
        print(bold + yellow + "postTraitementsRaster() : " + endC +
              image_output +
              " already exists and will not be calculated again." + endC)
    else:  # Cas où le fichier résultat n'existe pas au lancement
        if check:  # Si overwrite est activé
            try:
                removeFile(image_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_output)  # Ex : D2_Par_Zone\Paysage_01\Corr_3\Resultats
        basename_output = os.path.splitext(os.path.basename(image_output))[
            0]  # Ex : Paysage_01_merged_filtred_pt
        extension = os.path.splitext(image_output)[1]
        image_output_temp = repertory_output + os.sep + basename_output + SUFFIX_TEMP + extension  # Ex : D2_Par_Zone\Paysage_01\Corr_3\Resultats\Paysage_01_merged_filtred_pt_tmp.tif
        repertory_temp = repertory_output + os.sep + FOLDER_TEMP + image_name  # Ex : D2_Par_Zone\Paysage_01\Corr_3\Resultats\Temp_pt_raster

        if debug >= 3:
            print(cyan + "postTraitementsRaster() : " + endC +
                  "repertory_temp : " + str(repertory_temp) + endC)

        # Creation du repertoire de sortie s'il n'existe pas
        if not os.path.isdir(repertory_output):
            os.makedirs(repertory_output)

        # Nettoyage et creation du fichier temporaire:
        cleanTempData(repertory_temp)

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

        # ETAPE 2 : TRAITEMENTS
        nb_treatments = len(post_treatment_raster_dico)
        idx = 0
        key_traitement_list = list(post_treatment_raster_dico.keys())

        for key_traitement in sorted(key_traitement_list):

            # Noms des fichiers temporaires
            binary_mask = repertory_temp + os.sep + basename_output + SUFFIX_MASK + key_traitement + extension_raster  # Ex : D2_Par_Zone\Paysage_01\Corr_3\Resultats\Temp_pt_raster\Paysage_01_merged_filtred_pt_mask.tif
            dilated_binary_mask = repertory_temp + os.sep + basename_output + SUFFIX_DILATED + SUFFIX_MASK + key_traitement + extension_raster  # Ex : D2_Par_Zone\Paysage_01\Corr_3\Resultats\Temp_pt_raster\Paysage_01_merged_filtred_pt_dilated_mask.tif
            mask_to_apply = repertory_temp + os.sep + basename_output + SUFFIX_TOAPPLY + SUFFIX_MASK + key_traitement + extension_raster  # Ex : D2_Par_Zone\Paysage_01\Corr_3\Resultats\Temp_pt_raster\Paysage_01_merged_filtred_pt_to_apply_mask.tif

            # Extraction des informations du dictionnaire
            treatement_info_list = post_treatment_raster_dico[key_traitement][
                0]
            image_to_use = treatement_info_list[0]
            threshold_min = float(treatement_info_list[1])
            threshold_max = float(treatement_info_list[2])
            buffer_to_apply = int(treatement_info_list[3])
            in_or_out = treatement_info_list[4]
            class_to_replace = str(treatement_info_list[5])
            if class_to_replace.lower() != "all":
                class_to_replace = int(class_to_replace)
            replacement_class = int(treatement_info_list[6])

            # ETAPE 2-1 CREATION DU MASQUE BINAIRE
            if debug >= 2:
                print(
                    cyan + "postTraitementsRaster() : " + bold + green +
                    "TRAITEMENT %s/%s - Etape 1/4 : CREATION DU MASQUE BINAIRE POUR %s "
                    % (str(idx + 1), str(nb_treatments), image_to_use) + endC)

            createBinaryMaskThreshold(image_to_use, binary_mask, threshold_min,
                                      threshold_max, CODAGE)

            # ETAPE 2-2 CREATION DU MASQUE DILATE
            if buffer_to_apply == 0:  # Si le buffer est nul, alors on copie juste le masque binaire
                if debug >= 2:
                    print(
                        cyan + "postTraitementsRaster() : " + bold + green +
                        "TRAITEMENT %s/%s - Etape 2/4 : CREATION PAR RENOMMAGE DU MASQUE DILATE POUR %s"
                        % (str(idx + 1), str(nb_treatments), image_to_use) +
                        endC)
                os.rename(binary_mask, dilated_binary_mask)
            else:
                if debug >= 2:
                    print(
                        cyan + "postTraitementsRaster() : " + bold + green +
                        "TRAITEMENT %s/%s - Etape 2/4 : CREATION DU MASQUE DILATE POUR %s "
                        % (str(idx + 1), str(nb_treatments), image_to_use) +
                        endC)

                # Creation d'un mask binaire bufferisé
                bufferBinaryRaster(binary_mask, dilated_binary_mask,
                                   buffer_to_apply, CODAGE)

                if not save_results_intermediate:
                    if debug >= 3:
                        print(
                            cyan + "postTraitementsRaster() : " + bold +
                            green +
                            "TRAITEMENT %s/%s - Etape 2/4 : SUPRESSION DE %s QUI NE SERVIRA PLUS"
                            % (str(idx + 1), str(nb_treatments), binary_mask) +
                            endC)
                    # Suppression du masque binaire de base
                    removeFile(binary_mask)

            # ETAPE 2-3 CREATION DU MASQUE COMPLEMENTAIRE
            if in_or_out.lower() == "in":
                if debug >= 2:
                    print(
                        cyan + "postTraitementsRaster() : " + bold + green +
                        "TRAITEMENT %s/%s - Etape 3/4 : CREATION PAR RENOMMAGE DU MASQUE COMPLEMENTAIRE A APPLIQUER POUR %s"
                        % (str(idx + 1), str(nb_treatments), image_to_use) +
                        endC)
                os.rename(dilated_binary_mask, mask_to_apply)

            else:
                if debug >= 2:
                    print(
                        cyan + "postTraitementsRaster() : " + bold + green +
                        "TRAITEMENT %s/%s - Etape 3/4 : CREATION DU MASQUE COMPLEMENTAIRE POUR %s"
                        % (str(idx + 1), str(nb_treatments), image_to_use) +
                        endC)

                # Creation d'un mask binaire negatif
                createBinaryMask(dilated_binary_mask, mask_to_apply, 0.5,
                                 False, CODAGE)

                if not save_results_intermediate:
                    if debug >= 3:
                        print(
                            cyan + "postTraitementsRaster() : " + bold +
                            green +
                            "TRAITEMENT %s/%s - Etape 3/4 : SUPRESSION DE %s QUI NE SERVIRA PLUS"
                            % (str(idx + 1), str(nb_treatments),
                               dilated_binary_mask) + endC)
                    # Suppression du masque dilate
                    removeFile(dilated_binary_mask)

            # ETAPE 2-4 APPLICATION DU MASQUE
            if str(class_to_replace).lower() == "all":
                expression = "\"(im1b1 == 1 ? %d : im2b1)\"" % (
                    int(replacement_class))
            else:
                expression = "\"(im1b1 == 1 ? ( im2b1 == %d ? %d : im2b1) : im2b1)\"" % (
                    class_to_replace, replacement_class)

            if nb_treatments <= 1:
                input_for_command = image_input
                output_for_command = image_output_temp
            elif idx == 0:
                input_for_command = image_input
                output_for_command = repertory_temp + os.sep + basename_output + str(
                    idx + 1) + extension_raster
            elif idx == nb_treatments - 1:
                input_for_command = repertory_temp + os.sep + basename_output + str(
                    idx) + extension_raster
                output_for_command = image_output_temp
            else:
                input_for_command = repertory_temp + os.sep + basename_output + str(
                    idx) + extension_raster
                output_for_command = repertory_temp + os.sep + basename_output + str(
                    idx + 1) + extension_raster

            command = "otbcli_BandMath -il %s %s -exp %s -out %s %s" % (
                mask_to_apply, input_for_command, expression,
                output_for_command, CODAGE)

            if debug >= 2:
                print(
                    cyan + "postTraitementsRaster() : " + bold + green +
                    "TRAITEMENT %s/%s - Etape 4/4 : APPLICATION DU POST TRAITEMENT AVEC %s"
                    % (str(idx + 1), str(nb_treatments), mask_to_apply) + endC)
                print(command)

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

            if not save_results_intermediate:
                if debug >= 3:
                    print(
                        cyan + "postTraitementsRaster() : " + bold + green +
                        "TRAITEMENT %s/%s - Etape 4/4 : SUPRESSION DE %s QUI NE SERVIRA PLUS"
                        % (str(idx + 1), str(nb_treatments), mask_to_apply) +
                        endC)
                # Suppression du masque à appliquer
                removeFile(mask_to_apply)

            # mise a jour de l'index
            idx += 1

    # ETAPE 5 : DECOUPAGE DU RASTER DE SORTIE
    if enable_cutting_ask:

        # Decoupe du raster
        if not cutImageByVector(vector_input, image_output_temp, image_output,
                                None, None, no_data_value, 0, format_raster,
                                format_vector):
            print(
                cyan + "postTraitementsRaster() : " + bold + red +
                "!!! Une erreur c'est produite au cours du decoupage de l'image : "
                + image_output_temp + ". Voir message d'erreur." + endC,
                file=sys.stderr)
            raise

        if debug >= 2:
            print(
                cyan + "postTraitementsRaster() : " + bold + green +
                "TRAITEMENT %s/%s - Etape 5 : REDECOUPAGE DU RASTER DE SORTIE AVEC LE VECTEUR %s"
                % (str(idx + 1), str(nb_treatments), vector_input) + endC)

        if not save_results_intermediate:
            # Suppression du fichier intermediaire
            removeFile(image_output_temp)
    else:
        # Pas de redécoupage du fichier raster de sortie demander le fichier est juste renomé
        shutil.move(image_output_temp, image_output)

    # ETAPE 6 : SUPPRESSION DES FICHIERS INTERMEDIAIRES
    # Suppression des données intermédiaires
    if not save_results_intermediate:
        if debug >= 2:
            print(
                cyan + "postTraitementsRaster() : " + bold + green +
                "TRAITEMENT %s/%s - SUPRESSION DES DONNEES INTERMEDIAIRE CONTENUES DANS : %s"
                % (str(idx + 1), str(nb_treatments), repertory_temp) + endC)

        # Suppression du repertoire temporaire
        deleteDir(repertory_temp)

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

    return
Example #5
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