def runTDCKmeans(input_images, output_dir, input_sea_points, input_cut_vector, no_data_value, path_time_log, nb_classes=5, epsg=2154, format_raster='GTiff', format_vector="ESRI Shapefile", extension_raster=".tif", extension_vector=".shp", save_results_intermediate=True, overwrite=True): # Mise à jour du Log starting_event = "runTDCKmeans() : Select TDC kmeans starting : " timeLine(path_time_log, starting_event) # Initialisation des constantes ID = "id" REP_TEMP = "temp_TDCKmeans" CHANNEL_ORDER = ["Red", "Green", "Blue", "NIR"] # Initialisation des variables repertory_temp = output_dir + os.sep + REP_TEMP # Nettoyage du repertoire de sortie if overwrite and os.path.exists(output_dir): shutil.rmtree(output_dir) # 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) # Création du répertoire de sortie temporaire s'il n'existe pas déjà if not os.path.exists(repertory_temp): os.makedirs(repertory_temp) # Vérification de l'existence des fichiers if not os.path.exists(input_cut_vector): print(cyan + "runTDCKmeans() : " + bold + red + "The file %s does not exist" % (input_cut_vector) + endC, file=sys.stderr) sys.exit(1) # Affichage des paramètres if debug >= 3: print(bold + green + "Variables dans runTDCKmeans - Variables générales" + endC) print(cyan + "runTDCKmeans() : " + endC + "input_images : " + str(input_images) + endC) print(cyan + "runTDCKmeans() : " + endC + "output_dir : " + str(output_dir) + endC) print(cyan + "runTDCKmeans() : " + endC + "input_sea_points : " + str(input_sea_points) + endC) print(cyan + "runTDCKmeans() : " + endC + "input_cut_vector : " + str(input_cut_vector) + endC) print(cyan + "runTDCKmeans() : " + endC + "nb_classes : " + str(nb_classes) + endC) print(cyan + "runTDCKmeans() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "runTDCKmeans() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "runTDCKmeans() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "runTDCKmeans() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "runTDCKmeans() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "runTDCKmeans() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "runTDCKmeans() : " + endC + "overwrite : " + str(overwrite) + endC) dico = "" for image in input_images: # Vérification de l'existence des fichiers if not os.path.exists(image): print(cyan + "runTDCKmeans() : " + bold + red + "The file %s does not exist" % (image) + endC, file=sys.stderr) sys.exit(1) # Initialisation des fichiers de sortie image_name = os.path.splitext(os.path.basename(image))[0] im_NDVI = repertory_temp + os.sep + "im_NDVI_" + image_name + extension_raster im_NDWI2 = repertory_temp + os.sep + "im_NDWI2_" + image_name + extension_raster im_BI = repertory_temp + os.sep + "im_BI_" + image_name + extension_raster im_concat = repertory_temp + os.sep + "im_concat_" + image_name + extension_raster im_kmeans = repertory_temp + os.sep + "im_kmeans_" + image_name + extension_raster im_kmeans_decoup = repertory_temp + os.sep + "im_kmeans_decoup_" + image_name + extension_raster im_kmeans_decoup_filter = repertory_temp + os.sep + "im_filter_" + image_name + extension_raster im_kmeans_vect_name = "im_kmeans_vect_" + image_name im_kmeans_vector = output_dir + os.sep + "temp_TDCKMeans" + os.sep + im_kmeans_vect_name + extension_vector # Création des images indice createNDVI(image, im_NDVI, CHANNEL_ORDER) createNDWI2(image, im_NDWI2, CHANNEL_ORDER) createBI(image, im_BI, CHANNEL_ORDER) # Concaténation des bandes des images brute, NDVI, NDWI2 et BI command = "otbcli_ConcatenateImages -il %s %s %s %s -out %s" % ( image, im_NDVI, im_NDWI2, im_BI, im_concat) if debug >= 3: print(command) exitCode = os.system(command) if exitCode != 0: raise NameError( cyan + "runTDCKmeans() : " + endC + bold + red + "An error occured during otbcli_ConcatenateImages command. See error message above." + endC) else: print(cyan + "runTDCKmeans() : " + endC + bold + green + "Create binary file %s complete!" % (im_concat) + endC) # K-Means sur l'image concaténée command = "otbcli_KMeansClassification -in %s -nc %s -nodatalabel %s -rand %s -out %s" % ( im_concat, str(nb_classes), str(no_data_value), str(1), im_kmeans) if debug >= 3: print(command) exitCode = os.system(command) if exitCode != 0: raise NameError( cyan + "runTDCKmeans() : " + endC + bold + red + "An error occured during otbcli_ConcatenateImages command. See error message above." + endC) else: print(cyan + "runTDCKmeans() : " + endC + bold + green + "Create binary file %s complete!" % (im_kmeans) + endC) # Découpe du raster image Kmeans cutImageByVector(input_cut_vector, im_kmeans, im_kmeans_decoup, None, None, no_data_value, epsg, format_raster, format_vector) # Nettoyage de l'image raster Kmeans command = "otbcli_ClassificationMapRegularization -io.in %s -io.out %s -ip.radius %s" % ( im_kmeans_decoup, im_kmeans_decoup_filter, str(5)) if debug >= 3: print(command) exitCode = os.system(command) if exitCode != 0: raise NameError( cyan + "runTDCKmeans() : " + endC + bold + red + "An error occured during otbcli_ClassificationMapRegularization command. See error message above." + endC) else: print(cyan + "runTDCKmeans() : " + endC + bold + green + "Create binary file %s complete!" % (im_kmeans_decoup_filter) + endC) # Vectorisation de l'image découpée polygonizeRaster(im_kmeans_decoup_filter, im_kmeans_vector, im_kmeans_vect_name, ID, format_vector) # Création du dictionnaire pour le passage à PolygonMerToTDC dico += image + ":" + im_kmeans_vector + " " # Appel à PolygonMerToTDC pour l'extraction du TDC dico = dico[:-1] polygonMerToTDC(str(dico), output_dir, input_sea_points, False, 1, input_cut_vector, 1, -1, no_data_value, path_time_log, epsg, format_vector, extension_raster, extension_vector, save_results_intermediate, overwrite) # Suppression du repertoire temporaire if not save_results_intermediate and os.path.exists(repertory_temp): shutil.rmtree(repertory_temp) # Mise à jour du Log ending_event = "runTDCKmeans() : Select TDC kmeans ending : " timeLine(path_time_log, ending_event) return
def extractTexture(image_input, repertory_neochannels_output, path_time_log, channels_list, texture_families_list, radius_list, indices_to_compute_list=[], channel_order=['Red', 'Green', 'Blue', 'NIR'], extension_raster=".tif", save_results_intermediate=False, overwrite=True, bin_number=64): # Mise à jour du Log starting_event = "extractTexture() : Extract texture starting : " timeLine(path_time_log, starting_event) # Affichage des parametres if debug >= 3: print(cyan + "extractTexture() : " + endC + "image_input: " + str(image_input) + endC) print(cyan + "extractTexture() : " + endC + "repertory_neochannels_output: " + str(repertory_neochannels_output) + endC) print(cyan + "extractTexture() : " + endC + "path_time_log: " + str(path_time_log) + endC) print(cyan + "extractTexture() : " + endC + "channels_list: " + str(channels_list) + endC) print(cyan + "extractTexture() : " + endC + "texture_families_list: " + str(texture_families_list) + endC) print(cyan + "extractTexture() : " + endC + "radius_list: " + str(radius_list) + endC) print(cyan + "extractTexture() : " + endC + "indices_to_compute_list: " + str(indices_to_compute_list) + endC) print(cyan + "extractTexture() : " + endC + "channel_order: " + str(channel_order) + endC) print(cyan + "extractTexture() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "extractTexture() : " + endC + "overwrite: " + str(overwrite) + endC) print(cyan + "extractTexture() : " + endC + "bin_number: " + str(bin_number) + endC) # Constantes CODAGE = "float" # MISE EN PLACE DE VARIABLES UTILES POUR LE CALCUL DES INDICES ET VERIFICATION DE DONNEES # Récupération des bandes de couleurs Red = "" Blue = "" Green = "" RedEdge = "" NIR = "" MIR = "" channels_number_dico = { "Red": 0, "Green": 0, "Blue": 0, "NIR": 0, "RE": 0, "MIR": 0 } if "Red" in channel_order: num_channel = channel_order.index("Red") + 1 channels_number_dico["Red"] = num_channel Red = "im1b" + str(num_channel) if "Blue" in channel_order: num_channel = channel_order.index("Blue") + 1 channels_number_dico["Blue"] = num_channel Blue = "im1b" + str(num_channel) if "Green" in channel_order: num_channel = channel_order.index("Green") + 1 channels_number_dico["Green"] = num_channel Green = "im1b" + str(num_channel) if "RE" in channel_order: num_channel = channel_order.index("RE") + 1 channels_number_dico["RE"] = num_channel RedEdge = "im1b" + str(num_channel) if "NIR" in channel_order: num_channel = channel_order.index("NIR") + 1 channels_number_dico["NIR"] = num_channel NIR = "im1b" + str(num_channel) if "MIR" in channel_order: num_channel = channel_order.index("MIR") + 1 channels_number_dico["MIR"] = num_channel MIR = "im1b" + str(num_channel) if "NDVI" in indices_to_compute_list and (Red == "" or NIR == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "NDVI needs Red and NIR channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "NDVIMod" in indices_to_compute_list and (Red == "" or NIR == "" or RedEdge == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "NDVIMod needs Red,NIR and RedEdge channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "TNDVI" in indices_to_compute_list and (Red == "" or NIR == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "TNDVI needs Red and NIR channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "NDWI" in indices_to_compute_list and (MIR == "" or NIR == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "NDWI needs NIR and MIR channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "ISU" in indices_to_compute_list and (Red == "" or NIR == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "ISU needs Red and NIR channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "GEMI" in indices_to_compute_list and (Red == "" or NIR == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "GEMI needs Red and NIR channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "BSI" in indices_to_compute_list and (Red == "" or NIR == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "BSI needs Red and NIR channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "NDBI" in indices_to_compute_list and (MIR == "" or NIR == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "NDBI needs MIR and NIR channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "NDWI2" in indices_to_compute_list and (Green == "" or NIR == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "NDWI2 needs Green and NIR channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "NDWI2Mod" in indices_to_compute_list and (Green == "" or NIR == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "NDWI2Mod needs Green, NIR and RedEdge channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "MNDWI" in indices_to_compute_list and (Green == "" or MIR == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "MNDWI needs Green and MIR channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "IR" in indices_to_compute_list and (Green == "" or Blue == "" or Red == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "IR needs Green and Blue and Red channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "NBI" in indices_to_compute_list and (Red == "" or NIR == "" or MIR == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "NBI needs Red and NIR and MIR channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "PNDVI" in indices_to_compute_list and (Red == "" or Green == "" or Blue == "" or NIR == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "PNDVI needs Red and Green and Blue and NIRchannels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "CI" in indices_to_compute_list and (Red == "" or Green == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "CI needs Red and Green channels to be computed, and at least one is not specify in \"channel_order\"" + endC) if "BI" in indices_to_compute_list and (Red == "" or Green == "" or Blue == ""): raise NameError( cyan + "extractTexture() : " + bold + red + "BI needs Red and Green and Blue channels to be computed, and at least one is not specify in \"channel_order\"" + endC) # CALCUL DES TEXTURES - sur image, bande et famille de texture (autres paramètres fixés) image_name = os.path.splitext( os.path.basename(image_input) )[0] # Récupération du nom simple de l'image (sans le tif). Exemple : image_name = Image_01 repertory_neochannels_output += os.sep print( cyan + "extractTexture() : " + bold + green + "DEBUT DU CALCUL DE IMAGE : %s , BANDES(S) : %s , TEXTURE(S) : %s, RAYON(S) : %s " % (image_input, channels_list, texture_families_list, radius_list) + endC) for channel in channels_list: # Rappel : channels_list --> Liste des canaux sur lesquels on veut calculer les textures. Exemple : channels_list = ['Red','Green','Blue','NIR','RE'] print( cyan + "extractTexture() : " + bold + green + "Debut du calcul de image(s) : %s , bande(s) : %s , texture(s) : %s, rayon(s) : %s " % (image_input, channel, texture_families_list, radius_list) + endC) channel_num = channels_number_dico[ channel] # Transformation du caractère de canal en numéro de canal if debug >= 2: print(cyan + "extractTexture() : " + endC + "image : " + str(image_input) + endC) print(cyan + "extractTexture() : " + endC + "channel : " + str(channel) + endC) # Récupération de la valeur minimale et maximale du canal image_max_band, image_mini_band = getMinMaxValueBandImage( image_input, channel_num) # Valeur maximale des pixels sur la bande image_maximum = str(int(image_max_band)) # Valeur minimale des pixels sur la bande image_minimum = str(int(image_mini_band)) if debug >= 2: print(cyan + "extractTexture() : " + bold + green + "Statistiques du canal %s de l'image %s" % (channel, image_input) + endC) print(cyan + "extractTexture() : " + endC + "image_maximum : " + image_maximum + endC) print(cyan + "extractTexture() : " + endC + "image_minimum : " + image_minimum + endC) for texture in texture_families_list: # Rappel : texture_families_list = liste des familles de textures que l'on veut calculer. Exemple: texture_families_list = ["simple","advanced","higher"] print( cyan + "extractTexture() : " + bold + green + "Debut du calcul de image(s) : %s , bande(s) : %s , texture(s) : %s, rayon(s) : %s " % (image_input, channel, texture, radius_list) + endC) for radius in radius_list: # Rappel : Taille des fenêtres que l'on veut utiliser pour le calcul des textures. Exemple : radius_list = [1,2,3,4,5,6,7...] print( cyan + "extractTexture() : " + bold + green + "Debut du calcul de image(s) : %s , bande(s) : %s , texture(s) : %s, rayon(s) : %s " % (image_input, channel, texture, radius) + endC) output_textures_base_name = repertory_neochannels_output + image_name + "_chan" + channel + "_rad" + str( radius ) # Exemple : /home/scgsi/Desktop/Jacques/TravailV2/ImagesTestChaine/APTV_01/NeoCanaux/Image_01_chan1_rad3 output_textures_image_name = output_textures_base_name + "_" + texture output_textures = output_textures_image_name + extension_raster # Exemple : /home/scgsi/Desktop/Jacques/TravailV2/ImagesTestChaine/APTV_01/NeoCanaux/Image_01_chan1_rad3_simple.tif output_textures_split = output_textures_image_name + "_band" + extension_raster # Exemple : /home/scgsi/Desktop/Jacques/TravailV2/ImagesTestChaine/APTV_01/NeoCanaux/Image_01_chan1_rad3_simple_band.tif if debug >= 4: print(cyan + "extractTexture() : " + bold + green + "Nom des textures en sortie" + endC) print(cyan + "extractTexture() : " + endC + "repertory_neochannels_output : " + str(repertory_neochannels_output) + endC) print(cyan + "extractTexture() : " + endC + "image_name : " + str(image_name) + endC) print(cyan + "extractTexture() : " + endC + "channel : " + str(channel) + endC) print(cyan + "extractTexture() : " + endC + "texture : " + str(texture) + endC) print(cyan + "extractTexture() : " + endC + "radius : " + str(radius) + endC) print(cyan + "extractTexture() : " + endC + "output_textures : " + str(output_textures) + endC) print(cyan + "extractTexture() : " + endC + "output_textures_split : " + str(output_textures_split) + endC) # Test si les fichiers resultats existent deja files_exist = False files_name_texture_list = [] if (texture == "simple"): files_name_texture_list = [''] * 8 files_name_texture_list[ 0] = output_textures_base_name + "_" + 'Energy' + extension_raster files_name_texture_list[ 1] = output_textures_base_name + "_" + 'Entropy' + extension_raster files_name_texture_list[ 2] = output_textures_base_name + "_" + 'Correlation' + extension_raster files_name_texture_list[ 3] = output_textures_base_name + "_" + 'InverseDifferenceMoment' + extension_raster files_name_texture_list[ 4] = output_textures_base_name + "_" + 'Inertia' + extension_raster files_name_texture_list[ 5] = output_textures_base_name + "_" + 'ClusterShade' + extension_raster files_name_texture_list[ 6] = output_textures_base_name + "_" + 'ClusterProminence' + extension_raster files_name_texture_list[ 7] = output_textures_base_name + "_" + 'HaralickCorrelation' + extension_raster files_exist = True for file_texture in files_name_texture_list: if not os.path.isfile(file_texture): files_exist = False break if (texture == "advanced"): files_name_texture_list = [''] * 10 files_name_texture_list[ 0] = output_textures_base_name + "_" + 'Mean' + extension_raster files_name_texture_list[ 1] = output_textures_base_name + "_" + 'Variance' + extension_raster files_name_texture_list[ 2] = output_textures_base_name + "_" + 'SumAverage' + extension_raster files_name_texture_list[ 3] = output_textures_base_name + "_" + 'SumVariance' + extension_raster files_name_texture_list[ 4] = output_textures_base_name + "_" + 'SumEntropy' + extension_raster files_name_texture_list[ 5] = output_textures_base_name + "_" + 'DifferenceOfEntropies' + extension_raster files_name_texture_list[ 6] = output_textures_base_name + "_" + 'DifferenceOfVariances' + extension_raster files_name_texture_list[ 7] = output_textures_base_name + "_" + 'IC1' + extension_raster files_name_texture_list[ 8] = output_textures_base_name + "_" + 'IC2' + extension_raster files_name_texture_list[ 9] = output_textures_base_name + "_" + 'Dissimilarity' + extension_raster files_exist = True for file_texture in files_name_texture_list: if not os.path.isfile(file_texture): files_exist = False break if (texture == "higher"): files_name_texture_list = [''] * 11 files_name_texture_list[ 0] = output_textures_base_name + "_" + 'ShortRunEmphasis' + extension_raster files_name_texture_list[ 1] = output_textures_base_name + "_" + 'LongRunEmphasis' + extension_raster files_name_texture_list[ 2] = output_textures_base_name + "_" + 'GreyLevelNonUniformity' + extension_raster files_name_texture_list[ 3] = output_textures_base_name + "_" + 'RunLengthNonUniformity' + extension_raster files_name_texture_list[ 4] = output_textures_base_name + "_" + 'RunPercentage' + extension_raster files_name_texture_list[ 5] = output_textures_base_name + "_" + 'LowGreyLevelRunEmphasis' + extension_raster files_name_texture_list[ 6] = output_textures_base_name + "_" + 'HighGreyLevelRunEmphasis' + extension_raster files_name_texture_list[ 7] = output_textures_base_name + "_" + 'ShortRunLowGreyLevelEmphasis' + extension_raster files_name_texture_list[ 8] = output_textures_base_name + "_" + 'ShortRunHighGreyLevelEmphasis' + extension_raster files_name_texture_list[ 9] = output_textures_base_name + "_" + 'LongRunLowGreyLevelEmphasis' + extension_raster files_name_texture_list[ 10] = output_textures_base_name + "_" + 'LongRunHighGreyLevelEmphasis' + extension_raster files_exist = True for file_texture in files_name_texture_list: if not os.path.isfile(file_texture): files_exist = False break if not overwrite and files_exist: print( cyan + "extractTexture() : " + endC + "Textures %s have already been calculated for image %s , channel %s and radius %s. not overwrite : they will not be calculated again." % (texture, image_input, channel, radius) + endC) else: # sinon (option écrasement activée ou configuration non calculée) : lancement du calcul de la texture if debug >= 2: print( cyan + "extractTexture() : " + bold + green + "Parametres d entree de otbcli_HaralickTextureExtraction" + endC) print(cyan + "extractTexture() : " + endC + "image_input : " + str(image_input) + endC) print(cyan + "extractTexture() : " + endC + "channel : " + str(channel) + endC) print(cyan + "extractTexture() : " + endC + "radius : " + str(radius) + endC) print(cyan + "extractTexture() : " + endC + "image_minimum : " + str(image_minimum) + endC) print(cyan + "extractTexture() : " + endC + "image_maximum : " + str(image_maximum) + endC) print(cyan + "extractTexture() : " + endC + "bin_number : " + str(bin_number) + endC) print(cyan + "extractTexture() : " + endC + "texture : " + str(texture) + endC) print(cyan + "extractTexture() : " + endC + "output_textures : " + str(output_textures) + endC) # Nettoyage des fichiers de texture for file_texture in files_name_texture_list: removeFile(file_texture) try: # Suppression de l'éventuel fichier existant removeFile(output_textures) except Exception: pass # Si le fichier ne peut pas être supprimé, on suppose qu'il n'existe pas et on passe à la suite ######################################## # CALCUL DES TEXTURES # ######################################## command = "otbcli_HaralickTextureExtraction -in %s -channel %s -parameters.xrad %s -parameters.yrad %s -parameters.min %s -parameters.max %s -parameters.nbbin %s -texture %s -out %s %s" % ( image_input, channel_num, str(radius), str(radius), image_minimum, image_maximum, bin_number, texture, output_textures, CODAGE) if debug >= 2: print( cyan + "extractTexture() : " + endC + "command otbcli_HaralickTextureExtraction : %s " % (command) + endC) exitCode = os.system(command) # Execution de la commande if exitCode != 0: raise NameError( cyan + "extractTexture() : " + bold + red + "An error occured during otbcli_HaralickTextureExtraction command. See error message above." + endC) if debug >= 2: print(cyan + "extractTexture() : " + endC + bold + green + "Parametres d entree de otbcli_SplitImage" + endC) print(cyan + "extractTexture() : " + endC + "output_textures : " + str(output_textures) + endC) print(cyan + "extractTexture() : " + endC + "output_textures_split : " + str(output_textures_split) + endC) # Découpage de l'image avec 8 ou 9 bandes de texture en 8 ou 9 images-textures. Atribution automatique des noms par otbcli_SplitImage command = "otbcli_SplitImage -in %s -out %s" % ( output_textures, output_textures_split) if debug >= 2: print(cyan + "extractTexture() : " + endC + "command otbcli_SplitImage : %s " % (command) + endC) exitCode = os.system(command) if exitCode != 0: raise NameError( cyan + "extractTexture() : " + bold + red + "An error occured during otbcli_SplitImage command. See error message above." + endC) # Nettoyage du fichier intermediaire if not save_results_intermediate: removeFile(output_textures) ################################################################################################ # RENOMAGE DES NOMS DE TEXTURE # # Supression du nom de la famille et transformation du numéro de bande en nom de texture # ################################################################################################ print(cyan + "extractTexture() : " + endC + bold + green + "Debut du renomage des textures de l'image " + str(image_input) + endC) # Réecriture des nom de textures simples ou advanced ou higher for i in range(len(files_name_texture_list)): texture_name_final = files_name_texture_list[i] texture_name = output_textures_base_name + "_" + texture + "_band" + "_" + str( i) + extension_raster os.rename(texture_name, texture_name_final) print(cyan + "extractTexture() : " + endC + bold + green + "Fin du renomage des textures de l'image " + str(image_input) + endC) print( cyan + "extractTexture() : " + endC + bold + green + "Fin du calcul de image : %s , bande(s) : %s , texture(s) : %s, rayon(s) : %s " % (image_input, channel, texture, radius) + endC) print( cyan + "extractTexture() : " + endC + bold + green + "Fin du calcul de image : %s , bande(s) : %s , texture(s) : %s, rayon(s) : %s " % (image_input, channel, texture, radius_list) + endC) print( cyan + "extractTexture() : " + endC + bold + green + "Fin du calcul de image : %s , bande(s) : %s , texture(s) : %s, rayon(s) : %s " % (image_input, channel, texture_families_list, radius_list) + endC) print( bold + green + "FIN DU CALCUL DE IMAGE : %s , BANDE(S) : %s , TEXTURE(S) : %s, RAYON(S) : %s " % (image_input, channels_list, texture_families_list, radius_list) + endC) ######################################## # CALCUL DES INDICES # ######################################## print(bold + green + "DEBUT DU CALCUL DES INDICES %s DE L'IMAGE %s" % (indices_to_compute_list, image_input) + endC) for indice in indices_to_compute_list: # NDVI (Vegetation) if indice == "NDVI": output_NDVI = repertory_neochannels_output + image_name + "_NDVI" + extension_raster check_NDVI = os.path.isfile(output_NDVI) if check_NDVI and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_NDVI + " already exists and will not be calculated again.") else: createNDVI(image_input, output_NDVI, channel_order, CODAGE) # NDVIMod (Vegetation) if indice == "NDVIMod": output_NDVImod = repertory_neochannels_output + image_name + "_NDVImod" + extension_raster check_NDVImod = os.path.isfile(output_NDVImod) if check_NDVImod and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_NDVImod + " already exists and will not be calculated again.") else: createNDVIMod(image_input, output_NDVImod, channel_order, CODAGE) # TNDVI (Vegetation) if indice == "TNDVI": output_TNDVI = repertory_neochannels_output + image_name + "_TNDVI" + extension_raster check_TNDVI = os.path.isfile(output_TNDVI) if check_TNDVI and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_TNDVI + " already exists and will not be calculated again.") else: createTNDVI(image_input, output_TNDVI, channel_order, CODAGE) # NDWI (Eau) if indice == "NDWI": output_NDWI = repertory_neochannels_output + image_name + "_NDWI" + extension_raster check_NDWI = os.path.isfile(output_NDWI) if check_NDWI and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_NDWI + " already exists and will not be calculated again.") else: createNDWI(image_input, output_NDWI, channel_order, CODAGE) # ISU (Bati) if indice == "ISU": output_ISU = repertory_neochannels_output + image_name + "_ISU" + extension_raster check_ISU = os.path.isfile(output_ISU) if check_ISU and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_ISU + " already exists and will not be calculated again.") else: createISU(image_input, output_ISU, channel_order, CODAGE) # GEMI (Vegetation) if indice == "GEMI": output_GEMI = repertory_neochannels_output + image_name + "_GEMI" + extension_raster check_GEMI = os.path.isfile(output_GEMI) if check_GEMI and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_GEMI + " already exists and will not be calculated again.") else: createGEMI(image_input, output_GEMI, channel_order, CODAGE) # BSI (Vegetation) if indice == "BSI": output_BSI = repertory_neochannels_output + image_name + "_BSI" + extension_raster check_BSI = os.path.isfile(output_BSI) if check_BSI and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_BSI + " already exists and will not be calculated again.") else: createBSI(image_input, output_BSI, channel_order, CODAGE) # NDBI (Bati) if indice == "NDBI": output_NDBI = repertory_neochannels_output + image_name + "_NDBI" + extension_raster check_NDBI = os.path.isfile(output_NDBI) if check_NDBI and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_NDBI + " already exists and will not be calculated again.") else: createNDBI(image_input, output_NDBI, channel_order, CODAGE) # NDWI2 (Eau) if indice == "NDWI2": output_NDWI2 = repertory_neochannels_output + image_name + "_NDWI2" + extension_raster check_NDWI2 = os.path.isfile(output_NDWI2) if check_NDWI2 and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_NDWI2 + " already exists and will not be calculated again.") else: createNDWI2(image_input, output_NDWI2, channel_order, CODAGE) # NDWI2Mod (Eau) if indice == "NDWI2Mod": output_NDWI2Mod = repertory_neochannels_output + image_name + "_NDWI2Mod" + extension_raster check_NDWI2Mod = os.path.isfile(output_NDWI2Mod) if check_NDWI2Mod and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_NDWI2Mod + " already exists and will not be calculated again.") else: createNDWI2Mod(image_input, output_NDWI2Mod, channel_order, CODAGE) # MNDWI (Eau) if indice == "MNDWI": output_MNDWI = repertory_neochannels_output + image_name + "_MNDWI" + extension_raster check_MNDWI = os.path.isfile(output_MNDWI) if check_MNDWI and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_MNDWI + " already exists and will not be calculated again.") else: createMNDWI(image_input, output_MNDWI, channel_order, CODAGE) # IR (Sol) if indice == "IR": output_IR = repertory_neochannels_output + image_name + "_IR" + extension_raster check_IR = os.path.isfile(output_IR) if check_IR and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_IR + " already exists and will not be calculated again.") else: createIR(image_input, output_IR, channel_order, CODAGE) # NBI (Bati) if indice == "NBI": output_NBI = repertory_neochannels_output + image_name + "_NBI" + extension_raster check_NBI = os.path.isfile(output_NBI) if check_NBI and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_NBI + " already exists and will not be calculated again.") else: createNBI(image_input, output_NBI, channel_order, CODAGE) # PNDVI (Vegetation) if indice == "PNDVI": output_PNDVI = repertory_neochannels_output + image_name + "_PNDVI" + extension_raster check_PNDVI = os.path.isfile(output_PNDVI) if check_PNDVI and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_PNDVI + " already exists and will not be calculated again.") else: createPNDVI(image_input, output_PNDVI, channel_order, CODAGE) # CI (Sol) if indice == "CI": output_CI = repertory_neochannels_output + image_name + "_CI" + extension_raster check_CI = os.path.isfile(output_CI) if check_CI and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_CI + " already exists and will not be calculated again.") else: createCI(image_input, output_CI, channel_order, CODAGE) # BI (Brillance) if indice == "BI": output_BI = repertory_neochannels_output + image_name + "_BI" + extension_raster check_BI = os.path.isfile(output_BI) if check_BI and not overwrite: print(cyan + "extractTexture() : " + endC + "File " + output_BI + " already exists and will not be calculated again.") else: createBI(image_input, output_BI, channel_order, CODAGE) # Supression des .geom des fichiers d'indices - A GARDER? for file_to_remove in glob.glob(repertory_neochannels_output + os.sep + "*.geom"): removeFile(file_to_remove) print(bold + green + "FIN DU CALCUL DES INDICES %s DE L'IMAGE %s " % (indices_to_compute_list, image_input) + endC) # Mise à jour du Log ending_event = "extractTexture() : Extract texture ending : " timeLine(path_time_log, ending_event) return
def runTDCSeuil(input_im_seuils_dico, output_dir, input_sea_points, input_cut_vector, input_emprise_vector, simplif, is_calc_indice_image, attribute_val_limite, attribute_val_proced, attribute_val_datepr, attribute_val_precis, attribute_val_contac, attribute_val_type, no_data_value, path_time_log, channel_order=['Red', 'Green', 'Blue', 'NIR'], epsg=2154, format_raster='GTiff', format_vector="ESRI Shapefile", extension_raster=".tif", extension_vector=".shp", save_results_intermediate=True, overwrite=True): # Mise à jour du Log starting_event = "runTDCSeuil() : Select TDC Seuil starting : " timeLine(path_time_log, starting_event) # Affichage des paramètres if debug >= 3: print(bold + green + "Variables dans runTDCSeuil - Variables générales" + endC) print(cyan + "runTDCSeuil() : " + endC + "input_im_seuils_dico : " + str(input_im_seuils_dico) + endC) print(cyan + "runTDCSeuil() : " + endC + "output_dir : " + str(output_dir) + endC) print(cyan + "runTDCSeuil() : " + endC + "input_sea_points : " + str(input_sea_points) + endC) print(cyan + "runTDCSeuil() : " + endC + "input_cut_vector : " + str(input_cut_vector) + endC) print(cyan + "runTDCSeuil() : " + endC + "input_emprise_vector : " + str(input_emprise_vector) + endC) print(cyan + "runTDCSeuil() : " + endC + "simplif : " + str(simplif) + endC) print(cyan + "runTDCSeuil() : " + endC + "is_calc_indice_image : " + str(is_calc_indice_image) + endC) print(cyan + "runTDCSeuil() : " + endC + "attribute_val_limite : " + str(attribute_val_limite) + endC) print(cyan + "runTDCSeuil() : " + endC + "attribute_val_proced : " + str(attribute_val_proced) + endC) print(cyan + "runTDCSeuil() : " + endC + "attribute_val_datepr : " + str(attribute_val_datepr) + endC) print(cyan + "runTDCSeuil() : " + endC + "attribute_val_precis : " + str(attribute_val_precis) + endC) print(cyan + "runTDCSeuil() : " + endC + "attribute_val_contac : " + str(attribute_val_contac) + endC) print(cyan + "runTDCSeuil() : " + endC + "attribute_val_type : " + str(attribute_val_type) + endC) print(cyan + "runTDCSeuil() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "runTDCSeuil() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "runTDCSeuil() : " + endC + "channel_order: " + str(channel_order) + endC) print(cyan + "runTDCSeuil() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "runTDCSeuil() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "runTDCSeuil() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "runTDCSeuil() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "runTDCSeuil() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + "runTDCSeuil() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "runTDCSeuil() : " + endC + "overwrite : " + str(overwrite) + endC) # Initialisation des constantes AUTO = "auto" POS_NUMERO_DOSSIER = 2 REP_NDVI_TDC_SEUIL = "ndvi_TDCSeuil" REP_TEMP_BIN_MASK_V = "Temp_Binary_Mask_Vector_" ATTR_NAME_REFDOSSIER = "RefDossier" ATTR_NAME_NOMIMAGE = "NomImage" ATTR_NAME_DATEACQUI = "DateAcqui" ATTR_NAME_HEUREACQUI = "HeureAcqui" ATTR_NAME_LIMITE = "TdcLimite" ATTR_NAME_PROCED = "TdcProced" ATTR_NAME_DATEPR = "TdcDatepro" ATTR_NAME_PRECIS = "TdcPrecis" ATTR_NAME_CONTAC = "TdcContact" ATTR_NAME_TYPE = "Type" # Repertoire NDVI à conserver!!! repertory_ndvi = output_dir + os.sep + REP_NDVI_TDC_SEUIL repertory_temp_list = [] # 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) # Création du répertoire de sortie temporaire s'il n'existe pas déjà if not os.path.exists(repertory_ndvi): os.makedirs(repertory_ndvi) # Exploitation du fichier emprise pour renseigner les informations des attribues res_values_dico = {} if input_emprise_vector != "": # Lecture des attributs de fichier vecteur names_attribut_list = getAttributeNameList(input_emprise_vector, format_vector) attribute_name_dico = {} for name_attribut in names_attribut_list: attribute_name_dico[name_attribut] = getAttributeType( input_emprise_vector, name_attribut, format_vector) res_values_dico = getAttributeValues(input_emprise_vector, None, None, attribute_name_dico, format_vector) # On calcule plusieurs seuils par image, mais différents selon les images bin_mask_list = [] images_list = [] nb_images = len(input_im_seuils_dico.split()) image_first_and_seuils = input_im_seuils_dico.split()[0] # Création d'une liste d'image for elt in input_im_seuils_dico.split(): images_list.append(elt.split(":")[0]) if ":" not in image_first_and_seuils: print( cyan + "runTDCSeuil() : " + red + bold + "Aucun seuil spécifié ! (Nécessité d'au moins un pour la 1ère image)" + endC, file=sys.stderr) sys.exit(1) else: seuils_first_image_list = image_first_and_seuils.split(":")[1].split( ",") for i in range(nb_images): # Chaque image + seuils (exemple : /path/image_xx.tif:0.1,0,-0.1) image_index_and_seuils = input_im_seuils_dico.split()[i] seuils_index_image_list = image_index_and_seuils.split(":")[1].split( ",") # L'image à traiter input_image = image_index_and_seuils.split(":")[0] image_name = os.path.splitext(os.path.basename(input_image))[0] # Création du répertoire temporaire de calcul repertory_temp = output_dir + os.sep + REP_TEMP_BIN_MASK_V + image_name if not os.path.exists(repertory_temp): os.makedirs(repertory_temp) repertory_temp_list.append(repertory_temp) # Initialisation des champs des attributs num_dossier = image_name.split("_")[POS_NUMERO_DOSSIER] attribute_val_refdossier = num_dossier attribute_val_nomimage = image_name attribute_val_datecqui = " " attribute_val_heureacqui = " " if attribute_val_limite == "": attribute_val_limite = " " if attribute_val_proced == "": attribute_val_proced = " " if attribute_val_datepr == "": now = datetime.datetime.now() attribute_val_datepr = now.strftime("%Y-%m-%d") if attribute_val_precis == "": attribute_val_precis = " " if attribute_val_contac == "": attribute_val_contac = " " if attribute_val_type == "": attribute_val_type = " " # Cas ou un fichier d'emprise contenant des données des attributs est present et contient un champs "RefDossier" if ATTR_NAME_REFDOSSIER in res_values_dico: if num_dossier in res_values_dico[ATTR_NAME_REFDOSSIER]: index_dossier = res_values_dico[ATTR_NAME_REFDOSSIER].index( num_dossier) if ATTR_NAME_NOMIMAGE in res_values_dico: attribute_val_nomimage = res_values_dico[ ATTR_NAME_NOMIMAGE][index_dossier] if ATTR_NAME_DATEACQUI in res_values_dico: datecqui_list = res_values_dico[ATTR_NAME_DATEACQUI][ index_dossier] attribute_val_datecqui = str(datecqui_list[0]) + "-" + str( datecqui_list[1]) + "-" + str(datecqui_list[2]) if ATTR_NAME_HEUREACQUI in res_values_dico: attribute_val_heureacqui = res_values_dico[ ATTR_NAME_HEUREACQUI][index_dossier] # Initialisation de StructAttribute pour la création des champs attributes_list = [StructAttribute(ATTR_NAME_REFDOSSIER, ogr.OFTString, 20, attribute_val_refdossier), \ StructAttribute(ATTR_NAME_NOMIMAGE, ogr.OFTString, 20, attribute_val_nomimage), \ StructAttribute(ATTR_NAME_DATEACQUI, ogr.OFTDate, None,attribute_val_datecqui), \ StructAttribute(ATTR_NAME_HEUREACQUI, ogr.OFTString, 14, attribute_val_heureacqui), \ StructAttribute(ATTR_NAME_LIMITE, ogr.OFTString, 20, attribute_val_limite), \ StructAttribute(ATTR_NAME_PROCED, ogr.OFTString, 30, attribute_val_proced), \ StructAttribute(ATTR_NAME_DATEPR, ogr.OFTString, 14, attribute_val_datepr), \ StructAttribute(ATTR_NAME_PRECIS, ogr.OFTString, 20, attribute_val_precis), \ StructAttribute(ATTR_NAME_CONTAC, ogr.OFTString, 20, attribute_val_contac), \ StructAttribute(ATTR_NAME_TYPE, ogr.OFTString, 14, attribute_val_type)] # Calcul de l'image NDVI si is_calc_indice_image est à True if is_calc_indice_image: image_index = repertory_ndvi + os.sep + "image_NDVI_" + os.path.splitext( os.path.basename(images_list[i]))[0] + extension_raster if not os.path.exists(input_image): print(cyan + "runTDCSeuil() : " + red + bold + "L'image renseignée en entrée : " + input_image + " n'existe pas. Vérifiez le chemin !" + endC, file=sys.stderr) sys.exit(1) createNDVI(input_image, image_index, channel_order) else: image_index = seuils_index_image_list[0] if os.path.splitext(image_index)[1] != extension_raster: print( cyan + "runTDCSeuil() : " + red + bold + "Si vous choisissez de calculer l'image NDVI, mettre l'option -c. Sinon, le 1er paramètre derrière \":\" dans -isd doit être l'image indice (.tif)" + endC, file=sys.stderr) sys.exit(1) if ":" not in image_index_and_seuils: if is_calc_indice_image: for t in seuils_first_image_list: if t == AUTO: seuils_list = runCalculSeuil( image_index, output_dir, save_results_intermediate) # Masque centre classe bin_mask_cc = binaryMaskVect( image_index, repertory_temp, float(seuils_list[0]), input_cut_vector, attributes_list, no_data_value, epsg, format_raster, format_vector, extension_raster, extension_vector, save_results_intermediate, overwrite) # Masque borne inf bin_mask_bi = binaryMaskVect( image_index, repertory_temp, float(v[1]), input_cut_vector, attributes_list, no_data_value, epsg, format_raster, format_vector, extension_raster, extension_vector, save_results_intermediate, overwrite) # Ajout des masques à la liste bin_mask_list.append(bin_mask_cc) bin_mask_list.append(bin_mask_bi) else: bin_mask = binaryMaskVect( image_index, repertory_temp, float(t), input_cut_vector, attributes_list, no_data_value, epsg, format_raster, format_vector, extension_raster, extension_vector, save_results_intermediate, overwrite) bin_mask_list.append(bin_mask) else: print(cyan + "runTDCSeuil() : " + red + +bold + "Renseignez les images NDVI associées et les seuils !" + endC, file=sys.stderr) sys.exit(1) else: if is_calc_indice_image: for t in seuils_index_image_list: if t == AUTO: seuils_list = runCalculSeuil( image_index, output_dir, save_results_intermediate) # Masque centre classe bin_mask_cc = binaryMaskVect( image_index, repertory_temp, float(seuils_list[0]), input_cut_vector, attributes_list, no_data_value, epsg, format_raster, format_vector, extension_raster, extension_vector, save_results_intermediate, overwrite) # Masque borne inf bin_mask_bi = binaryMaskVect( image_index, repertory_temp, float(seuils_list[1]), input_cut_vector, attributes_list, no_data_value, epsg, format_raster, format_vector, extension_raster, extension_vector, save_results_intermediate, overwrite) # Ajout des masques à la liste bin_mask_list.append(bin_mask_cc) bin_mask_list.append(bin_mask_bi) else: bin_mask = binaryMaskVect( image_index, repertory_temp, float(t), input_cut_vector, attributes_list, no_data_value, epsg, format_raster, format_vector, extension_raster, extension_vector, save_results_intermediate, overwrite) bin_mask_list.append(bin_mask) else: for j in range(1, len(seuils_index_image_list)): t = seuils_index_image_list[j] if t == AUTO: seuils_list = runCalculSeuil( image_index, output_dir, save_results_intermediate) # Masque centre classe bin_mask_cc = binaryMaskVect( image_index, repertory_temp, float(seuils_list[0]), input_cut_vector, attributes_list, no_data_value, epsg, format_raster, format_vector, extension_raster, extension_vector, save_results_intermediate, overwrite) # Masque borne inf bin_mask_bi = binaryMaskVect( image_index, repertory_temp, float(seuils_list[1]), input_cut_vector, attributes_list, no_data_value, epsg, format_raster, format_vector, extension_raster, extension_vector, save_results_intermediate, overwrite) # Ajout des masques à la liste bin_mask_list.append(bin_mask_cc) bin_mask_list.append(bin_mask_bi) else: bin_mask = binaryMaskVect( image_index, repertory_temp, float(t), input_cut_vector, attributes_list, no_data_value, epsg, format_raster, format_vector, extension_raster, extension_vector, save_results_intermediate, overwrite) bin_mask_list.append(bin_mask) # Constitution du dictionnaire associant chaque image aux vecteurs NDVI associés, pour l'entrée dans PolygonMerToTDC im_ndvivect_dico = "" if is_calc_indice_image: ndvi_mask_index = 0 for i in range(nb_images): # Chaque image + seuils (exemple : /path/image_xx.tif:0.1,0,-0.1) image_index_and_seuils = input_im_seuils_dico.split()[i] input_image = image_index_and_seuils.split(":")[0] seuils_index_image_list = image_index_and_seuils.split( ":")[1].split(",") is_presence_auto = False im_ndvivect_dico += input_image + ":" # Si des seuils sont renseignés seulement pour la 1ère image if ":" not in image_index_and_seuils: # Parcours des seuils de la première image for seuil in seuils_first_image_list: if seuil == AUTO: is_presence_auto = True # S'il y a un seuil à "auto" dans la boucle, on parcourt un tour de plus (auto = borneinf + centre classe) if is_presence_auto == True: nb_iter = len(seuils_first_image_list) else: nb_iter = len(seuils_first_image_list) - 1 for s in range(nb_iter): im_ndvivect_dico += bin_mask_list[ndvi_mask_index] + "," ndvi_mask_index = ndvi_mask_index + 1 im_ndvivect_dico += bin_mask_list[ndvi_mask_index] + " " # Si au moins un seuil est renseigné pour chacune des autres images else: # Parcours des seuils de l'image for seuil in seuils_index_image_list: if seuil == AUTO: is_presence_auto = True # S'il y a un seuil à "auto" dans la boucle, on parcourt un tour de plus (auto = borneinf + centre classe) if is_presence_auto: nb_iter = len(seuils_index_image_list) else: nb_iter = len(seuils_index_image_list) - 1 for s in range(nb_iter): im_ndvivect_dico += bin_mask_list[ndvi_mask_index] + "," ndvi_mask_index = ndvi_mask_index + 1 im_ndvivect_dico += bin_mask_list[ndvi_mask_index] + " " ndvi_mask_index = ndvi_mask_index + 1 else: ndvi_mask_index = 0 for i in range(nb_images): # Chaque image + seuils (exemple : /path/image_xx.tif:0.1,0,-0.1) image_index_and_seuils = input_im_seuils_dico.split()[i] input_image = image_index_and_seuils.split(":")[0] seuils_index_image_list = image_index_and_seuils.split( ":")[1].split(",") is_presence_auto = False im_ndvivect_dico += input_image + ":" if ":" not in image_index_and_seuils: print(cyan + "runTDCSeuil() : " + red + bold + "Renseignez les images NDVI associées et les seuils !" + endC, file=sys.stderr) sys.exit(1) # Si au moins un seuil est renseigné pour chacune des autres images else: # Parcours des seuils de l'image for seuil in seuils_index_image_list: if seuil == AUTO: is_presence_auto = True # S'il y a un seuil à "auto" dans la boucle, on parcourt un tour de plus (auto = borneinf + centre classe) if is_presence_auto: nb_iter = len(seuils_index_image_list) else: nb_iter = len(seuils_index_image_list) - 1 for s in range(1, nb_iter): im_ndvivect_dico += bin_mask_list[ndvi_mask_index] + "," ndvi_mask_index = ndvi_mask_index + 1 im_ndvivect_dico += bin_mask_list[ndvi_mask_index] + " " ndvi_mask_index = ndvi_mask_index + 1 im_ndvivect_dico = im_ndvivect_dico[:-1] tdc_shp = polygonMerToTDC(im_ndvivect_dico, output_dir, input_sea_points, True, simplif, input_cut_vector, 3.5, -3.5, no_data_value, path_time_log, epsg, format_vector, extension_raster, extension_vector, save_results_intermediate, overwrite) # Suppression des répertoires temporaires for repertory_temp in repertory_temp_list: if not save_results_intermediate and os.path.exists(repertory_temp): shutil.rmtree(repertory_temp) # Mise à jour du Log ending_event = "runTDCSeuil() : Select TDC Seuil ending : " timeLine(path_time_log, ending_event) return tdc_shp
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