def computeRoughnessByOcsMnh( grid_input, grid_output, mnh_input, classif_input, class_build_list, epsg, no_data_value, path_time_log, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True): # Constante FIELD_H_TYPE = ogr.OFTReal FIELD_ID_TYPE = ogr.OFTInteger FIELD_NAME_HSUM = "sum_h" FIELD_NAME_HRE = "mean_h" FIELD_NAME_AREA = "nb_area" FIELD_NAME_ID = "id" SUFFIX_HEIGHT = '_hauteur' SUFFIX_BUILT = '_bati' SUFFIX_TEMP = '_temp' SUFFIX_MASK = '_mask' # Mise à jour du Log timeLine(path_time_log, "Début du calcul de l'indicateur Height of Roughness Elements par OCS et MNT starting : ") print(cyan + "computeRoughnessByOcsMnh() : " + endC + "Début du calcul de l'indicateur Height of Roughness Elements par OCS et MNT." + endC + "\n") if debug >= 3: print(bold + green + "computeRoughnessByOcsMnh() : Variables dans la fonction" + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "grid_input : " + str(grid_input) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "grid_output : " + str(grid_output) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "mnh_input : " + str(mnh_input) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "classif_input : " + str(classif_input) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "class_build_list : " + str(class_build_list) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "overwrite : " + str(overwrite) + endC) # Test si le vecteur de sortie existe déjà et si il doit être écrasés check = os.path.isfile(grid_output) if check and not overwrite: # Si le fichier de sortie existent deja et que overwrite n'est pas activé print(cyan + "computeRoughnessByOcsMnh() : " + bold + yellow + "Le calcul de Roughness par OCS et MNT a déjà eu lieu." + endC + "\n") print(cyan + "computeRoughnessByOcsMnh() : " + bold + yellow + "Grid vector output : " + grid_output + " already exists and will not be created again." + endC) else : if check: try: removeVectorFile(grid_output) except Exception: pass # si le fichier n'existe pas, il ne peut pas être supprimé : cette étape est ignorée ############################################ ### Préparation générale des traitements ### ############################################ # Récuperation de la projection de l'image epsg_proj = getProjectionImage(classif_input) if epsg_proj == 0: epsg_proj = epsg # Préparation des fichiers temporaires temp_path = os.path.dirname(grid_output) + os.sep + "RoughnessByOcsAndMnh" # Nettoyage du repertoire temporaire si il existe if os.path.exists(temp_path): shutil.rmtree(temp_path) os.makedirs(temp_path) basename = os.path.splitext(os.path.basename(grid_output))[0] built_height = temp_path + os.sep + basename + SUFFIX_HEIGHT + SUFFIX_BUILT + extension_raster built_height_temp = temp_path + os.sep + basename + SUFFIX_HEIGHT + SUFFIX_BUILT + SUFFIX_TEMP + extension_raster classif_built_mask = temp_path + os.sep + basename + SUFFIX_BUILT + SUFFIX_MASK + extension_raster grid_output_temp = temp_path + os.sep + basename + SUFFIX_TEMP + extension_vector ############################## ### Calcul de l'indicateur ### ############################## # liste des classes de bati a prendre en compte dans l'expression du BandMath expression_bati = "" for id_class in class_build_list : expression_bati += "im1b1==%s or " %(str(id_class)) expression_bati = expression_bati[:-4] expression = "(%s) and (im2b1!=%s) and (im2b1>0)" %(expression_bati, str(no_data_value)) # Creation d'un masque vecteur des batis pour la surface des zones baties command = "otbcli_BandMath -il %s %s -out %s uint8 -exp '%s ? 1 : 0'" %(classif_input, mnh_input, classif_built_mask, expression) if debug >= 3: print(command) exit_code = os.system(command) if exit_code != 0: print(command) print(cyan + "computeRoughnessByOcsMnh() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise # Récupération de la hauteur du bati command = "otbcli_BandMath -il %s %s -out %s float -exp '%s ? im2b1 : 0'" %(classif_input, mnh_input, built_height_temp, expression) if debug >= 3: print(command) exit_code = os.system(command) if exit_code != 0: print(command) print(cyan + "computeRoughnessByOcsMnh() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise command = "gdal_translate -a_srs EPSG:%s -a_nodata %s -of %s %s %s" %(str(epsg_proj), str(no_data_value), format_raster, built_height_temp, built_height) if debug >= 3: print(command) exit_code = os.system(command) if exit_code != 0: print(command) print(cyan + "computeRoughnessByOcsMnh() : " + bold + red + "!!! Une erreur c'est produite au cours de la comande : gdal_translate : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise # Récupération du nombre de pixel bati de chaque maille pour definir la surface statisticsVectorRaster(classif_built_mask, grid_input, grid_output_temp, 1, False, False, True, ["min", "max", "median", "mean", "std", "unique", "range"], [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite) # Renomer le champ 'sum' en FIELD_NAME_AREA renameFieldsVector(grid_output_temp, ['sum'], [FIELD_NAME_AREA], format_vector) # Récupération de la hauteur moyenne du bati de chaque maille statisticsVectorRaster(built_height, grid_output_temp, grid_output, 1, False, False, True, ["min", "max", "median", 'mean', "std", "unique", "range"], [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite) # Renomer le champ 'mean' en FIELD_NAME_HRE renameFieldsVector(grid_output, ['sum'], [FIELD_NAME_HSUM], format_vector) # Calcul de la colonne FIELD_NAME_HRE division de FIELD_NAME_HSUM par FIELD_NAME_AREA field_values_list = getAttributeValues(grid_output, None, None, {FIELD_NAME_ID:FIELD_ID_TYPE, FIELD_NAME_HSUM:FIELD_H_TYPE, FIELD_NAME_AREA:FIELD_H_TYPE}, format_vector) field_new_values_list = [] for index in range(0, len(field_values_list[FIELD_NAME_ID])) : value_h = 0.0 if field_values_list[FIELD_NAME_AREA][index] > 0 : value_h = field_values_list[FIELD_NAME_HSUM][index] / field_values_list[FIELD_NAME_AREA][index] field_new_values_list.append({FIELD_NAME_HRE:value_h}) # Ajour de la nouvelle colonne calculé FIELD_NAME_HRE addNewFieldVector(grid_output, FIELD_NAME_HRE, FIELD_H_TYPE, 0, None, None, format_vector) setAttributeValuesList(grid_output, field_new_values_list, format_vector) ########################################## ### Nettoyage des fichiers temporaires ### ########################################## if not save_results_intermediate: if os.path.exists(temp_path): shutil.rmtree(temp_path) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "Fin du calcul de l'indicateur Height of Roughness Elements par OCS et MNT." + endC + "\n") timeLine(path_time_log, "Fin du calcul de l'indicateur Height of Roughness Elements par OCS et MNT ending : ") return
def computeRoughness(classif_input, mnh_input, vector_grid_input, vector_grid_output, class_label_dico, epsg, path_time_log, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True): # Constante FIELD_NAME_HRE = "mean_h" # Mise à jour du Log timeLine( path_time_log, "Début du calcul de l'indicateur Height of Roughness Elements par OCS et MNT starting : " ) print( cyan + "computeRoughness() : " + endC + "Début du calcul de l'indicateur Height of Roughness Elements par OCS et MNT." + endC + "\n") if debug >= 3: print(bold + green + "computeRoughness() : Variables dans la fonction" + endC) print(cyan + "computeRoughness() : " + endC + "classif_input : " + str(classif_input) + endC) print(cyan + "computeRoughness() : " + endC + "mnh_input : " + str(mnh_input) + endC) print(cyan + "computeRoughness() : " + endC + "vector_grid_input : " + str(vector_grid_input) + endC) print(cyan + "computeRoughness() : " + endC + "vector_grid_output : " + str(vector_grid_output) + endC) print(cyan + "computeRoughness() : " + endC + "class_label_dico : " + str(class_label_dico) + endC) print(cyan + "computeRoughness() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "computeRoughness() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "computeRoughness() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "computeRoughness() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "computeRoughness() : " + endC + "overwrite : " + str(overwrite) + endC) # Test si le vecteur de sortie existe déjà et si il doit être écrasés check = os.path.isfile(vector_grid_output) if check and not overwrite: # Si le fichier de sortie existent deja et que overwrite n'est pas activé print(cyan + "computeRoughness() : " + bold + yellow + "Le calcul de Roughness par OCS et MNT a déjà eu lieu." + endC + "\n") print(cyan + "computeRoughness() : " + bold + yellow + "Grid vector output : " + vector_grid_output + " already exists and will not be created again." + endC) else: if check: try: removeVectorFile(vector_grid_output) except Exception: pass # si le fichier n'existe pas, il ne peut pas être supprimé : cette étape est ignorée ############################################ ### Préparation générale des traitements ### ############################################ # Récuperation de la projection de l'image epsg_proj = getProjectionImage(classif_input) if epsg_proj == 0: epsg_proj = epsg # Liste des classes #key_class_label_list = list(class_label_dico.keys()) # Préparation des fichiers temporaires temp_path = os.path.dirname(vector_grid_output) + os.sep + "TEMP_HRE" # Nettoyage du repertoire temporaire si il existe if os.path.exists(temp_path): shutil.rmtree(temp_path) os.makedirs(temp_path) buit_height_temp = temp_path + os.sep + "hauteur_bati_temp" + extension_raster buit_height = temp_path + os.sep + "hauteur_bati" + extension_raster ############################## ### Calcul de l'indicateur ### ############################## # Récupération de la hauteur du bati #code_bati = [c for c,v in class_label_dico.items() if v=="bati"][0] code_bati = list(class_label_dico.keys())[list( class_label_dico.values()).index("bati")] command = "otbcli_BandMath -il %s %s -out %s float -exp 'im1b1==%s ? im2b1 : 0'" % ( classif_input, mnh_input, buit_height_temp, str(code_bati)) exit_code = os.system(command) if exit_code != 0: print(command) print( cyan + "computeRoughness() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise command = "gdal_translate -a_srs EPSG:%s -a_nodata 0 -of %s %s %s" % ( str(epsg_proj), format_raster, buit_height_temp, buit_height) exit_code = os.system(command) if exit_code != 0: print(command) print( cyan + "computeRoughness() : " + bold + red + "!!! Une erreur c'est produite au cours de la comande : gdal_translate : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise # Récupération de la hauteur moyenne du bati de chaque maille statisticsVectorRaster( buit_height, vector_grid_input, vector_grid_output, 1, False, False, True, ["min", "max", "median", "sum", "std", "unique", "range"], [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite) # Renomer le champ 'mean' en FIELD_NAME_HRE renameFieldsVector(vector_grid_output, ['mean'], [FIELD_NAME_HRE], format_vector) ########################################## ### Nettoyage des fichiers temporaires ### ########################################## if not save_results_intermediate: if os.path.exists(temp_path): shutil.rmtree(temp_path) print( cyan + "computeRoughness() : " + endC + "Fin du calcul de l'indicateur Height of Roughness Elements par OCS et MNT." + endC + "\n") timeLine( path_time_log, "Fin du calcul de l'indicateur Height of Roughness Elements par OCS et MNT ending : " ) return
def cutRasterImages(images_input_list, vector_cut, images_output_list, buffer_size, round_pixel_size, epsg, no_data_value, resampling_methode, z_compress, 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 = "cutRasterImages() : Cutting rasters and vector starting : " timeLine(path_time_log, starting_event) print(endC) print(bold + green + "## START : CUTTING IMAGES" + endC) print(endC) if debug >= 2: print(bold + green + "cutRasterImages() : Variables dans la fonction" + endC) print(cyan + "cutRasterImages() : " + endC + "images_input_list : " + str(images_input_list) + endC) print(cyan + "cutRasterImages() : " + endC + "vector_cut : " + str(vector_cut) + endC) print(cyan + "cutRasterImages() : " + endC + "images_output_list : " + str(images_output_list) + endC) print(cyan + "cutRasterImages() : " + endC + "buffer_size : " + str(buffer_size) + endC) print(cyan + "cutRasterImages() : " + endC + "round_pixel_size : " + str(round_pixel_size) + endC) print(cyan + "cutRasterImages() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "cutRasterImages() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "cutRasterImages() : " + endC + "resampling_methode : " + str(resampling_methode)) print(cyan + "cutRasterImages() : " + endC + "z_compress : " + str(z_compress)) print(cyan + "cutRasterImages() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "cutRasterImages() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "cutRasterImages() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "cutRasterImages() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "cutRasterImages() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + "cutRasterImages() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "cutRasterImages() : " + endC + "overwrite : " + str(overwrite) + endC) # PREPARATION DES FICHIERS INTERMEDIAIRES BUFF_SUFFIX = "_buf" CUT_SUFFIX = "_cut" COMPRESS_SUFFIX = "_compress" EPSG_DEFAULT = 2154 if buffer_size > 0 and len( images_input_list ) > 0: # Cas le vecteur de découpe des rasteurs est bufferisé vector_buf_for_raster_cut = os.path.splitext( vector_cut)[0] + BUFF_SUFFIX + str(int(round( buffer_size, 0))) + 'm' + extension_vector if debug >= 3: print("vector_buf_for_raster_cut : " + str(vector_buf_for_raster_cut) + endC) # Test si le vecteur decoupe existe déjà et si il doit être écrasés check = os.path.isfile(vector_buf_for_raster_cut) if check and not overwrite: # Si le fichier existe deja et que overwrite n'est pas activé print(bold + yellow + "File vector cutting : " + vector_buf_for_raster_cut + " already exists and will not be created again." + endC) else: if check: try: removeVectorFile(vector_buf_for_raster_cut) except Exception: pass # si le fichier n'existe pas, il ne peut pas être supprimé : cette étape est ignorée # Création du vecteur de découpe bufferisé bufferVector(vector_cut, vector_buf_for_raster_cut, buffer_size, "", 1.0, 10, format_vector) else: # Cas le vecteur de découpe des rasteurs n'est pas bufferisé idem vecteur de découpe que les vecteurs vector_buf_for_raster_cut = vector_cut # DECOUPAGE DES RASTEURS PAR LE VECTEUR DE DECOUPE # Pour tous les fichiers raster à découpper for index_raster in range(len(images_input_list)): # Préparation des rasters de travail d'entrée et de sortie raster_input = images_input_list[index_raster] raster_output = images_output_list[index_raster] raster_output_compress = os.path.splitext( raster_output)[0] + COMPRESS_SUFFIX + extension_raster vector_cut_temp = os.path.splitext( raster_output)[0] + CUT_SUFFIX + extension_vector if debug >= 1: print("\n") print(cyan + "cutRasterImages() : " + endC + bold + green + "Découpe fichier raster : " + endC + str(raster_input) + endC) # Récuperation de l'emprise de l'image ima_xmin, ima_xmax, ima_ymin, ima_ymax = getEmpriseImage(raster_input) # Recuperation de la valeur de l'arrondi de la taille des pixels en X et Y si non définie if round_pixel_size == 0.0 and os.path.isfile(raster_input): # Identification de la tailles de pixels en x et en y pixel_size_x, pixel_size_y = getPixelWidthXYImage(raster_input) round_pixel_size = abs(pixel_size_x) else: pixel_size_x = round_pixel_size pixel_size_y = round_pixel_size # Préparation du vecteur de découpe temporaire createEmpriseShapeReduced(vector_buf_for_raster_cut, ima_xmin, ima_ymin, ima_xmax, ima_ymax, vector_cut_temp, format_vector) # Identification de l'emprise de vecteur de découpe empr_xmin, empr_xmax, empr_ymin, empr_ymax = getEmpriseFile( vector_cut_temp, format_vector) # Calculer l'emprise arrondi xmin, xmax, ymin, ymax = roundPixelEmpriseSize(pixel_size_x, pixel_size_y, empr_xmin, empr_xmax, empr_ymin, empr_ymax) # Trouver l'emprise optimale opt_xmin = xmin opt_xmax = xmax opt_ymin = ymin opt_ymax = ymax if ima_xmin > xmin: opt_xmin = ima_xmin if ima_xmax < xmax: opt_xmax = ima_xmax if ima_ymin > ymin: opt_ymin = ima_ymin if ima_ymax < ymax: opt_ymax = ima_ymax # Récuperation de la projection de l'image if epsg == 0: epsg_proj = getProjectionImage(raster_input) else: epsg_proj = epsg if epsg_proj == 0: epsg_proj = EPSG_DEFAULT if debug >= 3: print("epsg : " + str(epsg_proj) + endC) print("\n") # Test si le rasteur de sortie existe déjà et si il doit être écrasés check = os.path.isfile(raster_output) if check and not overwrite: # Si le fichier existe deja et que overwrite n'est pas activé print(bold + yellow + "File raster output : " + raster_output + " already exists and will not be created again." + endC) else: if check: try: removeFile(raster_output) except Exception: pass # si le fichier n'existe pas, il ne peut pas être supprimé : cette étape est ignorée # Commande de découpe raster command = 'gdalwarp -t_srs EPSG:' + str(epsg_proj) + ' -te ' + str( opt_xmin ) + ' ' + str(opt_ymin) + ' ' + str(opt_xmax) + ' ' + str( opt_ymax ) + ' -tap -multi -co "NUM_THREADS=ALL_CPUS" -dstnodata ' + str( no_data_value ) + ' -tr ' + str(abs(pixel_size_x)) + ' ' + str( abs(pixel_size_y) ) + ' -cutline ' + vector_cut_temp + ' -of ' + format_raster + ' ' + raster_input + ' ' + raster_output if resampling_methode != "": command += " -r " + resampling_methode if overwrite: command += ' -overwrite' if debug >= 2: print(bold + green + "Command : " + command + endC) exit_code = os.system(command) if exit_code != 0: print( cyan + "cutRasterImages() : " + bold + red + "!!! Une erreur c'est produite au cours du decoupage de l'image : " + raster_input + ". Voir message d'erreur." + endC, file=sys.stderr) raise if debug >= 2: print(cyan + "cutRasterImages() : " + bold + green + "DECOUPAGE DU RASTER %s AVEC LE VECTEUR %s" % (raster_input, vector_buf_for_raster_cut) + endC) print(command) if z_compress: # Commande de découpe raster et compression command = 'gdalwarp -t_srs EPSG:' + str( epsg_proj ) + ' -te ' + str(opt_xmin) + ' ' + str(opt_ymin) + ' ' + str( opt_xmax ) + ' ' + str( opt_ymax ) + ' -tap -multi -co "NUM_THREADS=ALL_CPUS" -dstnodata ' + str( no_data_value ) + ' -tr ' + str(abs(pixel_size_x)) + ' ' + str( abs(pixel_size_y) ) + ' -co "COMPRESS=DEFLATE" -co "PREDICTOR=2" -co "ZLEVEL=9" -cutline ' + vector_cut_temp + ' -of ' + format_raster + ' ' + raster_input + ' ' + raster_output_compress if resampling_methode != "": command += ' -r ' + resampling_methode if overwrite: command += ' -overwrite' if debug >= 2: print(bold + green + "Command : " + command + endC) exit_code = os.system(command) if exit_code != 0: print( cyan + "cutRasterImages() : " + bold + red + "!!! Une erreur c'est produite au cours du decoupage de l'image : " + raster_input + ". Voir message d'erreur." + endC, file=sys.stderr) raise if debug >= 2: print( cyan + "cutRasterImages() : " + bold + green + "DECOUPAGE ET COMPRESSION DU RASTER %s AVEC LE VECTEUR %s" % (raster_input, vector_buf_for_raster_cut) + endC) print(command) # Suppression des fichiers intermédiaires removeVectorFile(vector_cut_temp) # SUPPRESIONS FICHIERS INTERMEDIAIRES INUTILES # Suppression des fichiers intermédiaires if not save_results_intermediate and os.path.isfile( vector_buf_for_raster_cut ) and vector_buf_for_raster_cut != vector_cut: removeVectorFile(vector_buf_for_raster_cut) print(endC) print(bold + green + "## END : CUTTING IMAGES" + endC) print(endC) # Mise à jour du Log ending_event = "cutRasterImages() : Cutting rasters and vector ending : " timeLine(path_time_log, ending_event) return
def occupationIndicator(classif_input, mnh_input, vector_grid_input, vector_grid_output, class_label_dico, epsg, path_time_log, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True): # Mise à jour du Log starting_event = "occupationIndicator() : Calcul de l'indicateur occupation du sol/hauteur de végétation starting : " timeLine(path_time_log, starting_event) print( bold + green + "Début du calcul de l'indicateur 'occupation du sol/hauteur de végétation'." + endC + "\n") if debug >= 3: print(bold + green + "occupationIndicator() : Variables dans la fonction" + endC) print(cyan + "occupationIndicator() : " + endC + "classif_input : " + str(classif_input) + endC) print(cyan + "occupationIndicator() : " + endC + "mnh_input : " + str(mnh_input) + endC) print(cyan + "occupationIndicator() : " + endC + "vector_grid_input : " + str(vector_grid_input) + endC) print(cyan + "occupationIndicator() : " + endC + "vector_grid_output : " + str(vector_grid_output) + endC) print(cyan + "occupationIndicator() : " + endC + "class_label_dico : " + str(class_label_dico) + endC) print(cyan + "occupationIndicator() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "occupationIndicator() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "occupationIndicator() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "occupationIndicator() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "occupationIndicator() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "occupationIndicator() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + "occupationIndicator() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "occupationIndicator() : " + endC + "overwrite : " + str(overwrite) + endC) # Constante FIELD_OCS_NAME = 'class_OCS' FIELD_OCS_TYPE = ogr.OFTInteger FIELD_MAJORITY_NAME = 'majority' # Test si le vecteur de sortie existe déjà et si il doit être écrasés check = os.path.isfile(vector_grid_output) if check and not overwrite: # Si le fichier de sortie existent deja et que overwrite n'est pas activé print( bold + yellow + "Le calcul de l'indicateur occupation du sol/hauteur de végétation a déjà eu lieu. \n" + endC) print(bold + yellow + "Grid vector output : " + vector_grid_output + " already exists and will not be created again." + endC) else: if check: try: removeVectorFile(vector_grid_output) except Exception: pass # si le fichier n'existe pas, il ne peut pas être supprimé : cette étape est ignorée ############################################ ### Préparation générale des traitements ### ############################################ # Récuperation de la projection de l'image epsg_proj = getProjectionImage(classif_input) if epsg_proj == 0: epsg_proj = epsg # Liste des classes key_class_label_list = list(class_label_dico.keys()) # Préparation des fichiers temporaires temp_path = os.path.dirname(vector_grid_output) + os.sep + "TEMP_OCS" # Nettoyage du repertoire temporaire si il existe if os.path.exists(temp_path): shutil.rmtree(temp_path) os.makedirs(temp_path) tempOCS = temp_path + os.sep + "occupation_du_sol" + extension_vector tempHveg = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation" + extension_vector temp_class0 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class0" + extension_vector temp_class1 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class1" + extension_vector temp_class2 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class2" + extension_vector temp_class3 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class3" + extension_vector temp_class4 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class4" + extension_vector vegetation_height_temp = temp_path + os.sep + "hauteur_vegetation_temp" + extension_raster vegetation_height = temp_path + os.sep + "hauteur_vegetation" + extension_raster ############################## ### Calcul de l'indicateur ### ############################## # Récupération de l'occupation du sol de chaque maille statisticsVectorRaster(classif_input, vector_grid_input, tempOCS, 1, True, True, False, [], [], class_label_dico, path_time_log, True, format_vector, save_results_intermediate, overwrite) # Récupération de la hauteur moyenne et la hauteur max de la végétation de chaque maille command = "otbcli_BandMath -il %s %s -out %s float -exp 'im1b1==%s ? im2b1 : 0'" % ( classif_input, mnh_input, vegetation_height_temp, str(key_class_label_list[4])) exit_code = os.system(command) if exit_code != 0: print(command) print( cyan + "occupationIndicator() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise command = "gdal_translate -a_srs EPSG:%s -a_nodata 0 -of %s %s %s" % ( str(epsg_proj), format_raster, vegetation_height_temp, vegetation_height) exit_code = os.system(command) if exit_code != 0: print(command) print( cyan + "occupationIndicator() : " + bold + red + "!!! Une erreur c'est produite au cours de la comande : gdal_translate : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise statisticsVectorRaster(vegetation_height, tempOCS, tempHveg, 1, False, False, True, [], [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite) # Définir le nom des champs temp_class_list = [] list_class_str = "" for class_str in key_class_label_list: list_class_str += "%s, " % (str(class_label_dico[class_str])) built_str = class_label_dico[key_class_label_list[0]] road_str = class_label_dico[key_class_label_list[1]] water_str = class_label_dico[key_class_label_list[2]] baresoil_str = class_label_dico[key_class_label_list[3]] vegetation_str = class_label_dico[key_class_label_list[4]] vegetation_height_medium_str = "H_moy_" + vegetation_str[0:3] vegetation_height_max_str = "H_max_" + vegetation_str[0:3] if debug >= 3: print("built_str = " + built_str) print("road_str = " + road_str) print("water_str = " + water_str) print("baresoil_str = " + baresoil_str) print("vegetation_str = " + vegetation_str) print("vegetation_height_medium_str = " + vegetation_height_medium_str) print("vegetation_height_max_str = " + vegetation_height_max_str) column = "'ID, majority, minority, %s%s, %s, %s'" % ( list_class_str, vegetation_height_max_str, vegetation_height_medium_str, FIELD_OCS_NAME) # Ajout d'un champ renvoyant la classe d'OCS attribué à chaque polygone et renomer le champ 'mean' renameFieldsVector(tempHveg, ['max'], [vegetation_height_max_str], format_vector) renameFieldsVector(tempHveg, ['mean'], [vegetation_height_medium_str], format_vector) addNewFieldVector(tempHveg, FIELD_OCS_NAME, FIELD_OCS_TYPE, 0, None, None, format_vector) # Attribution de la classe 0 => classe majoritaire de bâti ou route ou eau #expression = "(" + built_str + " >= " + baresoil_str + " AND " + built_str + " >= " + vegetation_str + ") OR (" + road_str + " >= " + baresoil_str + " AND " + road_str + " >= " + vegetation_str + ") OR (" + water_str + " >= " + baresoil_str + " AND " + water_str + " >= " + vegetation_str + ")" expression = "(" + FIELD_MAJORITY_NAME + " = '" + built_str + "') OR (" + FIELD_MAJORITY_NAME + " = '" + road_str + "') OR (" + FIELD_MAJORITY_NAME + " = '" + water_str + "')" if debug >= 3: print(expression) ret = filterSelectDataVector(tempHveg, temp_class0, column, expression, format_vector) if not ret: raise NameError( cyan + "occupationIndicator() : " + bold + red + "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte" % (expression) + endC) updateFieldVector(temp_class0, FIELD_OCS_NAME, 0, format_vector) temp_class_list.append(temp_class0) # Attribution de la classe 1 => classe majoritaire de sol nu #expression = "(" + baresoil_str + " > " + built_str + " AND " + baresoil_str + " > " + road_str + " AND " + baresoil_str + " > " + water_str + " AND " + baresoil_str + " >= " + vegetation_str + ")" expression = "(" + FIELD_MAJORITY_NAME + " = '" + baresoil_str + "')" if debug >= 3: print(expression) ret = filterSelectDataVector(tempHveg, temp_class1, column, expression, format_vector) if not ret: raise NameError( cyan + "occupationIndicator() : " + bold + red + "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte" % (expression) + endC) updateFieldVector(temp_class1, FIELD_OCS_NAME, 1, format_vector) temp_class_list.append(temp_class1) # Attribution de la classe 2 => classe majoritaire de végétation avec Hauteur inferieur à 1 #expression = "(" + vegetation_str + " > " + built_str + " AND " + vegetation_str + " > " + road_str + " AND " + vegetation_str + " > " + water_str + " AND " + vegetation_str + " > " + baresoil_str + ") AND (" + vegetation_height_medium_str + " < 1)" expression = "(" + FIELD_MAJORITY_NAME + " = '" + vegetation_str + "') AND (" + vegetation_height_medium_str + " < 1)" if debug >= 3: print(expression) ret = filterSelectDataVector(tempHveg, temp_class2, column, expression, format_vector) if not ret: raise NameError( cyan + "occupationIndicator() : " + bold + red + "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte" % (expression) + endC) updateFieldVector(temp_class2, FIELD_OCS_NAME, 2, format_vector) temp_class_list.append(temp_class2) # Attribution de la classe 3 => classe majoritaire de végétation avec Hauteur entre 1 et 5 #expression = "(" + vegetation_str + " > " + built_str + " AND " + vegetation_str + " > " + road_str + " AND " + vegetation_str + " > " + water_str + " AND " + vegetation_str + " > " + baresoil_str + ") AND (" + vegetation_height_medium_str + " >= 1 AND " + vegetation_height_medium_str + " < 5)" expression = "(" + FIELD_MAJORITY_NAME + " = '" + vegetation_str + "') AND (" + vegetation_height_medium_str + " >= 1 AND " + vegetation_height_medium_str + " < 5)" if debug >= 3: print(expression) ret = filterSelectDataVector(tempHveg, temp_class3, column, expression, format_vector) if not ret: raise NameError( cyan + "occupationIndicator() : " + bold + red + "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte" % (expression) + endC) updateFieldVector(temp_class3, FIELD_OCS_NAME, 3, format_vector) temp_class_list.append(temp_class3) # Attribution de la classe 4 => classe majoritaire de végétation avec Hauteur > 5 #expression = "(" + vegetation_str + " > " + built_str + " AND " + vegetation_str + " > " + road_str + " AND " + vegetation_str + " > " + water_str + " AND " + vegetation_str + " > " + baresoil_str + ") AND (" + vegetation_height_medium_str + " >= 5)" expression = "(" + FIELD_MAJORITY_NAME + " = '" + vegetation_str + "') AND (" + vegetation_height_medium_str + " >= 5)" if debug >= 3: print(expression) ret = filterSelectDataVector(tempHveg, temp_class4, column, expression, format_vector) if not ret: raise NameError( cyan + "occupationIndicator() : " + bold + red + "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte" % (expression) + endC) updateFieldVector(temp_class4, FIELD_OCS_NAME, 4, format_vector) temp_class_list.append(temp_class4) fusionVectors(temp_class_list, vector_grid_output, format_vector) ########################################## ### Nettoyage des fichiers temporaires ### ########################################## if not save_results_intermediate: if os.path.exists(temp_path): shutil.rmtree(temp_path) # Mise à jour du Log print( bold + green + "Fin du calcul de l'indicateur 'occupation du sol/hauteur de végétation'." + endC + "\n") ending_event = "occupationIndicator() : Calcul de l'indicateur occupation du sol/hauteur de végétation ending : " timeLine(path_time_log, ending_event) return
def selectSamples(image_input_list, sample_image_input, vector_output, table_statistics_output, sampler_strategy, select_ratio_floor, ratio_per_class_dico, name_column, no_data_value, path_time_log, rand_seed=0, ram_otb=0, epsg=2154, format_vector='ESRI Shapefile', extension_vector=".shp", save_results_intermediate=False, overwrite=True) : # Mise à jour du Log starting_event = "selectSamples() : Select points in raster mask macro input starting : " timeLine(path_time_log, starting_event) if debug >= 3: print(cyan + "selectSamples() : " + endC + "image_input_list : " + str(image_input_list) + endC) print(cyan + "selectSamples() : " + endC + "sample_image_input : " + str(sample_image_input) + endC) print(cyan + "selectSamples() : " + endC + "vector_output : " + str(vector_output) + endC) print(cyan + "selectSamples() : " + endC + "table_statistics_output : " + str(table_statistics_output) + endC) print(cyan + "selectSamples() : " + endC + "sampler_strategy : " + str(sampler_strategy) + endC) print(cyan + "selectSamples() : " + endC + "select_ratio_floor : " + str(select_ratio_floor) + endC) print(cyan + "selectSamples() : " + endC + "ratio_per_class_dico : " + str(ratio_per_class_dico) + endC) print(cyan + "selectSamples() : " + endC + "name_column : " + str(name_column) + endC) print(cyan + "selectSamples() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "selectSamples() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "selectSamples() : " + endC + "rand_seed : " + str(rand_seed) + endC) print(cyan + "selectSamples() : " + endC + "ram_otb : " + str(ram_otb) + endC) print(cyan + "selectSamples() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "selectSamples() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "selectSamples() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + "selectSamples() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "selectSamples() : " + endC + "overwrite : " + str(overwrite) + endC) # Constantes EXT_XML = ".xml" SUFFIX_SAMPLE = "_sample" SUFFIX_STATISTICS = "_statistics" SUFFIX_POINTS = "_points" SUFFIX_VALUE = "_value" BAND_NAME = "band_" COLUMN_CLASS = "class" COLUMN_ORIGINFID = "originfid" NB_POINTS = "nb_points" AVERAGE = "average" STANDARD_DEVIATION = "st_dev" print(cyan + "selectSamples() : " + bold + green + "DEBUT DE LA SELECTION DE POINTS" + endC) # Definition variables et chemins repertory_output = os.path.dirname(vector_output) filename = os.path.splitext(os.path.basename(vector_output))[0] sample_points_output = repertory_output + os.sep + filename + SUFFIX_SAMPLE + extension_vector file_statistic_points = repertory_output + os.sep + filename + SUFFIX_STATISTICS + SUFFIX_POINTS + EXT_XML if debug >= 3: print(cyan + "selectSamples() : " + endC + "file_statistic_points : " + str(file_statistic_points) + endC) # 0. EXISTENCE DU FICHIER DE SORTIE #---------------------------------- # Si le fichier vecteur points de sortie existe deja et que overwrite n'est pas activé check = os.path.isfile(vector_output) if check and not overwrite: print(bold + yellow + "Samples points already done for file %s and will not be calculated again." %(vector_output) + endC) else: # Si non ou si la vérification est désactivée : creation du fichier d'échantillons points # Suppression de l'éventuel fichier existant if check: try: removeVectorFile(vector_output) except Exception: pass # Si le fichier ne peut pas être supprimé, on suppose qu'il n'existe pas et on passe à la suite if os.path.isfile(table_statistics_output) : try: removeFile(table_statistics_output) except Exception: pass # Si le fichier ne peut pas être supprimé, on suppose qu'il n'existe pas et on passe à la suite # 1. STATISTIQUE SUR L'IMAGE DES ECHANTILLONS RASTEUR #---------------------------------------------------- if debug >= 3: print(cyan + "selectSamples() : " + bold + green + "Start statistique sur l'image des echantillons rasteur..." + endC) id_micro_list = identifyPixelValues(sample_image_input) if 0 in id_micro_list : id_micro_list.remove(0) min_micro_class_nb_points = -1 min_micro_class_label = 0 infoStructPointSource_dico = {} writeTextFile(file_statistic_points, '<?xml version="1.0" ?>\n') appendTextFileCR(file_statistic_points, '<GeneralStatistics>') appendTextFileCR(file_statistic_points, ' <Statistic name="pointsPerClassRaw">') if debug >= 2: print("Nombre de points par micro classe :" + endC) for id_micro in id_micro_list : nb_pixels = countPixelsOfValue(sample_image_input, id_micro) if debug >= 2: print("MicroClass : " + str(id_micro) + ", nb_points = " + str(nb_pixels)) appendTextFileCR(file_statistic_points, ' <StatisticPoints class="%d" value="%d" />' %(id_micro, nb_pixels)) if min_micro_class_nb_points == -1 or min_micro_class_nb_points > nb_pixels : min_micro_class_nb_points = nb_pixels min_micro_class_label = id_micro infoStructPointSource_dico[id_micro] = StructInfoMicoClass() infoStructPointSource_dico[id_micro].label_class = id_micro infoStructPointSource_dico[id_micro].nb_points = nb_pixels infoStructPointSource_dico[id_micro].info_points_list = [] del nb_pixels if debug >= 2: print("MicroClass min points find : " + str(min_micro_class_label) + ", nb_points = " + str(min_micro_class_nb_points)) appendTextFileCR(file_statistic_points, ' </Statistic>') pending_event = cyan + "selectSamples() : " + bold + green + "End statistique sur l'image des echantillons rasteur. " + endC if debug >= 3: print(pending_event) timeLine(path_time_log,pending_event) # 2. CHARGEMENT DE L'IMAGE DES ECHANTILLONS #------------------------------------------ if debug >= 3: print(cyan + "selectSamples() : " + bold + green + "Start chargement de l'image des echantillons..." + endC) # Information image cols, rows, bands = getGeometryImage(sample_image_input) xmin, xmax, ymin, ymax = getEmpriseImage(sample_image_input) pixel_width, pixel_height = getPixelWidthXYImage(sample_image_input) projection_input = getProjectionImage(sample_image_input) if projection_input == None or projection_input == 0 : projection_input = epsg else : projection_input = int(projection_input) pixel_width = abs(pixel_width) pixel_height = abs(pixel_height) # Lecture des données raw_data = getRawDataImage(sample_image_input) if debug >= 3: print("projection = " + str(projection_input)) print("cols = " + str(cols)) print("rows = " + str(rows)) # Creation d'une structure dico contenent tous les points différents de zéro progress = 0 pass_prog = False for y_row in range(rows) : for x_col in range(cols) : value_class = raw_data[y_row][x_col] if value_class != 0 : infoStructPointSource_dico[value_class].info_points_list.append(x_col + (y_row * cols)) # Barre de progression if debug >= 4: if ((float(y_row) / rows) * 100.0 > progress) and not pass_prog : progress += 1 pass_prog = True print("Progression => " + str(progress) + "%") if ((float(y_row) / rows) * 100.0 > progress + 1) : pass_prog = False del raw_data pending_event = cyan + "selectSamples() : " + bold + green + "End chargement de l'image des echantillons. " + endC if debug >= 3: print(pending_event) timeLine(path_time_log,pending_event) # 3. SELECTION DES POINTS D'ECHANTILLON #-------------------------------------- if debug >= 3: print(cyan + "selectSamples() : " + bold + green + "Start selection des points d'echantillon..." + endC) appendTextFileCR(file_statistic_points, ' <Statistic name="pointsPerClassSelect">') # Rendre deterministe la fonction aléatoire de random.sample if rand_seed > 0: random.seed( rand_seed ) # Pour toute les micro classes for id_micro in id_micro_list : # Selon la stategie de selection nb_points_ratio = 0 while switch(sampler_strategy.lower()): if case('all'): # Le mode de selection 'all' est choisi nb_points_ratio = infoStructPointSource_dico[id_micro].nb_points infoStructPointSource_dico[id_micro].sample_points_list = range(nb_points_ratio) break if case('percent'): # Le mode de selection 'percent' est choisi id_macro_class = int(math.floor(id_micro / 100) * 100) select_ratio_class = ratio_per_class_dico[id_macro_class] nb_points_ratio = int(infoStructPointSource_dico[id_micro].nb_points * select_ratio_class / 100) infoStructPointSource_dico[id_micro].sample_points_list = random.sample(range(infoStructPointSource_dico[id_micro].nb_points), nb_points_ratio) break if case('mixte'): # Le mode de selection 'mixte' est choisi nb_points_ratio = int(infoStructPointSource_dico[id_micro].nb_points * select_ratio_floor / 100) if id_micro == min_micro_class_label : # La plus petite micro classe est concervée intégralement infoStructPointSource_dico[id_micro].sample_points_list = range(infoStructPointSource_dico[id_micro].nb_points) nb_points_ratio = min_micro_class_nb_points elif nb_points_ratio <= min_micro_class_nb_points : # Les micro classes dont le ratio de selection est inferieur au nombre de points de la plus petite classe sont égement conservées intégralement infoStructPointSource_dico[id_micro].sample_points_list = random.sample(range(infoStructPointSource_dico[id_micro].nb_points), min_micro_class_nb_points) nb_points_ratio = min_micro_class_nb_points else : # Pour toutes les autres micro classes tirage aleatoire d'un nombre de points correspondant au ratio infoStructPointSource_dico[id_micro].sample_points_list = random.sample(range(infoStructPointSource_dico[id_micro].nb_points), nb_points_ratio) break break if debug >= 2: print("MicroClass = " + str(id_micro) + ", nb_points_ratio " + str(nb_points_ratio)) appendTextFileCR(file_statistic_points, ' <StatisticPoints class="%d" value="%d" />' %(id_micro, nb_points_ratio)) appendTextFileCR(file_statistic_points, ' </Statistic>') appendTextFileCR(file_statistic_points, '</GeneralStatistics>') pending_event = cyan + "selectSamples() : " + bold + green + "End selection des points d'echantillon. " + endC if debug >= 3: print(pending_event) timeLine(path_time_log,pending_event) # 4. PREPARATION DES POINTS D'ECHANTILLON #---------------------------------------- if debug >= 3: print(cyan + "selectSamples() : " + bold + green + "Start preparation des points d'echantillon..." + endC) # Création du dico de points points_random_value_dico = {} index_dico_point = 0 for micro_class in infoStructPointSource_dico : micro_class_struct = infoStructPointSource_dico[micro_class] label_class = micro_class_struct.label_class point_attr_dico = {name_column:int(label_class), COLUMN_CLASS:int(label_class), COLUMN_ORIGINFID:0} for id_point in micro_class_struct.sample_points_list: # Recuperer les valeurs des coordonnees des points coor_x = float(xmin + (int(micro_class_struct.info_points_list[id_point] % cols) * pixel_width)) + (pixel_width / 2.0) coor_y = float(ymax - (int(micro_class_struct.info_points_list[id_point] / cols) * pixel_height)) - (pixel_height / 2.0) points_random_value_dico[index_dico_point] = [[coor_x, coor_y], point_attr_dico] del coor_x del coor_y index_dico_point += 1 del point_attr_dico del infoStructPointSource_dico pending_event = cyan + "selectSamples() : " + bold + green + "End preparation des points d'echantillon. " + endC if debug >=3: print(pending_event) timeLine(path_time_log,pending_event) # 5. CREATION DU FICHIER SHAPE DE POINTS D'ECHANTILLON #----------------------------------------------------- if debug >= 3: print(cyan + "selectSamples() : " + bold + green + "Start creation du fichier shape de points d'echantillon..." + endC) # Définir les attibuts du fichier résultat attribute_dico = {name_column:ogr.OFTInteger, COLUMN_CLASS:ogr.OFTInteger, COLUMN_ORIGINFID:ogr.OFTInteger} # Creation du fichier shape createPointsFromCoordList(attribute_dico, points_random_value_dico, sample_points_output, projection_input, format_vector) del attribute_dico del points_random_value_dico pending_event = cyan + "selectSamples() : " + bold + green + "End creation du fichier shape de points d'echantillon. " + endC if debug >=3: print(pending_event) timeLine(path_time_log,pending_event) # 6. EXTRACTION DES POINTS D'ECHANTILLONS #----------------------------------------- if debug >= 3: print(cyan + "selectSamples() : " + bold + green + "Start extraction des points d'echantillon dans l'image..." + endC) # Cas ou l'on a une seule image if len(image_input_list) == 1: # Extract sample image_input = image_input_list[0] command = "otbcli_SampleExtraction -in %s -vec %s -outfield prefix -outfield.prefix.name %s -out %s -field %s" %(image_input, sample_points_output, BAND_NAME, vector_output, name_column) if ram_otb > 0: command += " -ram %d" %(ram_otb) if debug >= 3: print(command) exitCode = os.system(command) if exitCode != 0: raise NameError(cyan + "selectSamples() : " + bold + red + "An error occured during otbcli_SampleExtraction command. See error message above." + endC) # Cas de plusieurs imagettes else : # Le repertoire de sortie repertory_output = os.path.dirname(vector_output) # Initialisation de la liste pour le multi-threading et la liste de l'ensemble des echantions locaux thread_list = [] vector_local_output_list = [] # Obtenir l'emprise des images d'entrées pour redecouper le vecteur d'echantillon d'apprentissage pour chaque image for image_input in image_input_list : # Definition des fichiers sur emprise local file_name = os.path.splitext(os.path.basename(image_input))[0] emprise_local_sample = repertory_output + os.sep + file_name + SUFFIX_SAMPLE + extension_vector vector_sample_local_output = repertory_output + os.sep + file_name + SUFFIX_VALUE + extension_vector vector_local_output_list.append(vector_sample_local_output) # Gestion sans thread... #SampleLocalExtraction(image_input, sample_points_output, emprise_local_sample, vector_sample_local_output, name_column, BAND_NAME, ram_otb, format_vector, extension_vector, save_results_intermediate) # Gestion du multi threading thread = threading.Thread(target=SampleLocalExtraction, args=(image_input, sample_points_output, emprise_local_sample, vector_sample_local_output, name_column, BAND_NAME, ram_otb, format_vector, extension_vector, save_results_intermediate)) thread.start() thread_list.append(thread) # Extraction des echantions points des images try: for thread in thread_list: thread.join() except: print(cyan + "selectSamples() : " + bold + red + "Erreur lors de l'éextaction des valeurs d'echantion : impossible de demarrer le thread" + endC, file=sys.stderr) # Fusion des multi vecteurs de points contenant les valeurs des bandes de l'image fusionVectors(vector_local_output_list, vector_output, format_vector) # Clean des vecteurs point sample local file for vector_sample_local_output in vector_local_output_list : removeVectorFile(vector_sample_local_output) if debug >= 3: print(cyan + "selectSamples() : " + bold + green + "End extraction des points d'echantillon dans l'image." + endC) # 7. CALCUL DES STATISTIQUES SUR LES VALEURS DES POINTS D'ECHANTILLONS SELECTIONNEES #----------------------------------------------------------------------------------- if debug >= 3: print(cyan + "selectSamples() : " + bold + green + "Start calcul des statistiques sur les valeurs des points d'echantillons selectionnees..." + endC) # Si le calcul des statistiques est demandé presence du fichier stat if table_statistics_output != "": # On récupère la liste de données pending_event = cyan + "selectSamples() : " + bold + green + "Encours calcul des statistiques part1... " + endC if debug >=4: print(pending_event) timeLine(path_time_log,pending_event) attribute_name_dico = {} name_field_value_list = [] names_attribut_list = getAttributeNameList(vector_output, format_vector) if debug >=4: print("names_attribut_list = " + str(names_attribut_list)) attribute_name_dico[name_column] = ogr.OFTInteger for name_attribut in names_attribut_list : if BAND_NAME in name_attribut : attribute_name_dico[name_attribut] = ogr.OFTReal name_field_value_list.append(name_attribut) name_field_value_list.sort() res_values_dico = getAttributeValues(vector_output, None, None, attribute_name_dico, format_vector) del attribute_name_dico # Trie des données par identifiant micro classes pending_event = cyan + "selectSamples() : " + bold + green + "Encours calcul des statistiques part2... " + endC if debug >=4: print(pending_event) timeLine(path_time_log,pending_event) data_value_by_micro_class_dico = {} stat_by_micro_class_dico = {} # Initilisation du dico complexe for id_micro in id_micro_list : data_value_by_micro_class_dico[id_micro] = {} stat_by_micro_class_dico[id_micro] = {} for name_field_value in res_values_dico : if name_field_value != name_column : data_value_by_micro_class_dico[id_micro][name_field_value] = [] stat_by_micro_class_dico[id_micro][name_field_value] = {} stat_by_micro_class_dico[id_micro][name_field_value][AVERAGE] = 0.0 stat_by_micro_class_dico[id_micro][name_field_value][STANDARD_DEVIATION] = 0.0 # Trie des valeurs pending_event = cyan + "selectSamples() : " + bold + green + "Encours calcul des statistiques part3... " + endC if debug >=4: print(pending_event) timeLine(path_time_log,pending_event) for index in range(len(res_values_dico[name_column])) : id_micro = res_values_dico[name_column][index] for name_field_value in name_field_value_list : data_value_by_micro_class_dico[id_micro][name_field_value].append(res_values_dico[name_field_value][index]) del res_values_dico # Calcul des statistiques pending_event = cyan + "selectSamples() : " + bold + green + "Encours calcul des statistiques part4... " + endC if debug >=4: print(pending_event) timeLine(path_time_log,pending_event) for id_micro in id_micro_list : for name_field_value in name_field_value_list : try : stat_by_micro_class_dico[id_micro][name_field_value][AVERAGE] = average(data_value_by_micro_class_dico[id_micro][name_field_value]) except: stat_by_micro_class_dico[id_micro][name_field_value][AVERAGE] = 0 try : stat_by_micro_class_dico[id_micro][name_field_value][STANDARD_DEVIATION] = standardDeviation(data_value_by_micro_class_dico[id_micro][name_field_value]) except: stat_by_micro_class_dico[id_micro][name_field_value][STANDARD_DEVIATION] = 0 try : stat_by_micro_class_dico[id_micro][name_field_value][NB_POINTS] = len(data_value_by_micro_class_dico[id_micro][name_field_value]) except: stat_by_micro_class_dico[id_micro][name_field_value][NB_POINTS] = 0 del data_value_by_micro_class_dico # Creation du fichier statistique .csv pending_event = cyan + "selectSamples() : " + bold + green + "Encours calcul des statistiques part5... " + endC if debug >= 4: print(pending_event) timeLine(path_time_log,pending_event) text_csv = " Micro classes ; Champs couche image ; Nombre de points ; Moyenne ; Ecart type \n" writeTextFile(table_statistics_output, text_csv) for id_micro in id_micro_list : for name_field_value in name_field_value_list : # Ecriture du fichier text_csv = " %d " %(id_micro) text_csv += " ; %s" %(name_field_value) text_csv += " ; %d" %(stat_by_micro_class_dico[id_micro][name_field_value][NB_POINTS]) text_csv += " ; %f" %(stat_by_micro_class_dico[id_micro][name_field_value][AVERAGE]) text_csv += " ; %f" %(stat_by_micro_class_dico[id_micro][name_field_value][STANDARD_DEVIATION]) appendTextFileCR(table_statistics_output, text_csv) del name_field_value_list else : if debug >=3: print(cyan + "selectSamples() : " + bold + green + "Pas de calcul des statistiques sur les valeurs des points demander!!!." + endC) del id_micro_list pending_event = cyan + "selectSamples() : " + bold + green + "End calcul des statistiques sur les valeurs des points d'echantillons selectionnees. " + endC if debug >= 3: print(pending_event) timeLine(path_time_log,pending_event) # 8. SUPRESSION DES FICHIERS INTERMEDIAIRES #------------------------------------------ if not save_results_intermediate: if os.path.isfile(sample_points_output) : removeVectorFile(sample_points_output) print(cyan + "selectSamples() : " + bold + green + "FIN DE LA SELECTION DE POINTS" + endC) # Mise à jour du Log ending_event = "selectSamples() : Select points in raster mask macro input ending : " timeLine(path_time_log,ending_event) return