def preparationRasters(urbanatlas_input, ucz_output, emprise_file, mask_file, enter_with_mask, image_file, mnh_file, built_files_list, hydrography_file, roads_files_list, rpg_file, indicators_method, ucz_method, dbms_choice, threshold_ndvi, threshold_ndvi_water, threshold_ndwi2, threshold_bi_bottom, threshold_bi_top, no_data_value, path_time_log, temp_directory, format_raster, format_vector, extension_raster): print(bold + yellow + "Début de la préparation des données rasters." + endC) step = " Début de la préparation des données rasters : " timeLine(path_time_log, step) image_cut = temp_directory + os.sep + os.path.splitext( os.path.basename(image_file))[0] + "_cut" + extension_raster print(bold + cyan + " Découpage de '%s' à l'emprise de '%s' :" % (image_file, emprise_file) + endC) # Découpage de l'image en entrée (image sat ou résultat classif) cutImageByVector(emprise_file, image_file, image_cut, None, None, no_data_value, 0, format_raster, format_vector) if indicators_method == "BD_exogenes": neochannels = temp_directory + os.sep + os.path.splitext( os.path.basename(image_file))[0] + "_NDVI" + extension_raster print(bold + cyan + " Calcul de NDVI à partir de '%s' :" % (image_cut) + endC) os.system( "otbcli_RadiometricIndices -in %s -out %s -channels.red 1 -channels.nir 4 -list Vegetation:NDVI" % (image_cut, neochannels) ) # Calcul du NDVI pour la 1ère méthode de calcul des indicateurs elif indicators_method == "SI_seuillage": neochannels = temp_directory + os.sep + os.path.splitext( os.path.basename( image_file))[0] + "_NDVI_NDWI2_BI" + extension_raster print(bold + cyan + " Calcul de NDVI/NDWI2/BI à partir de '%s' :" % (image_cut) + endC) os.system( "otbcli_RadiometricIndices -in %s -out %s -channels.green 3 -channels.red 1 -channels.nir 4 -list Vegetation:NDVI Water:NDWI2 Soil:BI" % (image_cut, neochannels) ) # Calcul des néocanaux pour la 2ème méthode de calcul des indicateurs elif indicators_method == "Resultats_classif": MNH_cut = temp_directory + os.sep + os.path.splitext( os.path.basename(mnh_file))[0] + "_cut" + extension_raster print(bold + cyan + " Découpage de '%s' à l'emprise de '%s' :" % (mnh_file, emprise_file) + endC) # Découpage du MNH pour la 4ème méthode de calcul des indicateurs cutImageByVector(emprise_file, mnh_file, MNH_cut, None, None, no_data_value, 0, format_raster, format_vector) step = " Fin de la préparation des données rasters : " timeLine(path_time_log, step) print(bold + yellow + "Fin de la préparation des données rasters." + endC) print("\n") return
def cutRasterSamples(image_input, vector_input, image_output, reference_image, epsg, no_data_value, path_time_log, superposition=False, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", save_results_intermediate=False, overwrite=True): # Mise à jour du Log starting_event = "cutRasterSamples() : Masks creation starting : " timeLine(path_time_log, starting_event) print(endC) print(bold + green + "## START : CUTTING IMAGE" + endC) print(endC) if debug >= 2: print(bold + green + "cutRasterSamples() : Variables dans la fonction" + endC) print(cyan + "cutRasterSamples() : " + endC + "image_input : " + str(image_input) + endC) print(cyan + "cutRasterSamples() : " + endC + "vector_input : " + str(vector_input) + endC) print(cyan + "cutRasterSamples() : " + endC + "image_output : " + str(image_output) + endC) print(cyan + "cutRasterSamples() : " + endC + "reference_image : " + str(reference_image) + endC) print(cyan + "cutRasterSamples() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "cutRasterSamples() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "cutRasterSamples() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "cutRasterSamples() : " + endC + "superposition : " + str(superposition) + endC) print(cyan + "cutRasterSamples() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "cutRasterSamples() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "cutRasterSamples() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "cutRasterSamples() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "cutRasterSamples() : " + endC + "overwrite : " + str(overwrite) + endC) # ETAPE 0 : PREPARATION DES FICHIERS INTERMEDIAIRES SAMPLE_MASK_SUFFIX = "_mask" CODAGE = "uint8" repertory_output = os.path.dirname(image_output) if superposition: # Cas où on vérifie la superposition géométrique avec l'image satellite output_mask_temp01 = repertory_output + os.sep + os.path.splitext( os.path.basename(image_input) )[0] + SAMPLE_MASK_SUFFIX + "_temp01" + extension_raster output_mask_temp02 = repertory_output + os.sep + os.path.splitext( os.path.basename(image_input) )[0] + SAMPLE_MASK_SUFFIX + "_temp02" + extension_raster else: # Cas où on ne vérifie pas la superposition géométrique avec l'image satellite output_mask_temp01 = image_output # ETAPE 1 : DECOUPAGE DU RASTEUR PAR LE VECTEUR D'EMPRISE # Fonction de découpe if not cutImageByVector(vector_input, image_input, output_mask_temp01, None, None, no_data_value, epsg, format_raster, format_vector): raise NameError( cyan + "cutRasterSamples() : " + bold + red + "!!! Une erreur c'est produite au cours du decoupage de l'image : " + image_input + ". Voir message d'erreur." + endC) if debug >= 2: print(cyan + "cutRasterSamples() : " + bold + green + "DECOUPAGE DU RASTER %s AVEC LE VECTEUR %s" % (image_input, vector_input) + endC) # ETAPE 2 : SUPERPOSITION DU FICHIER DECOUPE AVEC LE FICHIER DE REFERENCE if superposition: # Cas où on vérifie la superposition géométrique # Commande de mise en place de la geométrie command = "otbcli_Superimpose -inr " + reference_image + " -inm " + output_mask_temp01 + " -out " + output_mask_temp02 exit_code = os.system(command) if exit_code != 0: raise NameError( cyan + "cutRasterSamples() : " + bold + red + "!!! Une erreur c'est produite au cours du superimpose de l'image : " + output_mask_temp01 + ". Voir message d'erreur." + endC) # Commande de binarisation du nouveau masque (qui n'est plus binaire si une modification geometrique a été effectuée) expression_binarisation = "\"(im1b1 < %f? 0 : 1)\"" % (0.5) command = "otbcli_BandMath -il " + output_mask_temp02 + " -out " + image_output + " " + CODAGE + " -exp " + expression_binarisation exit_code = os.system(command) if exit_code != 0: raise NameError( cyan + "cutRasterSamples() : " + bold + red + "!!! Une erreur c'est produite au cours de la binarisation de l'image : " + output_mask_temp02 + ". Voir message d'erreur." + endC) if debug >= 2: print(cyan + "cutRasterSamples() : " + bold + green + "SUPERIMPOSE ET FICHIER BINAIRE DU FICHIER %s" % (image_input) + endC) print(command) # ETAPE 3 : SUPPRESIONS FICHIERS INTERMEDIAIRES INUTILES # Suppression des données intermédiaires if not save_results_intermediate: if superposition: removeFile(output_mask_temp01) removeFile(output_mask_temp02) print(endC) print(bold + green + "## END : UTTING IMAGE" + endC) print(endC) # Mise à jour du Log ending_event = "cutRasterSamples() : Masks creation ending : " timeLine(path_time_log, ending_event) return
def estimateQualityMns(image_input, vector_cut_input, vector_sample_input_list, vector_sample_points_input, raster_input_dico, vector_output, no_data_value, path_time_log, format_raster='GTiff', epsg=2154, format_vector='ESRI Shapefile', extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True): # Mise à jour du Log starting_event = "estimateQualityMns() : Masks creation starting : " timeLine(path_time_log, starting_event) print(endC) print(bold + green + "## START : CREATE HEIGHT POINTS FILE FROM MNS" + endC) print(endC) if debug >= 2: print(bold + green + "estimateQualityMns() : Variables dans la fonction" + endC) print(cyan + "estimateQualityMns() : " + endC + "image_input : " + str(image_input) + endC) print(cyan + "estimateQualityMns() : " + endC + "vector_cut_input : " + str(vector_cut_input) + endC) print(cyan + "estimateQualityMns() : " + endC + "vector_sample_input_list : " + str(vector_sample_input_list) + endC) print(cyan + "estimateQualityMns() : " + endC + "vector_sample_points_input : " + str(vector_sample_points_input) + endC) print(cyan + "estimateQualityMns() : " + endC + "raster_input_dico : " + str(raster_input_dico) + endC) print(cyan + "estimateQualityMns() : " + endC + "vector_output : " + str(vector_output) + endC) print(cyan + "estimateQualityMns() : " + endC + "no_data_value : " + str(no_data_value)) print(cyan + "estimateQualityMns() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "estimateQualityMns() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "estimateQualityMns() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "estimateQualityMns() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "estimateQualityMns() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "estimateQualityMns() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + "estimateQualityMns() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "estimateQualityMns() : " + endC + "overwrite : " + str(overwrite) + endC) # Définion des constantes EXT_DBF = '.dbf' EXT_CSV = '.csv' CODAGE = "uint16" SUFFIX_STUDY = '_study' SUFFIX_CUT = '_cut' SUFFIX_TEMP = '_temp' SUFFIX_CLEAN = '_clean' SUFFIX_SAMPLE = '_sample' ATTRIBUTE_ID = "ID" ATTRIBUTE_Z_INI = "Z_INI" ATTRIBUTE_Z_FIN = "Z_FIN" ATTRIBUTE_PREC_ALTI = "PREC_ALTI" ATTRIBUTE_Z_REF = "Z_Ref" ATTRIBUTE_Z_MNS = "Z_Mns" ATTRIBUTE_Z_DELTA = "Z_Delta" ERODE_EDGE_POINTS = -1.0 ERROR_VALUE = -99.0 ERROR_MIN_VALUE = -9999 ERROR_MAX_VALUE = 9999 # ETAPE 0 : PREPARATION DES FICHIERS INTERMEDIAIRES # Si le fichier de sortie existe on ecrase check = os.path.isfile(vector_output) if check and not overwrite: # Si un fichier de sortie avec le même nom existe déjà, et si l'option ecrasement est à false, alors FIN print(cyan + "estimateQualityMns() : " + bold + yellow + "Create file %s already exist : no actualisation" % (vector_output) + endC) return if os.path.isfile(os.path.splitext(vector_output)[0] + EXT_CSV): removeFile(os.path.splitext(vector_output)[0] + EXT_CSV) repertory_output = os.path.dirname(vector_output) base_name = os.path.splitext(os.path.basename(vector_output))[0] vector_output_temp = repertory_output + os.sep + base_name + SUFFIX_TEMP + extension_vector raster_study = repertory_output + os.sep + base_name + SUFFIX_STUDY + extension_raster vector_study = repertory_output + os.sep + base_name + SUFFIX_STUDY + extension_vector vector_study_clean = repertory_output + os.sep + base_name + SUFFIX_STUDY + SUFFIX_CLEAN + extension_vector image_cut = repertory_output + os.sep + base_name + SUFFIX_CUT + extension_raster vector_sample_temp = repertory_output + os.sep + base_name + SUFFIX_SAMPLE + SUFFIX_TEMP + extension_vector vector_sample_temp_clean = repertory_output + os.sep + base_name + SUFFIX_SAMPLE + SUFFIX_TEMP + SUFFIX_CLEAN + extension_vector # Utilisation des données raster externes raster_cut_dico = {} for raster_input in raster_input_dico: base_name_raster = os.path.splitext(os.path.basename(raster_input))[0] raster_cut = repertory_output + os.sep + base_name_raster + SUFFIX_CUT + extension_raster raster_cut_dico[raster_input] = raster_cut if os.path.exists(raster_cut): removeFile(raster_cut) # ETAPE 1 : DEFINIR UN SHAPE ZONE D'ETUDE if (not vector_cut_input is None) and (vector_cut_input != "") and ( os.path.isfile(vector_cut_input)): cutting_action = True vector_study = vector_cut_input else: cutting_action = False createVectorMask(image_input, vector_study) # ETAPE 2 : DECOUPAGE DU RASTEUR PAR LE VECTEUR D'ETUDE SI BESOIN ET REECHANTILLONAGE SI BESOIN if cutting_action: # Identification de la tailles de pixels en x et en y du fichier MNS de reference pixel_size_x, pixel_size_y = getPixelWidthXYImage(image_input) # Si le fichier de sortie existe deja le supprimer if os.path.exists(image_cut): removeFile(image_cut) # Commande de découpe if not cutImageByVector(vector_study, image_input, image_cut, pixel_size_x, pixel_size_y, no_data_value, 0, format_raster, format_vector): print( cyan + "estimateQualityMns() : " + bold + red + "Une erreur c'est produite au cours du decoupage de l'image : " + image_input + endC, file=sys.stderr) raise if debug >= 2: print(cyan + "estimateQualityMns() : " + bold + green + "DECOUPAGE DU RASTER %s AVEC LE VECTEUR %s" % (image_input, vector_study) + endC) else: image_cut = image_input # Definir l'emprise du fichier MNS de reference # Decoupage de chaque raster de la liste des rasters for raster_input in raster_input_dico: raster_cut = raster_cut_dico[raster_input] if not cutImageByVector(vector_study, raster_input, raster_cut, pixel_size_x, pixel_size_y, no_data_value, 0, format_raster, format_vector): raise NameError( cyan + "estimateQualityMns() : " + bold + red + "Une erreur c'est produite au cours du decoupage du raster : " + raster_input + endC) # Gémotrie de l'image pixel_size_x, pixel_size_y = getPixelWidthXYImage(image_cut) cols, rows, bands = getGeometryImage(image_cut) xmin, xmax, ymin, ymax = getEmpriseImage(image_cut) if debug >= 3: print("Geometrie Image : ") print(" cols = " + str(cols)) print(" rows = " + str(rows)) print(" xmin = " + str(xmin)) print(" xmax = " + str(xmax)) print(" ymin = " + str(ymin)) print(" ymax = " + str(ymax)) print(" pixel_size_x = " + str(pixel_size_x)) print(" pixel_size_y = " + str(pixel_size_y)) print("\n") # Création du dico coordonnées des points en systeme cartographique points_random_value_dico = {} # liste coordonnées des points au format matrice image brute points_coordonnees_image_list = [] # Selon que l'on utilise le fichier de points d'echantillons ou que l'on recréé a partir des sommets des vecteurs lignes if (vector_sample_points_input is None) or (vector_sample_points_input == ""): # ETAPE 3 : DECOUPAGES DES VECTEURS DE REFERENCE D'ENTREE PAR LE VECTEUR D'ETUDE ET LEUR FUSION ET # LECTURE D'UN VECTEUR DE LIGNES ET SAUVEGARDE DES COORDONNEES POINTS DES EXTREMITEES ET LEUR HAUTEUR # Découpage des vecteurs de bd réference avec le vecteur zone d'étude vector_sample_input_cut_list = [] for vector_sample in vector_sample_input_list: vector_name = os.path.splitext(os.path.basename(vector_sample))[0] vector_sample_cut = repertory_output + os.sep + vector_name + SUFFIX_CUT + extension_vector vector_sample_input_cut_list.append(vector_sample_cut) cutoutVectors(vector_study, vector_sample_input_list, vector_sample_input_cut_list, format_vector) # Fusion des vecteurs de bd réference découpés fusionVectors(vector_sample_input_cut_list, vector_sample_temp, format_vector) # Preparation des colonnes names_column_start_point_list = [ ATTRIBUTE_ID, ATTRIBUTE_Z_INI, ATTRIBUTE_PREC_ALTI ] names_column_end_point_list = [ ATTRIBUTE_ID, ATTRIBUTE_Z_FIN, ATTRIBUTE_PREC_ALTI ] fields_list = [ ATTRIBUTE_ID, ATTRIBUTE_PREC_ALTI, ATTRIBUTE_Z_INI, ATTRIBUTE_Z_FIN ] multigeometries2geometries(vector_sample_temp, vector_sample_temp_clean, fields_list, "MULTILINESTRING", format_vector) points_coordinates_dico = readVectorFileLinesExtractTeminalsPoints( vector_sample_temp_clean, names_column_start_point_list, names_column_end_point_list, format_vector) else: # ETAPE 3_BIS : DECOUPAGE DE VECTEURS D'ECHANTILLONS POINTS PAR LE VECTEUR D'EMPRISE ET # LECTURE DES COORDONNES D'ECHANTILLONS DURECTEMENT DANS LE FICHIER VECTEUR POINTS # Liste coordonnées des points au format matrice image brute cutVectorAll(vector_study, vector_sample_points_input, vector_sample_temp, format_vector) points_coordinates_dico = readVectorFilePoints(vector_sample_temp, format_vector) # ETAPE 4 : PREPARATION DU VECTEUR DE POINTS for index_key in points_coordinates_dico: # Recuperer les valeurs des coordonnees coord_info_list = points_coordinates_dico[index_key] coor_x = coord_info_list[0] coor_y = coord_info_list[1] attribut_dico = coord_info_list[2] # Coordonnées des points au format matrice image pos_x = int(round((coor_x - xmin) / abs(pixel_size_x)) - 1) pos_y = int(round((ymax - coor_y) / abs(pixel_size_y)) - 1) if pos_x < 0: pos_x = 0 if pos_x >= cols: pos_x = cols - 1 if pos_y < 0: pos_y = 0 if pos_y >= rows: pos_y = rows - 1 coordonnees_list = [pos_x, pos_y] points_coordonnees_image_list.append(coordonnees_list) value_ref = 0.0 if ATTRIBUTE_Z_INI in attribut_dico.keys(): value_ref = float(attribut_dico[ATTRIBUTE_Z_INI]) if ATTRIBUTE_Z_FIN in attribut_dico.keys(): value_ref = float(attribut_dico[ATTRIBUTE_Z_FIN]) precision_alti = 0.0 if ATTRIBUTE_PREC_ALTI in attribut_dico.keys(): precision_alti = float(attribut_dico[ATTRIBUTE_PREC_ALTI]) point_attr_dico = { ATTRIBUTE_ID: index_key, ATTRIBUTE_Z_REF: value_ref, ATTRIBUTE_PREC_ALTI: precision_alti, ATTRIBUTE_Z_MNS: 0.0, ATTRIBUTE_Z_DELTA: 0.0 } for raster_input in raster_input_dico: field_name = raster_input_dico[raster_input][0][0] point_attr_dico[field_name] = 0.0 points_random_value_dico[index_key] = [[coor_x, coor_y], point_attr_dico] # ETAPE 5 : LECTURE DES DONNEES DE HAUTEURS ISSU DU MNS et autre raster # Lecture dans le fichier raster des valeurs values_height_list = getPixelsValueListImage( image_cut, points_coordonnees_image_list) values_others_dico = {} for raster_input in raster_input_dico: raster_cut = raster_cut_dico[raster_input] values_list = getPixelsValueListImage(raster_cut, points_coordonnees_image_list) values_others_dico[raster_input] = values_list for i in range(len(points_random_value_dico)): value_mns = values_height_list[i] value_ref = points_random_value_dico[i][1][ATTRIBUTE_Z_REF] points_random_value_dico[i][1][ATTRIBUTE_Z_MNS] = float(value_mns) precision_alti = points_random_value_dico[i][1][ATTRIBUTE_PREC_ALTI] points_random_value_dico[i][1][ATTRIBUTE_PREC_ALTI] = float( precision_alti) value_diff = value_ref - value_mns points_random_value_dico[i][1][ATTRIBUTE_Z_DELTA] = float(value_diff) for raster_input in raster_input_dico: field_name = raster_input_dico[raster_input][0][0] value_other = values_others_dico[raster_input][i] points_random_value_dico[i][1][field_name] = float(value_other) # ETAPE 6 : CREATION D'UN VECTEUR DE POINTS AVEC DONNEE COORDONNES POINT ET HAUTEUR REFERENCE ET MNS # Suppression des points contenant des valeurs en erreur et en dehors du filtrage points_random_value_dico_clean = {} for i in range(len(points_random_value_dico)): value_ref = points_random_value_dico[i][1][ATTRIBUTE_Z_REF] if value_ref != ERROR_VALUE and value_ref > ERROR_MIN_VALUE and value_ref < ERROR_MAX_VALUE: points_is_valid = True for raster_input in raster_input_dico: if len(raster_input_dico[raster_input]) > 1 and len( raster_input_dico[raster_input][1]) > 1: threshold_min = float( raster_input_dico[raster_input][1][0]) threshold_max = float( raster_input_dico[raster_input][1][1]) field_name = raster_input_dico[raster_input][0][0] value_raster = float( points_random_value_dico[i][1][field_name]) if value_raster < threshold_min or value_raster > threshold_max: points_is_valid = False if points_is_valid: points_random_value_dico_clean[i] = points_random_value_dico[i] # Définir les attibuts du fichier résultat attribute_dico = { ATTRIBUTE_ID: ogr.OFTInteger, ATTRIBUTE_PREC_ALTI: ogr.OFTReal, ATTRIBUTE_Z_REF: ogr.OFTReal, ATTRIBUTE_Z_MNS: ogr.OFTReal, ATTRIBUTE_Z_DELTA: ogr.OFTReal } for raster_input in raster_input_dico: field_name = raster_input_dico[raster_input][0][0] attribute_dico[field_name] = ogr.OFTReal createPointsFromCoordList(attribute_dico, points_random_value_dico_clean, vector_output_temp, epsg, format_vector) # Suppression des points en bord de zone d'étude bufferVector(vector_study, vector_study_clean, ERODE_EDGE_POINTS, "", 1.0, 10, format_vector) cutVectorAll(vector_study_clean, vector_output_temp, vector_output, True, format_vector) # ETAPE 7 : TRANSFORMATION DU FICHIER .DBF EN .CSV dbf_file = repertory_output + os.sep + base_name + EXT_DBF csv_file = repertory_output + os.sep + base_name + EXT_CSV if debug >= 2: print(cyan + "estimateQualityMns() : " + bold + green + "Conversion du fichier DBF %s en fichier CSV %s" % (dbf_file, csv_file) + endC) convertDbf2Csv(dbf_file, csv_file) # ETAPE 8 : SUPPRESIONS FICHIERS INTERMEDIAIRES INUTILES # Suppression des données intermédiaires if not save_results_intermediate: if cutting_action: if os.path.isfile(image_cut): removeFile(image_cut) else: if os.path.isfile(vector_study): removeVectorFile(vector_study) for raster_input in raster_input_dico: raster_cut = raster_cut_dico[raster_input] if os.path.isfile(raster_cut): removeFile(raster_cut) if os.path.isfile(vector_output_temp): removeVectorFile(vector_output_temp) if os.path.isfile(vector_study_clean): removeVectorFile(vector_study_clean) if os.path.isfile(vector_sample_temp): removeVectorFile(vector_sample_temp) if os.path.isfile(vector_sample_temp_clean): removeVectorFile(vector_sample_temp_clean) for vector_file in vector_sample_input_cut_list: if os.path.isfile(vector_file): removeVectorFile(vector_file) print(bold + green + "## END : CREATE HEIGHT POINTS FILE FROM MNSE" + endC) # Mise à jour du Log ending_event = "estimateQualityMns() : Masks creation ending : " timeLine(path_time_log, ending_event) return
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 rasterAssembly(input_images_list, output_image, radius, value_to_force, boundaries_shape, no_data_value, path_time_log, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", save_results_inter=False, overwrite=True): # Mise à jour du Log starting_event = "rasterAssembly() : Assemblage d'images raster starting " timeLine(path_time_log, starting_event) if debug >= 3: print(cyan + "rasterAssembly() : " + endC + "input_images_list : " + str(input_images_list)) print(cyan + "rasterAssembly() : " + endC + "output_image : " + str(output_image)) print(cyan + "rasterAssembly() : " + endC + "radius : " + str(radius)) print(cyan + "rasterAssembly() : " + endC + "value_to_force : " + str(value_to_force)) print(cyan + "rasterAssembly() : " + endC + "boundaries_shape : " + str(boundaries_shape)) print(cyan + "rasterAssembly() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "rasterAssembly() : " + endC + "path_time_log : " + str(path_time_log)) print(cyan + "rasterAssembly() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "rasterAssembly() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "rasterAssembly() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "rasterAssembly() : " + endC + "save_results_inter : " + str(save_results_inter)) print(cyan + "rasterAssembly() : " + endC + "overwrite : " + str(overwrite)) print(cyan + "rasterAssembly() : " + bold + green + "START ...\n" + endC) # Gestion des noms de variables CODAGE = "uint16" images_input_list_str = " " for input_image in input_images_list: images_input_list_str += input_image + " " output_dir = os.path.dirname(output_image) output_name = os.path.splitext(os.path.basename(output_image))[0] temp_directory = output_dir + os.sep + "Temp" vrt_image = temp_directory + os.sep + output_name + '_vrt' + extension_raster assembled_image = temp_directory + os.sep + output_name + '_assembled' + extension_raster assembled_smoothed_image = temp_directory + os.sep + output_name + '_assembled_smoothed' + extension_raster assembled_cleaned_with_smooth_image = temp_directory + os.sep + output_name + '_assembled_cleaned_with_smooth' + extension_raster assembled_cleaned_with_smooth_and_value_to_force_image = temp_directory + os.sep + output_name + '_assembled_cleaned_with_smooth_and_value_to_force' + extension_raster assembled_cleaned_cutted_image = temp_directory + os.sep + output_name + '_assembled_cleaned_cutted' + extension_raster # ETAPE 1/5 : CREATION DU RASTER VIRTUEL if not os.path.exists(temp_directory): os.makedirs(temp_directory) command = "gdalbuildvrt -srcnodata %s %s %s" % ( str(no_data_value), vrt_image, images_input_list_str) if debug >= 2: print( '\n' + cyan + "rasterAssembly() : " + bold + green + "ETAPE 1/5 : DEBUT DE LA CREATION DU RASTER VIRTUEL. Sortie : %s - Entrees : %s" % (vrt_image, images_input_list_str) + endC) print(command) exitCode = os.system(command) if exitCode != 0: raise NameError( cyan + "rasterAssembly() : " + bold + red + "An error occured during the virtual raster construction. See error message above." ) else: if debug >= 2: print('\n' + cyan + "rasterAssembly() : " + bold + green + "ETAPE 1/5 : FIN DE LA CREATION DU RASTER VIRTUEL" + endC) # ETAPE 2/5 : DEBUT DE LA CONVERSION DU RASTER VIRTUEL EN .tif command = "gdal_translate -a_nodata %s -of %s %s %s" % ( str(no_data_value), format_raster, vrt_image, assembled_image) if debug >= 2: print( '\n' + cyan + "rasterAssembly() : " + bold + green + "ETAPE 2/5 : DEBUT DE LA CONVERSION DU RASTER VIRTUEL EN .tif. Entree : %s - Sortie : %s" % (vrt_image, assembled_image) + endC) print(command) exitCode = os.system(command) if exitCode != 0: raise NameError( cyan + "rasterAssembly() : " + bold + red + "An error occured during the virtual raster conversion. See error message above." ) else: if debug >= 2: print( '\n' + cyan + "rasterAssembly() : " + bold + green + "ETAPE 2/5 : FIN DE LA CONVERSION DU RASTER VIRTUEL EN .tif. " + endC) # ETAPE 3/5 : SUPPRESSION EVENTUELLE DU RASTER VIRTUEL if not save_results_inter: if debug >= 2: print('\n' + cyan + "rasterAssembly() : " + bold + green + "ETAPE 3/5 : DEBUT DE LA SUPRESSION DU RASTER VIRTUEL %s" % (vrt_image) + endC) try: removeFile(vrt_image) # Tentative de suppression du fichier except Exception: pass # Si le fichier ne peut pas être supprimé, on suppose qu'il n'existe pas et on passe à la suite if debug >= 2: print(cyan + "rasterAssembly() : " + bold + green + "ETAPE 3/5 : FIN DE LA SUPRESSION DU RASTER VIRTUEL" + endC) else: if debug >= 2: print(cyan + "rasterAssembly() : " + bold + yellow + "ETAPE 3/5 : PAS DE SUPPRESSION DU RASTER VIRTUEL %s" % (vrt_image) + endC) # ETAPE 4/5 et 5/5 : SI DEMANDE : CALCUL ET APPLICATION DU FILTRE MAJORITAIRE if radius > 0: # ETAPE 4/5 : Calcul du fichier filtre majoritaire command = "otbcli_ClassificationMapRegularization -io.in %s -io.out %s %s -ip.radius %d" % ( assembled_image, assembled_smoothed_image, CODAGE, radius) if debug >= 2: print( '\n' + cyan + "rasterAssembly() : " + bold + green + "ETAPE 4/5 : DEBUT DU CALCUL DU FILTRE MAJORITAIRE DE RAYON %s. Entree : %s - Sortie : %s" % (radius, assembled_image, assembled_smoothed_image) + endC) print(command) exitCode = os.system(command) if exitCode != 0: raise NameError( cyan + "rasterAssembly() : " + bold + red + "An error occured during otbcli_ClassificationMapRegularization command. See error message above." ) else: if debug >= 2: print(cyan + "rasterAssembly() : " + bold + green + "ETAPE 4/5 : FIN DU CALCUL DU FILTRE MAJORITAIRE" + endC) # ETAPE 5/5 : Utilisation du fichier raster filtre majoritaire pour boucher les trous eventuels entre les images assemblées expression = "\"(im1b1 == 0? im2b1 : im1b1)\"" command = "otbcli_BandMath -il %s %s -exp %s -out %s %s" % ( assembled_image, assembled_smoothed_image, expression, assembled_cleaned_with_smooth_image, CODAGE) if debug >= 2: print( '\n' + cyan + "rasterAssembly() : " + bold + green + "ETAPE 5/5 : DEBUT DE L'APPLICATION DU FILTRE MAJORITAIRE. Sortie : %s - Entree : %s et %s" % (assembled_cleaned_with_smooth_image, assembled_image, assembled_smoothed_image) + endC) print(command) exitCode = os.system(command) if exitCode != 0: raise NameError( cyan + "rasterAssembly() : " + bold + red + "An error occured during otbcli_BandMath command. See error message above." ) else: if debug >= 2: print( cyan + "rasterAssembly() : " + bold + green + "ETAPE 5/5 : FIN DE L'APPLICATION DU FILTRE MAJORITAIRE" + endC) # Supression éventuelle du filtre majoritaire et de l'image non nettoyée if not save_results_inter: if debug >= 2: print( cyan + "rasterAssembly() : " + bold + green + "SUPRESSION DU FILTRE MAJORITAIRE %s ET DE L'IMAGE NON NETTOYEE %s" % (assembled_smoothed_image, assembled_image) + endC) try: removeFile(assembled_smoothed_image ) # Tentative de suppression du fichier except Exception: pass # Si le fichier ne peut pas être supprimé, on suppose qu'il n'existe pas et on passe à la suite try: removeFile( assembled_image) # Tentative de suppression du fichier except Exception: pass # Si le fichier ne peut pas être supprimé, on suppose qu'il n'existe pas et on passe à la suite else: # Cas où le filtre majoritaire n'est pas demandé assembled_cleaned_with_smooth_image = assembled_image if debug >= 2: print('\n' + cyan + "rasterAssembly() : " + bold + yellow + "ETAPE 4/5 : PAS DE CALCUL DU FILTRE MAJORITAIRE DEMANDE" + endC) print( '\n' + cyan + "rasterAssembly() : " + bold + yellow + "ETAPE 5/5 : PAS D'APPLICATION DU FILTRE MAJORITAIRE DEMANDE" + endC) # ETAPE 6/5 : SI DEMANDE : ON IMPOSE UNE VALEUR "value_to_force" POUR LES 0 RESTANTS if value_to_force > 0: expression = "\"(im1b1 == 0? %d : im1b1)\"" % (value_to_force) command = "otbcli_BandMath -il %s -exp %s -out %s %s" % ( assembled_cleaned_with_smooth_image, expression, assembled_cleaned_with_smooth_and_value_to_force_image, CODAGE) if debug >= 2: print( '\n' + cyan + "rasterAssembly() : " + bold + green + "ETAPE 6/5 : DEBUT DU NETTOYAGE DES ZEROS RESTANTS, TRANSFORMES EN %s. SORTIE : %s" % (value_to_force, assembled_cleaned_with_smooth_and_value_to_force_image) + endC) print(command) exitCode = os.system(command) if exitCode != 0: raise NameError( cyan + "rasterAssembly() : " + bold + red + "An error occured during the otbcli_BandMath command. See error message above." ) else: if debug >= 2: print(cyan + "rasterAssembly() : " + bold + green + "ETAPE 6/5 : FIN DU NETTOYAGE DES ZEROS RESTANTS" + endC) # Supression éventuelle de l'image non nettoyée if not save_results_inter: if debug >= 2: print(cyan + "rasterAssembly() : " + bold + green + "SUPRESSION DE L'IMAGE NON NETTOYEE %s" % (assembled_cleaned_with_smooth_image) + endC) try: removeFile(assembled_cleaned_with_smooth_image ) # Tentative de suppression du fichier except Exception: pass # Si le fichier ne peut pas être supprimé, on suppose qu'il n'existe pas et on passe à la suite else: # Cas où le forcage d'une valeur n'est pas demandé assembled_cleaned_with_smooth_and_value_to_force_image = assembled_cleaned_with_smooth_image if debug >= 2: print('\n' + cyan + "rasterAssembly() : " + bold + yellow + "ETAPE 6/5 : AUCUNE VALEUR IMPOSEE POUR LES 0" + endC) # ETAPE 7/5 : SI DEMANDE : DECOUPAGE AU REGARD DE L'EMPRISE if boundaries_shape != "": if debug >= 2: print( '\n' + cyan + "rasterAssembly() : " + bold + green + "ETAPE 7/5 : DEBUT DU DECOUPAGE AU REGARD DE L EMPRISE GLOBALE %s" % (boundaries_shape) + endC) if not cutImageByVector( boundaries_shape, assembled_cleaned_with_smooth_and_value_to_force_image, output_image, None, None, no_data_value, 0, format_raster, format_vector): raise NameError( cyan + "rasterAssembly() : " + bold + red + "An error occured during the cutting. See error message above." ) else: if debug >= 2: print( cyan + "rasterAssembly() : " + bold + green + "ETAPE 7/5 : FIN DU DECOUPAGE AU REGARD DE L'EMPRISE GLOBALE" + endC) # Supression éventuelle de l'image non découpée if not save_results_inter: if debug >= 2: print( cyan + "rasterAssembly() : " + bold + green + "SUPRESSION DE L'IMAGE NON DECOUPEE %s" % (assembled_cleaned_with_smooth_and_value_to_force_image) + endC) try: removeFile( assembled_cleaned_with_smooth_and_value_to_force_image ) # Tentative de suppression du fichier except Exception: pass # Si le fichier ne peut pas être supprimé, on suppose qu'il n'existe pas et on passe à la suite else: os.rename( assembled_cleaned_with_smooth_and_value_to_force_image, output_image ) # Dans ce cas, l'image finale est assembled_cleaned_with_smooth_and_value_to_force_image, qu'il faut renommer if debug >= 2: print('\n' + cyan + "rasterAssembly() : " + bold + yellow + "ETAPE 7/5 : AUCUN DECOUPAGE FINAL DEMANDE" + endC) # SUPPRESSION DU DOSSIER TEMP if not save_results_inter and os.path.exists(temp_directory): deleteDir(temp_directory) if debug >= 2: print(cyan + "rasterAssembly() : " + bold + green + "FIN DE L'ASSEMBLAGE DES RASTERS. Sortie : %s" % (output_image) + endC) # Mise à jour du Log ending_event = "rasterAssembly() : Realocation micro class on classification image ending : " timeLine(path_time_log, ending_event) return
def binaryMaskVect(input_image, output_dir, threshold, input_cut_vector, attributes_list, no_data_value, epsg, format_raster="GTiff", format_vector="ESRI Shapefile", extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True): # Affichage des paramètres if debug >= 3: print(bold + green + "Variables dans le binaryMaskVect - Variables générales" + endC) print(cyan + "binaryMaskVect() : " + endC + "input_image : " + str(input_image) + endC) print(cyan + "binaryMaskVect() : " + endC + "output_dir : " + str(output_dir) + endC) print(cyan + "binaryMaskVect() : " + endC + "threshold : " + str(threshold) + endC) print(cyan + "binaryMaskVect() : " + endC + "input_cut_vector : " + str(input_cut_vector) + endC) print(cyan + "binaryMaskVect() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "binaryMaskVect() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "binaryMaskVect() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "binaryMaskVect() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + "binaryMaskVect() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "binaryMaskVect() : " + endC + "overwrite : " + str(overwrite) + endC) image_name = os.path.splitext(os.path.basename(input_image))[0] binary_mask = output_dir + os.sep + "bin_mask_" + image_name + "_" + str( threshold).replace('.', '_') + extension_raster binary_mask_decoup = output_dir + os.sep + "bin_mask_decoup_" + image_name + "_" + str( threshold).replace('.', '_') + extension_raster binary_mask_vector = output_dir + os.sep + "bin_mask_vect_" + image_name + "_" + str( threshold).replace('.', '_') + extension_vector # Création du répertoire de sortie s'il n'existe pas déjà if not os.path.exists(output_dir): os.makedirs(output_dir) # Suppression des fichiers temporaires pour les calculs if os.path.exists(binary_mask): removeFile(binary_mask) if os.path.exists(binary_mask_decoup): removeFile(binary_mask_decoup) if os.path.exists(binary_mask_vector): if overwrite: removeVectorFile(binary_mask_vector, format_vector) else: return binary_mask_vector # Création du masque binaire createBinaryMask(input_image, binary_mask, threshold, False) if input_cut_vector != "": # Découpe du raster cutImageByVector(input_cut_vector, binary_mask, binary_mask_decoup, None, None, no_data_value, epsg, format_raster, format_vector) else: binary_mask_decoup = binary_mask # Vectorisation du masque binaire découpé polygonizeRaster(binary_mask_decoup, binary_mask_vector, image_name, "id", format_vector) # Ajout des champs au fichier vecteur créé for attribute in attributes_list: addNewFieldVector(binary_mask_vector, attribute.name, attribute.ogrType, attribute.value, attribute.width, None, format_vector) # Suppresions des fichiers intermediaires inutiles et reperoire temporaire if not save_results_intermediate: removeFile(binary_mask) removeFile(binary_mask_decoup) return binary_mask_vector
def classesOfWaterHeights(input_flooded_areas_vector, input_digital_elevation_model_file, output_heights_classes_file, output_heights_classes_vector, heights_classes='0,0.5,1,1.5,2', epsg=2154, no_data_value=0, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster='.tif', extension_vector='.shp', grass_gisbase=os.environ['GISBASE'], grass_gisdb='GRASS_database', grass_location='LOCATION', grass_mapset='MAPSET', path_time_log='', save_results_intermediate=False, overwrite=True): if debug >= 3: print('\n' + bold + green + "Classes de hauteurs d'eau - Variables dans la fonction :" + endC) print(cyan + " classesOfWaterHeights() : " + endC + "input_flooded_areas_vector : " + str(input_flooded_areas_vector) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "input_digital_elevation_model_file : " + str(input_digital_elevation_model_file) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "output_heights_classes_file : " + str(output_heights_classes_file) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "output_heights_classes_vector : " + str(output_heights_classes_vector) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "heights_classes : " + str(heights_classes) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "grass_gisbase : " + str(grass_gisbase) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "grass_gisdb : " + str(grass_gisdb) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "grass_location : " + str(grass_location) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "grass_mapset : " + str(grass_mapset) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + " classesOfWaterHeights() : " + endC + "overwrite : " + str(overwrite) + endC + '\n') # Définition des constantes ENCODING_RASTER_FLOAT = 'float' ENCODING_RASTER_UINT8 = 'uint8' EXTENSION_RASTER_SAGA = '.sdat' FORMAT_VECTOR_GRASS = format_vector.replace(' ', '_') SUFFIX_TEMP = '_temp' SUFFIX_LINES = '_lines' SUFFIX_POINTS = '_points' SUFFIX_ALTI = '_altitude' SUFFIX_CUT = '_cut' SUFFIX_RAW = '_raw_heights' INDEX_FIELD = 'idx' ALTI_FIELD = 'altitude' VECTORISATION = 'GRASS' # Mise à jour du log starting_event = "classesOfWaterHeights() : Début du traitement : " timeLine(path_time_log, starting_event) print(cyan + "classesOfWaterHeights() : " + bold + green + "DEBUT DES TRAITEMENTS" + endC + '\n') # Définition des variables 'basename' flooded_areas_basename = os.path.splitext( os.path.basename(input_flooded_areas_vector))[0] digital_elevation_model_basename = os.path.splitext( os.path.basename(input_digital_elevation_model_file))[0] flooded_areas_lines_basename = flooded_areas_basename + SUFFIX_LINES flooded_areas_points_basename = flooded_areas_basename + SUFFIX_POINTS if output_heights_classes_file != "": output_heights_classes_basename = os.path.splitext( os.path.basename(output_heights_classes_file))[0] output_dirname = os.path.dirname(output_heights_classes_file) else: output_heights_classes_basename = os.path.splitext( os.path.basename(output_heights_classes_vector))[0] output_dirname = os.path.dirname(output_heights_classes_vector) # Définition des variables temp temp_directory = output_dirname + os.sep + output_heights_classes_basename + SUFFIX_TEMP flooded_areas_lines = temp_directory + os.sep + flooded_areas_lines_basename + extension_vector flooded_areas_points = temp_directory + os.sep + flooded_areas_points_basename + extension_vector altitude_points = temp_directory + os.sep + flooded_areas_points_basename + SUFFIX_ALTI + extension_vector altitude_grid = temp_directory + os.sep + flooded_areas_basename + SUFFIX_ALTI + EXTENSION_RASTER_SAGA altitude_file = temp_directory + os.sep + flooded_areas_basename + SUFFIX_ALTI + SUFFIX_CUT + extension_raster digital_elevation_model_cut = temp_directory + os.sep + digital_elevation_model_basename + SUFFIX_CUT + extension_raster raw_heights = temp_directory + os.sep + flooded_areas_basename + SUFFIX_RAW + extension_raster heights_classes_temp = temp_directory + os.sep + output_heights_classes_basename + extension_raster if output_heights_classes_file == "": output_heights_classes_file = output_dirname + os.sep + output_heights_classes_basename + extension_raster # Nettoyage des traitements précédents if debug >= 3: print(cyan + "classesOfWaterHeights() : " + endC + "Nettoyage des traitements précédents." + endC + '\n') removeFile(output_heights_classes_file) removeVectorFile(output_heights_classes_vector, format_vector=format_vector) cleanTempData(temp_directory) ############# # Etape 0/6 # Préparation des traitements ############# print(cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 0/6 - Début de la préparation des traitements." + endC + '\n') # Préparation de GRASS xmin, xmax, ymin, ymax = getEmpriseImage( input_digital_elevation_model_file) pixel_width, pixel_height = getPixelWidthXYImage( input_digital_elevation_model_file) grass_gisbase, grass_gisdb, grass_location, grass_mapset = initializeGrass( temp_directory, xmin, xmax, ymin, ymax, pixel_width, pixel_height, projection=epsg, gisbase=grass_gisbase, gisdb=grass_gisdb, location=grass_location, mapset=grass_mapset, clean_old=True, overwrite=overwrite) # Gestion des classes de hauteurs d'eau thresholds_list = heights_classes.split(',') thresholds_list_float = [float(x) for x in thresholds_list] thresholds_list_float.sort() thresholds_list_float_len = len(thresholds_list_float) print(cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 0/6 - Fin de la préparation des traitements." + endC + '\n') ############# # Etape 1/6 # Création de points sur le périmètre de l'emprise inondée ############# print( cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 1/6 - Début de la création de points sur le périmètre de l'emprise inondée." + endC + '\n') # Conversion de l'emprise inondée en polylignes convertePolygon2Polylines(input_flooded_areas_vector, flooded_areas_lines, overwrite=overwrite, format_vector=format_vector) # Création de points le long du polyligne use = 'vertex' dmax = 10 percent = False importVectorOgr2Grass(flooded_areas_lines, flooded_areas_lines_basename, overwrite=overwrite) pointsAlongPolylines(flooded_areas_lines_basename, flooded_areas_points_basename, use=use, dmax=dmax, percent=percent, overwrite=overwrite) exportVectorOgr2Grass(flooded_areas_points_basename, flooded_areas_points, format_vector=FORMAT_VECTOR_GRASS, overwrite=overwrite) # Ajout d'un index sur les points addNewFieldVector(flooded_areas_points, INDEX_FIELD, ogr.OFTInteger, field_value=None, field_width=None, field_precision=None, format_vector=format_vector) updateIndexVector(flooded_areas_points, index_name=INDEX_FIELD, format_vector=format_vector) print( cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 1/6 - Fin de la création de points sur le périmètre de l'emprise inondée." + endC + '\n') ############# # Etape 2/6 # Récupération de l'altitude sous chaque point ############# print( cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 2/6 - Début de la récupération de l'altitude sous chaque point." + endC + '\n') # Ajout d'un champ pour récupérer l'altitude addNewFieldVector(flooded_areas_points, ALTI_FIELD, ogr.OFTReal, field_value=None, field_width=None, field_precision=None, format_vector=format_vector) # Echantillonnage du MNT sous le fichier points importVectorOgr2Grass(flooded_areas_points, flooded_areas_points_basename, overwrite=overwrite) importRasterGdal2Grass(input_digital_elevation_model_file, digital_elevation_model_basename, overwrite=overwrite) sampleRasterUnderPoints(flooded_areas_points_basename, digital_elevation_model_basename, ALTI_FIELD, overwrite=overwrite) exportVectorOgr2Grass(flooded_areas_points_basename, altitude_points, format_vector=FORMAT_VECTOR_GRASS, overwrite=overwrite) print( cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 2/6 - Fin de la récupération de l'altitude sous chaque point." + endC + '\n') ############# # Etape 3/6 # Triangulation de l'altitude ############# print(cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 3/6 - Début de la triangulation de l'altitude." + endC + '\n') pixel_size = abs(min(pixel_width, pixel_height)) triangulationDelaunay(altitude_points, altitude_grid, ALTI_FIELD, cellsize=pixel_size) print(cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 3/6 - Fin de la triangulation de l'altitude." + endC + '\n') ############# # Etape 4/6 # Calcul des hauteurs brutes ############# print(cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 4/6 - Début du calcul des hauteurs brutes." + endC + '\n') # Redécoupage sur l'emprise inondée cutRasterImages([altitude_grid, input_digital_elevation_model_file], input_flooded_areas_vector, [altitude_file, digital_elevation_model_cut], 0, 0, epsg, no_data_value, "", False, path_time_log, format_raster=format_raster, format_vector=format_vector, extension_raster=extension_raster, extension_vector=extension_vector, save_results_intermediate=save_results_intermediate, overwrite=overwrite) # BandMath pour les hauteurs brutes (triangulation - MNT) expression = "im1b1 - im2b1" rasterCalculator([altitude_file, digital_elevation_model_cut], raw_heights, expression, codage=ENCODING_RASTER_FLOAT) print(cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 4/6 - Fin du calcul des hauteurs brutes." + endC + '\n') ############# # Etape 5/6 # Attribution des classes de hauteurs d'eau ############# print(cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 5/6 - Début de l'attribution des classes de hauteurs d'eau." + endC + '\n') # Génération de l'expression expression = "" for i in range(thresholds_list_float_len - 1): min_threshold = thresholds_list_float[i] max_threshold = thresholds_list_float[i + 1] expression += "im1b1>=%s and im1b1<%s ? %s : " % (min_threshold, max_threshold, i + 1) expression += "im1b1>=%s ? %s : 0" % (thresholds_list_float[ thresholds_list_float_len - 1], thresholds_list_float_len) # Calcul des classes de hauteurs d'eau rasterCalculator([raw_heights], heights_classes_temp, expression, codage=ENCODING_RASTER_UINT8) # Redécoupage propre des zones en dehors de l'emprise inondée cutImageByVector(input_flooded_areas_vector, heights_classes_temp, output_heights_classes_file, pixel_size_x=pixel_width, pixel_size_y=pixel_height, no_data_value=no_data_value, epsg=epsg, format_raster=format_raster, format_vector=format_vector) print(cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 5/6 - Fin de l'attribution des classes de hauteurs d'eau." + endC + '\n') ############# # Etape 6/6 # Vectorisation des classes de hauteurs d'eau ############# if output_heights_classes_vector != "": print( cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 6/6 - Début de la vectorisation des classes de hauteurs d'eau." + endC + '\n') name_column = 'class' umc_list = 0 if VECTORISATION == 'GRASS': vectorizeGrassClassification( output_heights_classes_file, output_heights_classes_vector, name_column, [umc_list], False, True, True, input_flooded_areas_vector, True, path_time_log, expression="", format_vector=format_vector, extension_raster=extension_raster, extension_vector=extension_vector, save_results_intermediate=save_results_intermediate, overwrite=overwrite) else: vectorizeClassification( output_heights_classes_file, output_heights_classes_vector, name_column, [umc_list], 2000, False, True, True, True, True, True, input_flooded_areas_vector, True, False, False, [0], path_time_log, expression="", format_vector=format_vector, extension_raster=extension_raster, extension_vector=extension_vector, save_results_intermediate=save_results_intermediate, overwrite=overwrite) print( cyan + "classesOfWaterHeights() : " + bold + green + "ETAPE 6/6 - Fin de la vectorisation des classes de hauteurs d'eau." + endC + '\n') else: print( cyan + "classesOfWaterHeights() : " + bold + yellow + "ETAPE 6/6 - Pas de vectorisation des classes de hauteurs d'eau demandée." + endC + '\n') # Suppression des fichiers temporaires if not save_results_intermediate: if debug >= 3: print(cyan + "classesOfWaterHeights() : " + endC + "Suppression des fichiers temporaires." + endC + '\n') deleteDir(temp_directory) print(cyan + "classesOfWaterHeights() : " + bold + green + "FIN DES TRAITEMENTS" + endC + '\n') # Mise à jour du log ending_event = "classesOfWaterHeights() : Fin du traitement : " timeLine(path_time_log, ending_event) return
def createMnh(image_mns_input, image_mnt_input, image_threshold_input, vector_emprise_input, image_mnh_output, automatic, bd_road_vector_input_list, bd_road_buff_list, sql_road_expression_list, bd_build_vector_input_list, height_bias, threshold_bd_value, threshold_delta_h, mode_interpolation, method_interpolation, interpolation_bco_radius, simplify_vector_param, epsg, no_data_value, ram_otb, path_time_log, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True): # Mise à jour du Log starting_event = "createMnh() : MNH creation starting : " timeLine(path_time_log,starting_event) print(endC) print(bold + green + "## START : MNH CREATION" + endC) print(endC) if debug >= 2: print(bold + green + "createMnh() : Variables dans la fonction" + endC) print(cyan + "createMnh() : " + endC + "image_mns_input : " + str(image_mns_input) + endC) print(cyan + "createMnh() : " + endC + "image_mnt_input : " + str(image_mnt_input) + endC) print(cyan + "createMnh() : " + endC + "image_threshold_input : " + str(image_threshold_input) + endC) print(cyan + "createMnh() : " + endC + "vector_emprise_input : " + str(vector_emprise_input) + endC) print(cyan + "createMnh() : " + endC + "image_mnh_output : " + str(image_mnh_output) + endC) print(cyan + "createMnh() : " + endC + "automatic : " + str(automatic) + endC) print(cyan + "createMnh() : " + endC + "bd_road_vector_input_list : " + str(bd_road_vector_input_list) + endC) print(cyan + "createMnh() : " + endC + "bd_road_buff_list : " + str(bd_road_buff_list) + endC) print(cyan + "createMnh() : " + endC + "sql_road_expression_list : " + str(sql_road_expression_list) + endC) print(cyan + "createMnh() : " + endC + "bd_build_vector_input_list : " + str(bd_build_vector_input_list) + endC) print(cyan + "createMnh() : " + endC + "height_bias : " + str(height_bias) + endC) print(cyan + "createMnh() : " + endC + "threshold_bd_value : " + str(threshold_bd_value) + endC) print(cyan + "createMnh() : " + endC + "threshold_delta_h : " + str(threshold_delta_h) + endC) print(cyan + "createMnh() : " + endC + "mode_interpolation : " + str(mode_interpolation) + endC) print(cyan + "createMnh() : " + endC + "method_interpolation : " + str(method_interpolation) + endC) print(cyan + "createMnh() : " + endC + "interpolation_bco_radius : " + str(interpolation_bco_radius) + endC) print(cyan + "createMnh() : " + endC + "simplify_vector_param : " + str(simplify_vector_param) + endC) print(cyan + "createMnh() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "createMnh() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "createMnh() : " + endC + "ram_otb : " + str(ram_otb) + endC) print(cyan + "createMnh() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "createMnh() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "createMnh() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "createMnh() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "createMnh() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + "createMnh() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "createMnh() : " + endC + "overwrite : " + str(overwrite) + endC) # LES CONSTANTES PRECISION = 0.0000001 CODAGE_8B = "uint8" CODAGE_F = "float" SUFFIX_CUT = "_cut" SUFFIX_CLEAN = "_clean" SUFFIX_SAMPLE = "_sample" SUFFIX_MASK = "_mask" SUFFIX_TMP = "_tmp" SUFFIX_MNS = "_mns" SUFFIX_MNT = "_mnt" SUFFIX_ROAD = "_road" SUFFIX_BUILD = "_build" SUFFIX_RASTER = "_raster" SUFFIX_VECTOR = "_vector" # DEFINIR LES REPERTOIRES ET FICHIERS TEMPORAIRES repertory_output = os.path.dirname(image_mnh_output) basename_mnh = os.path.splitext(os.path.basename(image_mnh_output))[0] sub_repertory_raster_temp = repertory_output + os.sep + basename_mnh + SUFFIX_RASTER + SUFFIX_TMP sub_repertory_vector_temp = repertory_output + os.sep + basename_mnh + SUFFIX_VECTOR + SUFFIX_TMP cleanTempData(sub_repertory_raster_temp) cleanTempData(sub_repertory_vector_temp) basename_vector_emprise = os.path.splitext(os.path.basename(vector_emprise_input))[0] basename_mns_input = os.path.splitext(os.path.basename(image_mns_input))[0] basename_mnt_input = os.path.splitext(os.path.basename(image_mnt_input))[0] image_mnh_tmp = sub_repertory_raster_temp + os.sep + basename_mnh + SUFFIX_TMP + extension_raster image_mnh_road = sub_repertory_raster_temp + os.sep + basename_mnh + SUFFIX_ROAD + extension_raster vector_bd_bati_temp = sub_repertory_vector_temp + os.sep + basename_mnh + SUFFIX_BUILD + SUFFIX_TMP + extension_vector vector_bd_bati = repertory_output + os.sep + basename_mnh + SUFFIX_BUILD + extension_vector raster_bd_bati = sub_repertory_vector_temp + os.sep + basename_mnh + SUFFIX_BUILD + extension_raster removeVectorFile(vector_bd_bati) image_emprise_mnt_mask = sub_repertory_raster_temp + os.sep + basename_vector_emprise + SUFFIX_MNT + extension_raster image_mnt_cut = sub_repertory_raster_temp + os.sep + basename_mnt_input + SUFFIX_CUT + extension_raster image_mnt_clean = sub_repertory_raster_temp + os.sep + basename_mnt_input + SUFFIX_CLEAN + extension_raster image_mnt_clean_sample = sub_repertory_raster_temp + os.sep + basename_mnt_input + SUFFIX_CLEAN + SUFFIX_SAMPLE + extension_raster image_emprise_mns_mask = sub_repertory_raster_temp + os.sep + basename_vector_emprise + SUFFIX_MNS + extension_raster image_mns_cut = sub_repertory_raster_temp + os.sep + basename_mns_input + SUFFIX_CUT + extension_raster image_mns_clean = sub_repertory_raster_temp + os.sep + basename_mns_input + SUFFIX_CLEAN + extension_raster vector_bd_road_temp = sub_repertory_vector_temp + os.sep + basename_mnh + SUFFIX_ROAD + SUFFIX_TMP + extension_vector raster_bd_road_mask = sub_repertory_raster_temp + os.sep + basename_mnh + SUFFIX_ROAD + SUFFIX_MASK + extension_raster if image_threshold_input != "" : basename_threshold_input = os.path.splitext(os.path.basename(image_threshold_input))[0] image_threshold_cut = sub_repertory_raster_temp + os.sep + basename_threshold_input + SUFFIX_CUT + extension_raster image_threshold_mask = sub_repertory_raster_temp + os.sep + basename_threshold_input + SUFFIX_MASK + extension_raster # VERIFICATION SI LE FICHIER DE SORTIE EXISTE DEJA # Si un fichier de sortie avec le même nom existe déjà, et si l'option ecrasement est à false, alors on ne fait rien check = os.path.isfile(image_mnh_output) if check and not overwrite: print(bold + yellow + "createMnh() : " + endC + "Create mnh %s from %s and %s already done : no actualisation" % (image_mnh_output, image_mns_input, image_mnt_input) + endC) # Si non, ou si la fonction ecrasement est désative, alors on le calcule else: if check: try: # Suppression de l'éventuel fichier existant removeFile(image_mnh_output) except Exception: pass # Si le fichier ne peut pas être supprimé, on suppose qu'il n'existe pas et on passe à la suite # DECOUPAGE DES FICHIERS MS ET MNT D'ENTREE PAR LE FICHIER D'EMPRISE if debug >= 3: print(bold + green + "createMnh() : " + endC + "Decoupage selon l'emprise des fichiers %s et %s " %(image_mns_input, image_mnt_input) + endC) # Fonction de découpe du mns if not cutImageByVector(vector_emprise_input, image_mns_input, image_mns_cut, None, None, no_data_value, epsg, format_raster, format_vector) : raise NameError (cyan + "createMnh() : " + bold + red + "!!! Une erreur c'est produite au cours du decoupage de l'image : " + image_mns_input + ". Voir message d'erreur." + endC) # Fonction de découpe du mnt if not cutImageByVector(vector_emprise_input, image_mnt_input, image_mnt_cut, None, None, no_data_value, epsg, format_raster, format_vector) : raise NameError (cyan + "createMnh() : " + bold + red + "!!! Une erreur c'est produite au cours du decoupage de l'image : " + image_mnt_input + ". Voir message d'erreur." + endC) if debug >= 3: print(bold + green + "createMnh() : " + endC + "Decoupage des fichiers %s et %s complet" %(image_mns_cut, image_mnt_cut) + endC) # REBOUCHAGE DES TROUS DANS LE MNT D'ENTREE SI NECESSAIRE nodata_mnt = getNodataValueImage(image_mnt_cut) pixelNodataCount = countPixelsOfValue(image_mnt_cut, nodata_mnt) if pixelNodataCount > 0 : if debug >= 3: print(bold + green + "createMnh() : " + endC + "Fill the holes MNT for %s" %(image_mnt_cut) + endC) # Rasterisation du vecteur d'emprise pour creer un masque pour boucher les trous du MNT rasterizeBinaryVector(vector_emprise_input, image_mnt_cut, image_emprise_mnt_mask, 1, CODAGE_8B) # Utilisation de SAGA pour boucher les trous fillNodata(image_mnt_cut, image_emprise_mnt_mask, image_mnt_clean, save_results_intermediate) if debug >= 3: print(bold + green + "createMnh() : " + endC + "Fill the holes MNT to %s completed" %(image_mnt_clean) + endC) else : image_mnt_clean = image_mnt_cut if debug >= 3: print(bold + green + "\ncreateMnh() : " + endC + "Fill the holes not necessary MNT for %s" %(image_mnt_cut) + endC) # REBOUCHAGE DES TROUS DANS LE MNS D'ENTREE SI NECESSAIRE nodata_mns = getNodataValueImage(image_mns_cut) pixelNodataCount = countPixelsOfValue(image_mns_cut, nodata_mns) if pixelNodataCount > 0 : if debug >= 3: print(bold + green + "createMnh() : " + endC + "Fill the holes MNS for %s" %(image_mns_cut) + endC) # Rasterisation du vecteur d'emprise pour creer un masque pour boucher les trous du MNS rasterizeBinaryVector(vector_emprise_input, image_mns_cut, image_emprise_mns_mask, 1, CODAGE_8B) # Utilisation de SAGA pour boucher les trous fillNodata(image_mns_cut, image_emprise_mns_mask, image_mns_clean, save_results_intermediate) if debug >= 3: print(bold + green + "\ncreateMnh() : " + endC + "Fill the holes MNS to %s completed" %(image_mns_clean) + endC) else : image_mns_clean = image_mns_cut if debug >= 3: print(bold + green + "createMnh() : " + endC + "Fill the holes not necessary MNS for %s" %(image_mns_cut) + endC) # CALLER LE FICHIER MNT AU FORMAT DU FICHIER MNS # Commande de mise en place de la geométrie re-echantionage command = "otbcli_Superimpose -inr " + image_mns_clean + " -inm " + image_mnt_clean + " -mode " + mode_interpolation + " -interpolator " + method_interpolation + " -out " + image_mnt_clean_sample if method_interpolation.lower() == 'bco' : command += " -interpolator.bco.radius " + str(interpolation_bco_radius) if ram_otb > 0: command += " -ram %d" %(ram_otb) if debug >= 3: print(cyan + "createMnh() : " + bold + green + "Réechantillonage du fichier %s par rapport à la reference %s" %(image_mnt_clean, image_mns_clean) + endC) print(command) exit_code = os.system(command) if exit_code != 0: print(command) raise NameError (cyan + "createMnh() : " + bold + red + "!!! Une erreur c'est produite au cours du superimpose de l'image : " + image_mnt_input + ". Voir message d'erreur." + endC) # INCRUSTATION DANS LE MNH DES DONNEES VECTEURS ROUTES if debug >= 3: print(bold + green + "createMnh() : " + endC + "Use BD road to clean MNH" + endC) # Creation d'un masque de filtrage des donnes routes (exemple : le NDVI) if image_threshold_input != "" : if not cutImageByVector(vector_emprise_input, image_threshold_input, image_threshold_cut, None, None, no_data_value, epsg, format_raster, format_vector) : raise NameError (cyan + "createMnh() : " + bold + red + "!!! Une erreur c'est produite au cours du decoupage de l'image : " + image_threshold_input + ". Voir message d'erreur." + endC) createBinaryMask(image_threshold_cut, image_threshold_mask, threshold_bd_value, False, CODAGE_8B) # Execution de la fonction createMacroSamples pour une image correspondant au données routes if bd_road_vector_input_list != [] : createMacroSamples(image_mns_clean, vector_emprise_input, vector_bd_road_temp, raster_bd_road_mask, bd_road_vector_input_list, bd_road_buff_list, sql_road_expression_list, path_time_log, basename_mnh, simplify_vector_param, format_vector, extension_vector, save_results_intermediate, overwrite) if debug >= 3: print(bold + green + "\ncreateMnh() : " + endC + "File raster from BD road is create %s" %(raster_bd_road_mask) + endC) # CALCUL DU MNH # Calcul par bandMath du MNH definir l'expression qui soustrait le MNT au MNS en introduisant le biais et en mettant les valeurs à 0 à une valeur approcher de 0.0000001 delta = "" if height_bias > 0 : delta = "+%s" %(str(height_bias)) elif height_bias < 0 : delta = "-%s" %(str(abs(height_bias))) else : delta = "" # Definition de l'expression if bd_road_vector_input_list != [] : if image_threshold_input != "" : expression = "\"im3b1 > 0 and im4b1 > 0?%s:(im1b1-im2b1%s) > 0.0?im1b1-im2b1%s:%s\"" %(str(PRECISION), delta, delta, str(PRECISION)) command = "otbcli_BandMath -il %s %s %s %s -out %s %s -exp %s" %(image_mns_clean, image_mnt_clean_sample, raster_bd_road_mask, image_threshold_mask, image_mnh_tmp, CODAGE_F, expression) else : expression = "\"im3b1 > 0?%s:(im1b1-im2b1%s) > 0.0?im1b1-im2b1%s:%s\"" %(str(PRECISION), delta, delta, str(PRECISION)) command = "otbcli_BandMath -il %s %s %s -out %s %s -exp %s" %(image_mns_clean, image_mnt_clean_sample, raster_bd_road_mask, image_mnh_tmp, CODAGE_F, expression) else : expression = "\"(im1b1-im2b1%s) > 0.0?im1b1-im2b1%s:%s\"" %(delta, delta, str(PRECISION)) command = "otbcli_BandMath -il %s %s -out %s %s -exp %s" %(image_mns_clean, image_mnt_clean_sample, image_mnh_tmp, CODAGE_F, expression) if ram_otb > 0: command += " -ram %d" %(ram_otb) if debug >= 3: print(cyan + "createMnh() : " + bold + green + "Calcul du MNH %s difference du MNS : %s par le MNT :%s" %(image_mnh_tmp, image_mns_clean, image_mnt_clean_sample) + endC) print(command) exitCode = os.system(command) if exitCode != 0: print(command) raise NameError(cyan + "createMnh() : " + bold + red + "An error occured during otbcli_BandMath command to compute MNH " + image_mnh_tmp + ". See error message above." + endC) # DECOUPAGE DU MNH if bd_build_vector_input_list == []: image_mnh_road = image_mnh_output if debug >= 3: print(bold + green + "createMnh() : " + endC + "Decoupage selon l'emprise du fichier mnh %s " %(image_mnh_tmp) + endC) # Fonction de découpe du mnh if not cutImageByVector(vector_emprise_input, image_mnh_tmp, image_mnh_road, None, None, no_data_value, epsg, format_raster, format_vector) : raise NameError (cyan + "createMnh() : " + bold + red + "!!! Une erreur c'est produite au cours du decoupage de l'image : " + image_mns_input + ". Voir message d'erreur." + endC) if debug >= 3: print(bold + green + "createMnh() : " + endC + "Decoupage du fichier mnh %s complet" %(image_mnh_road) + endC) # INCRUSTATION DANS LE MNH DES DONNEES VECTEURS BATIS # Si demander => liste de fichier vecteur bati passé en donnée d'entrée if bd_build_vector_input_list != []: # Découpage des vecteurs de bd bati exogenes avec l'emprise vectors_build_cut_list = [] for vector_build_input in bd_build_vector_input_list : vector_name = os.path.splitext(os.path.basename(vector_build_input))[0] vector_build_cut = sub_repertory_vector_temp + os.sep + vector_name + SUFFIX_CUT + extension_vector vectors_build_cut_list.append(vector_build_cut) cutoutVectors(vector_emprise_input, bd_build_vector_input_list, vectors_build_cut_list, format_vector) # Fusion des vecteurs batis découpés fusionVectors (vectors_build_cut_list, vector_bd_bati_temp) # Croisement vecteur rasteur entre le vecteur fusion des batis et le MNH créé precedement statisticsVectorRaster(image_mnh_road, vector_bd_bati_temp, "", 1, False, False, True, ['PREC_PLANI','PREC_ALTI','ORIGIN_BAT','median','sum','std','unique','range'], [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite) # Calcul de la colonne delta_H entre les hauteurs des batis et la hauteur moyenne du MNH sous le bati COLUMN_ID = "ID" COLUMN_H_BUILD = "HAUTEUR" COLUMN_H_BUILD_MIN = "Z_MIN" COLUMN_H_BUILD_MAX = "Z_MAX" COLUMN_H_MNH = "mean" COLUMN_H_MNH_MIN = "min" COLUMN_H_MNH_MAX = "max" COLUMN_H_DIFF = "H_diff" field_type = ogr.OFTReal field_value = 0.0 field_width = 20 field_precision = 2 attribute_name_dico = {} attribute_name_dico[COLUMN_ID] = ogr.OFTString attribute_name_dico[COLUMN_H_BUILD] = ogr.OFTReal attribute_name_dico[COLUMN_H_MNH] = ogr.OFTReal # Ajouter la nouvelle colonne H_diff addNewFieldVector(vector_bd_bati_temp, COLUMN_H_DIFF, field_type, field_value, field_width, field_precision, format_vector) # Recuperer les valeur de hauteur du bati et du mnt dans le vecteur data_z_dico = getAttributeValues(vector_bd_bati_temp, None, None, attribute_name_dico, format_vector) # Calculer la difference des Hauteur bati et mnt field_new_values_dico = {} for index in range(len(data_z_dico[COLUMN_ID])) : index_polygon = data_z_dico[COLUMN_ID][index] delta_h = abs(data_z_dico[COLUMN_H_BUILD][index] - data_z_dico[COLUMN_H_MNH][index]) field_new_values_dico[index_polygon] = {COLUMN_H_DIFF:delta_h} # Mettre à jour la colonne H_diff dans le vecteur setAttributeIndexValuesList(vector_bd_bati_temp, COLUMN_ID, field_new_values_dico, format_vector) # Suppression de tous les polygones bati dons la valeur du delat H est inferieur à threshold_delta_h column = "'%s, %s, %s, %s, %s, %s, %s, %s'"% (COLUMN_ID, COLUMN_H_BUILD, COLUMN_H_BUILD_MIN, COLUMN_H_BUILD_MAX, COLUMN_H_MNH, COLUMN_H_MNH_MIN, COLUMN_H_MNH_MAX, COLUMN_H_DIFF) expression = "%s > %s" % (COLUMN_H_DIFF, threshold_delta_h) filterSelectDataVector(vector_bd_bati_temp, vector_bd_bati, column, expression, overwrite, format_vector) # Attention!!!! PAUSE pour trie et verification des polygones bati nom deja present dans le MNH ou non if not automatic : print(bold + blue + "Application MnhCreation => " + endC + "Vérification manuelle du vecteur bati %s pour ne concerver que les batis non présent dans le MNH courant %s" %(vector_bd_bati_temp, image_mnh_road) + endC) input(bold + red + "Appuyez sur entree pour continuer le programme..." + endC) # Creation du masque bati avec pour H la hauteur des batiments rasterizeVector(vector_bd_bati, raster_bd_bati, image_mnh_road, COLUMN_H_BUILD) # Fusion du mask des batis et du MNH temporaire expression = "\"im1b1 > 0.0?im1b1:im2b1\"" command = "otbcli_BandMath -il %s %s -out %s %s -exp %s" %(raster_bd_bati, image_mnh_road, image_mnh_output, CODAGE_F, expression) if ram_otb > 0: command += " -ram %d" %(ram_otb) if debug >= 3: print(cyan + "createMnh() : " + bold + green + "Amelioration du MNH %s ajout des hauteurs des batis %s" %(image_mnh_road, raster_bd_bati) + endC) print(command) exitCode = os.system(command) if exitCode != 0: print(command) raise NameError(cyan + "createMnh() : " + bold + red + "An error occured during otbcli_BandMath command to compute MNH Final" + image_mnh_output + ". See error message above." + endC) # SUPPRESIONS FICHIERS INTERMEDIAIRES INUTILES # Suppression des fichiers intermédiaires if not save_results_intermediate : if bd_build_vector_input_list != []: removeFile(image_mnh_road) removeFile(image_threshold_cut) removeFile(image_threshold_mask) removeFile(raster_bd_bati) removeVectorFile(vector_bd_road_temp) removeVectorFile(vector_bd_bati_temp) removeVectorFile(vector_bd_bati) # A confirmer!!! removeFile(raster_bd_road_mask) removeFile(image_mnh_tmp) deleteDir(sub_repertory_raster_temp) deleteDir(sub_repertory_vector_temp) print(endC) print(bold + green + "## END : MNH CREATION" + endC) print(endC) # Mise à jour du Log ending_event = "createMnh() : MNH creation ending : " timeLine(path_time_log,ending_event) return
def computeQualityIndiceRateQuantity(raster_input, vector_sample_input, repertory_output, base_name, geom, size_grid, pixel_size_x, pixel_size_y, field_value_verif, field_value_other, no_data_value, epsg, format_raster, format_vector, extension_raster, extension_vector, overwrite=True, save_results_intermediate=False): # Définition des constantes EXT_TXT = '.txt' SUFFIX_STUDY = '_study' SUFFIX_CUT = '_cut' SUFFIX_BUILD = '_build' SUFFIX_OTHER = '_other' SUFFIX_LOCAL = '_local' SUFFIX_MATRIX = '_matrix' FIELD_NAME_CLASSIF = "classif" FIELD_TYPE = ogr.OFTInteger # Les variables locales vector_local_study = repertory_output + os.sep + base_name + SUFFIX_LOCAL + SUFFIX_STUDY + extension_vector vector_local_cut_study = repertory_output + os.sep + base_name + SUFFIX_LOCAL + SUFFIX_CUT + SUFFIX_STUDY + extension_vector vector_local_cut_build = repertory_output + os.sep + base_name + SUFFIX_LOCAL + SUFFIX_CUT + SUFFIX_BUILD + extension_vector vector_local_cut_other = repertory_output + os.sep + base_name + SUFFIX_LOCAL + SUFFIX_CUT + SUFFIX_OTHER + extension_vector vector_local_cut = repertory_output + os.sep + base_name + SUFFIX_LOCAL + SUFFIX_CUT + extension_vector raster_local_cut = repertory_output + os.sep + base_name + SUFFIX_LOCAL + SUFFIX_CUT + extension_raster matrix_local_file = repertory_output + os.sep + base_name + SUFFIX_LOCAL + SUFFIX_CUT + SUFFIX_MATRIX + EXT_TXT class_ref_list = None class_pro_list = None rate_quantity_list = None matrix_origine = None kappa = 0.0 overall_accuracy = 0.0 # Netoyage les fichiers de travail local if os.path.isfile(vector_local_study): removeVectorFile(vector_local_study) if os.path.isfile(vector_local_cut_study): removeVectorFile(vector_local_cut_study) if os.path.isfile(vector_local_cut): removeVectorFile(vector_local_cut) if os.path.isfile(vector_local_cut_build): removeVectorFile(vector_local_cut_build) if os.path.isfile(vector_local_cut_other): removeVectorFile(vector_local_cut_other) if os.path.isfile(raster_local_cut): removeFile(raster_local_cut) if os.path.isfile(matrix_local_file): removeFile(matrix_local_file) # Creation d'un shape file de travail local polygon_attr_geom_dico = {"1": [geom, {}]} createPolygonsFromGeometryList({}, polygon_attr_geom_dico, vector_local_study, epsg, format_vector) # Découpe sur zone local d'étude du fichier vecteur de référence cutVector(vector_local_study, vector_sample_input, vector_local_cut_build, format_vector) differenceVector(vector_local_cut_build, vector_local_study, vector_local_cut_other, format_vector) addNewFieldVector(vector_local_cut_build, FIELD_NAME_CLASSIF, FIELD_TYPE, field_value_verif, None, None, format_vector) addNewFieldVector(vector_local_cut_other, FIELD_NAME_CLASSIF, FIELD_TYPE, field_value_other, None, None, format_vector) input_shape_list = [vector_local_cut_build, vector_local_cut_other] fusionVectors(input_shape_list, vector_local_cut) # Découpe sur zone local d'étude du fichier rasteur de classification if not cutImageByVector(vector_local_study, raster_input, raster_local_cut, pixel_size_x, pixel_size_y, no_data_value, 0, format_raster, format_vector): return class_ref_list, class_pro_list, rate_quantity_list, kappa, overall_accuracy, matrix_origine # Calcul de la matrice de confusion computeConfusionMatrix(raster_local_cut, vector_local_cut, "", FIELD_NAME_CLASSIF, matrix_local_file, overwrite) # lecture de la matrice de confusion matrix, class_ref_list, class_pro_list = readConfusionMatrix( matrix_local_file) matrix_origine = copy.deepcopy(matrix) if matrix == []: print( cyan + "computeQualityIndiceRateQuantity() : " + bold + yellow + "!!! Une erreur c'est produite au cours de la lecture de la matrice de confusion : " + matrix_local_file + ". Voir message d'erreur." + endC) matrix_origine = None return class_ref_list, class_pro_list, rate_quantity_list, kappa, overall_accuracy, matrix_origine # Correction de la matrice de confusion # Dans le cas ou le nombre de microclasses des échantillons de controles # et le nombre de microclasses de la classification sont différents class_missing_list = [] if class_ref_list != class_pro_list: matrix, class_missing_list = correctMatrix(class_ref_list, class_pro_list, matrix, no_data_value) class_count = len(matrix[0]) - len(class_missing_list) # Calcul des indicateurs de qualité : rate_quantity_list precision_list, recall_list, fscore_list, performance_list, rate_false_positive_list, rate_false_negative_list, rate_quantity_list, class_list, overall_accuracy, overall_fscore, overall_performance, kappa = computeIndicators( class_count, matrix, class_ref_list, class_missing_list) # Chercher si une ligne no data existe si c'est le cas correction de la matrice if str(no_data_value) in class_pro_list: pos_col_nodata = class_pro_list.index(str(no_data_value)) for line in matrix_origine: del line[pos_col_nodata] class_pro_list.remove(str(no_data_value)) # Suppression des données temporaires locales if not save_results_intermediate: if os.path.isfile(vector_local_study): removeVectorFile(vector_local_study) if os.path.isfile(vector_local_cut_study): removeVectorFile(vector_local_cut_study) if os.path.isfile(vector_local_cut): removeVectorFile(vector_local_cut) if os.path.isfile(vector_local_cut_build): removeVectorFile(vector_local_cut_build) if os.path.isfile(vector_local_cut_other): removeVectorFile(vector_local_cut_other) if os.path.isfile(raster_local_cut): removeFile(raster_local_cut) if os.path.isfile(matrix_local_file): removeFile(matrix_local_file) return class_ref_list, class_pro_list, rate_quantity_list, kappa, overall_accuracy, matrix_origine
def postTraitementsRaster(image_input, image_output, vector_input, enable_cutting_ask, post_treatment_raster_dico, no_data_value, path_time_log, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", save_results_intermediate=False, overwrite=True): # Print if debug >= 3: print(bold + green + "Variables dans la fonction" + endC) print(cyan + "postTraitementsRaster() : " + endC + "image_input : " + str(image_input) + endC) print(cyan + "postTraitementsRaster() : " + endC + "image_output : " + str(image_output) + endC) print(cyan + "postTraitementsRaster() : " + endC + "vector_input : " + str(vector_input) + endC) print(cyan + "postTraitementsRaster() : " + endC + "enable_cutting_ask : " + str(enable_cutting_ask) + endC) print(cyan + "postTraitementsRaster() : " + endC + "post_treatment_raster_dico : " + str(post_treatment_raster_dico) + endC) print(cyan + "postTraitementsRaster() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "postTraitementsRaster() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "postTraitementsRaster() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "postTraitementsRaster() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "postTraitementsRaster() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "postTraitementsRaster() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "postTraitementsRaster() : " + endC + "overwrite : " + str(overwrite) + endC) # Mise à jour du Log starting_event = "postTraitementsRaster() : Past traitements raster starting : " timeLine(path_time_log, starting_event) # Constantes CODAGE = "uint16" FOLDER_TEMP = "TempPtRaster_" SUFFIX_TEMP = "_tmp" SUFFIX_MASK = '_mask' SUFFIX_DILATED = '_dilated' SUFFIX_TOAPPLY = '_to_apply' # ETAPE 1 : NETTOYAGE DES DONNEES EXISTANTES print(cyan + "postTraitementsRaster() : " + bold + green + "NETTOYAGE DE L ESPACE DE TRAVAIL..." + endC) # Nom de base de l'image image_name = os.path.splitext(os.path.basename(image_input))[0] # Nettoyage d'anciennes données résultat check = os.path.isfile(image_output) if check and not overwrite: # Si le fichier résultat existe deja et que overwrite n'est pas activéptrd print(bold + yellow + "postTraitementsRaster() : " + endC + image_output + " already exists and will not be calculated again." + endC) else: # Cas où le fichier résultat n'existe pas au lancement if check: # Si overwrite est activé try: removeFile(image_output) # Tentative de suppression du fichier except Exception: pass # Si le fichier ne peut pas être supprimé, on suppose qu'il n'existe pas et on passe à la suite # Définition des répertoires temporaires repertory_output = os.path.dirname( image_output) # Ex : D2_Par_Zone\Paysage_01\Corr_3\Resultats basename_output = os.path.splitext(os.path.basename(image_output))[ 0] # Ex : Paysage_01_merged_filtred_pt extension = os.path.splitext(image_output)[1] image_output_temp = repertory_output + os.sep + basename_output + SUFFIX_TEMP + extension # Ex : D2_Par_Zone\Paysage_01\Corr_3\Resultats\Paysage_01_merged_filtred_pt_tmp.tif repertory_temp = repertory_output + os.sep + FOLDER_TEMP + image_name # Ex : D2_Par_Zone\Paysage_01\Corr_3\Resultats\Temp_pt_raster if debug >= 3: print(cyan + "postTraitementsRaster() : " + endC + "repertory_temp : " + str(repertory_temp) + endC) # Creation du repertoire de sortie s'il n'existe pas if not os.path.isdir(repertory_output): os.makedirs(repertory_output) # Nettoyage et creation du fichier temporaire: cleanTempData(repertory_temp) print(cyan + "postTraitementsRaster() : " + bold + green + "... FIN NETTOYAGE" + endC) # ETAPE 2 : TRAITEMENTS nb_treatments = len(post_treatment_raster_dico) idx = 0 key_traitement_list = list(post_treatment_raster_dico.keys()) for key_traitement in sorted(key_traitement_list): # Noms des fichiers temporaires binary_mask = repertory_temp + os.sep + basename_output + SUFFIX_MASK + key_traitement + extension_raster # Ex : D2_Par_Zone\Paysage_01\Corr_3\Resultats\Temp_pt_raster\Paysage_01_merged_filtred_pt_mask.tif dilated_binary_mask = repertory_temp + os.sep + basename_output + SUFFIX_DILATED + SUFFIX_MASK + key_traitement + extension_raster # Ex : D2_Par_Zone\Paysage_01\Corr_3\Resultats\Temp_pt_raster\Paysage_01_merged_filtred_pt_dilated_mask.tif mask_to_apply = repertory_temp + os.sep + basename_output + SUFFIX_TOAPPLY + SUFFIX_MASK + key_traitement + extension_raster # Ex : D2_Par_Zone\Paysage_01\Corr_3\Resultats\Temp_pt_raster\Paysage_01_merged_filtred_pt_to_apply_mask.tif # Extraction des informations du dictionnaire treatement_info_list = post_treatment_raster_dico[key_traitement][ 0] image_to_use = treatement_info_list[0] threshold_min = float(treatement_info_list[1]) threshold_max = float(treatement_info_list[2]) buffer_to_apply = int(treatement_info_list[3]) in_or_out = treatement_info_list[4] class_to_replace = str(treatement_info_list[5]) if class_to_replace.lower() != "all": class_to_replace = int(class_to_replace) replacement_class = int(treatement_info_list[6]) # ETAPE 2-1 CREATION DU MASQUE BINAIRE if debug >= 2: print( cyan + "postTraitementsRaster() : " + bold + green + "TRAITEMENT %s/%s - Etape 1/4 : CREATION DU MASQUE BINAIRE POUR %s " % (str(idx + 1), str(nb_treatments), image_to_use) + endC) createBinaryMaskThreshold(image_to_use, binary_mask, threshold_min, threshold_max, CODAGE) # ETAPE 2-2 CREATION DU MASQUE DILATE if buffer_to_apply == 0: # Si le buffer est nul, alors on copie juste le masque binaire if debug >= 2: print( cyan + "postTraitementsRaster() : " + bold + green + "TRAITEMENT %s/%s - Etape 2/4 : CREATION PAR RENOMMAGE DU MASQUE DILATE POUR %s" % (str(idx + 1), str(nb_treatments), image_to_use) + endC) os.rename(binary_mask, dilated_binary_mask) else: if debug >= 2: print( cyan + "postTraitementsRaster() : " + bold + green + "TRAITEMENT %s/%s - Etape 2/4 : CREATION DU MASQUE DILATE POUR %s " % (str(idx + 1), str(nb_treatments), image_to_use) + endC) # Creation d'un mask binaire bufferisé bufferBinaryRaster(binary_mask, dilated_binary_mask, buffer_to_apply, CODAGE) if not save_results_intermediate: if debug >= 3: print( cyan + "postTraitementsRaster() : " + bold + green + "TRAITEMENT %s/%s - Etape 2/4 : SUPRESSION DE %s QUI NE SERVIRA PLUS" % (str(idx + 1), str(nb_treatments), binary_mask) + endC) # Suppression du masque binaire de base removeFile(binary_mask) # ETAPE 2-3 CREATION DU MASQUE COMPLEMENTAIRE if in_or_out.lower() == "in": if debug >= 2: print( cyan + "postTraitementsRaster() : " + bold + green + "TRAITEMENT %s/%s - Etape 3/4 : CREATION PAR RENOMMAGE DU MASQUE COMPLEMENTAIRE A APPLIQUER POUR %s" % (str(idx + 1), str(nb_treatments), image_to_use) + endC) os.rename(dilated_binary_mask, mask_to_apply) else: if debug >= 2: print( cyan + "postTraitementsRaster() : " + bold + green + "TRAITEMENT %s/%s - Etape 3/4 : CREATION DU MASQUE COMPLEMENTAIRE POUR %s" % (str(idx + 1), str(nb_treatments), image_to_use) + endC) # Creation d'un mask binaire negatif createBinaryMask(dilated_binary_mask, mask_to_apply, 0.5, False, CODAGE) if not save_results_intermediate: if debug >= 3: print( cyan + "postTraitementsRaster() : " + bold + green + "TRAITEMENT %s/%s - Etape 3/4 : SUPRESSION DE %s QUI NE SERVIRA PLUS" % (str(idx + 1), str(nb_treatments), dilated_binary_mask) + endC) # Suppression du masque dilate removeFile(dilated_binary_mask) # ETAPE 2-4 APPLICATION DU MASQUE if str(class_to_replace).lower() == "all": expression = "\"(im1b1 == 1 ? %d : im2b1)\"" % ( int(replacement_class)) else: expression = "\"(im1b1 == 1 ? ( im2b1 == %d ? %d : im2b1) : im2b1)\"" % ( class_to_replace, replacement_class) if nb_treatments <= 1: input_for_command = image_input output_for_command = image_output_temp elif idx == 0: input_for_command = image_input output_for_command = repertory_temp + os.sep + basename_output + str( idx + 1) + extension_raster elif idx == nb_treatments - 1: input_for_command = repertory_temp + os.sep + basename_output + str( idx) + extension_raster output_for_command = image_output_temp else: input_for_command = repertory_temp + os.sep + basename_output + str( idx) + extension_raster output_for_command = repertory_temp + os.sep + basename_output + str( idx + 1) + extension_raster command = "otbcli_BandMath -il %s %s -exp %s -out %s %s" % ( mask_to_apply, input_for_command, expression, output_for_command, CODAGE) if debug >= 2: print( cyan + "postTraitementsRaster() : " + bold + green + "TRAITEMENT %s/%s - Etape 4/4 : APPLICATION DU POST TRAITEMENT AVEC %s" % (str(idx + 1), str(nb_treatments), mask_to_apply) + endC) print(command) exitCode = os.system(command) if exitCode != 0: print(command) raise NameError( bold + red + "postTraitementsRaster() : An error occured during otbcli_BandMath command. See error message above." + endC) if not save_results_intermediate: if debug >= 3: print( cyan + "postTraitementsRaster() : " + bold + green + "TRAITEMENT %s/%s - Etape 4/4 : SUPRESSION DE %s QUI NE SERVIRA PLUS" % (str(idx + 1), str(nb_treatments), mask_to_apply) + endC) # Suppression du masque à appliquer removeFile(mask_to_apply) # mise a jour de l'index idx += 1 # ETAPE 5 : DECOUPAGE DU RASTER DE SORTIE if enable_cutting_ask: # Decoupe du raster if not cutImageByVector(vector_input, image_output_temp, image_output, None, None, no_data_value, 0, format_raster, format_vector): print( cyan + "postTraitementsRaster() : " + bold + red + "!!! Une erreur c'est produite au cours du decoupage de l'image : " + image_output_temp + ". Voir message d'erreur." + endC, file=sys.stderr) raise if debug >= 2: print( cyan + "postTraitementsRaster() : " + bold + green + "TRAITEMENT %s/%s - Etape 5 : REDECOUPAGE DU RASTER DE SORTIE AVEC LE VECTEUR %s" % (str(idx + 1), str(nb_treatments), vector_input) + endC) if not save_results_intermediate: # Suppression du fichier intermediaire removeFile(image_output_temp) else: # Pas de redécoupage du fichier raster de sortie demander le fichier est juste renomé shutil.move(image_output_temp, image_output) # ETAPE 6 : SUPPRESSION DES FICHIERS INTERMEDIAIRES # Suppression des données intermédiaires if not save_results_intermediate: if debug >= 2: print( cyan + "postTraitementsRaster() : " + bold + green + "TRAITEMENT %s/%s - SUPRESSION DES DONNEES INTERMEDIAIRE CONTENUES DANS : %s" % (str(idx + 1), str(nb_treatments), repertory_temp) + endC) # Suppression du repertoire temporaire deleteDir(repertory_temp) # Mise à jour du Log ending_event = "postTraitementsRaster() : Add data base exogene to classification ending : " timeLine(path_time_log, ending_event) return
def estimateQualityClassification(image_input, vector_cut_input, vector_sample_input, vector_output, nb_dot, no_data_value, column_name_vector, column_name_ref, column_name_class, path_time_log, epsg=2154, format_raster='GTiff', format_vector="ESRI Shapefile", extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True): # Mise à jour du Log starting_event = "estimateQualityClassification() : Masks creation starting : " timeLine(path_time_log, starting_event) print(endC) print(bold + green + "## START : CREATE PRINT POINTS FILE FROM CLASSIF IMAGE" + endC) print(endC) if debug >= 2: print(bold + green + "estimateQualityClassification() : Variables dans la fonction" + endC) print(cyan + "estimateQualityClassification() : " + endC + "image_input : " + str(image_input) + endC) print(cyan + "estimateQualityClassification() : " + endC + "vector_cut_input : " + str(vector_cut_input) + endC) print(cyan + "estimateQualityClassification() : " + endC + "vector_sample_input : " + str(vector_sample_input) + endC) print(cyan + "estimateQualityClassification() : " + endC + "vector_output : " + str(vector_output) + endC) print(cyan + "estimateQualityClassification() : " + endC + "nb_dot : " + str(nb_dot) + endC) print(cyan + "estimateQualityClassification() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "estimateQualityClassification() : " + endC + "column_name_vector : " + str(column_name_vector) + endC) print(cyan + "estimateQualityClassification() : " + endC + "column_name_ref : " + str(column_name_ref) + endC) print(cyan + "estimateQualityClassification() : " + endC + "column_name_class : " + str(column_name_class) + endC) print(cyan + "estimateQualityClassification() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "estimateQualityClassification() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "estimateQualityClassification() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "estimateQualityClassification() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "estimateQualityClassification() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "estimateQualityClassification() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + "estimateQualityClassification() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "estimateQualityClassification() : " + endC + "overwrite : " + str(overwrite) + endC) # ETAPE 0 : PREPARATION DES FICHIERS INTERMEDIAIRES CODAGE = "uint16" SUFFIX_STUDY = '_study' SUFFIX_CUT = '_cut' SUFFIX_TEMP = '_temp' SUFFIX_SAMPLE = '_sample' repertory_output = os.path.dirname(vector_output) base_name = os.path.splitext(os.path.basename(vector_output))[0] vector_output_temp = repertory_output + os.sep + base_name + SUFFIX_TEMP + extension_vector raster_study = repertory_output + os.sep + base_name + SUFFIX_STUDY + extension_raster vector_study = repertory_output + os.sep + base_name + SUFFIX_STUDY + extension_vector raster_cut = repertory_output + os.sep + base_name + SUFFIX_CUT + extension_raster vector_sample_temp = repertory_output + os.sep + base_name + SUFFIX_SAMPLE + SUFFIX_TEMP + extension_vector # Mise à jour des noms de champs input_ref_col = "" val_ref = 0 if (column_name_vector != "") and (not column_name_vector is None): input_ref_col = column_name_vector if (column_name_ref != "") and (not column_name_ref is None): val_ref_col = column_name_ref if (column_name_class != "") and (not column_name_class is None): val_class_col = column_name_class # ETAPE 1 : DEFINIR UN SHAPE ZONE D'ETUDE if (not vector_cut_input is None) and (vector_cut_input != "") and ( os.path.isfile(vector_cut_input)): cutting_action = True vector_study = vector_cut_input else: cutting_action = False createVectorMask(image_input, vector_study) # ETAPE 2 : DECOUPAGE DU RASTEUR PAR LE VECTEUR D'EMPRISE SI BESOIN if cutting_action: # Identification de la tailles de pixels en x et en y pixel_size_x, pixel_size_y = getPixelWidthXYImage(image_input) # Si le fichier de sortie existe deja le supprimer if os.path.exists(raster_cut): removeFile(raster_cut) # Commande de découpe if not cutImageByVector(vector_study, image_input, raster_cut, pixel_size_x, pixel_size_y, no_data_value, 0, format_raster, format_vector): raise NameError( cyan + "estimateQualityClassification() : " + bold + red + "Une erreur c'est produite au cours du decoupage de l'image : " + image_input + endC) if debug >= 2: print(cyan + "estimateQualityClassification() : " + bold + green + "DECOUPAGE DU RASTER %s AVEC LE VECTEUR %s" % (image_input, vector_study) + endC) else: raster_cut = image_input # ETAPE 3 : CREATION DE LISTE POINTS AVEC DONNEE ISSU D'UN FICHIER RASTER # Gémotrie de l'image cols, rows, bands = getGeometryImage(raster_cut) xmin, xmax, ymin, ymax = getEmpriseImage(raster_cut) pixel_width, pixel_height = getPixelWidthXYImage(raster_cut) if debug >= 2: print("cols : " + str(cols)) print("rows : " + str(rows)) print("bands : " + str(bands)) print("xmin : " + str(xmin)) print("ymin : " + str(ymin)) print("xmax : " + str(xmax)) print("ymax : " + str(ymax)) print("pixel_width : " + str(pixel_width)) print("pixel_height : " + str(pixel_height)) # ETAPE 3-1 : CAS CREATION D'UN FICHIER DE POINTS PAR TIRAGE ALEATOIRE DANS LA MATRICE IMAGE if (vector_sample_input is None) or (vector_sample_input == ""): is_sample_file = False # Les dimensions de l'image nb_pixels = abs(cols * rows) # Tirage aléatoire des points drawn_dot_list = [] while len(drawn_dot_list) < nb_dot: val = random.randint(0, nb_pixels) if not val in drawn_dot_list: drawn_dot_list.append(val) # Creation d'un dico index valeur du tirage et attibuts pos_x, pos_y et value pixel points_random_value_dico = {} points_coordonnees_list = [] for point in drawn_dot_list: pos_y = point // cols pos_x = point % cols coordonnees_list = [pos_x, pos_y] points_coordonnees_list.append(coordonnees_list) # Lecture dans le fichier raster des valeurs values_list = getPixelsValueListImage(raster_cut, points_coordonnees_list) print(values_list) for idx_point in range(len(drawn_dot_list)): val_class = values_list[idx_point] coordonnees_list = points_coordonnees_list[idx_point] pos_x = coordonnees_list[0] pos_y = coordonnees_list[1] coor_x = xmin + (pos_x * abs(pixel_width)) coor_y = ymax - (pos_y * abs(pixel_height)) point_attr_dico = { "Ident": idx_point, val_ref_col: int(val_ref), val_class_col: int(val_class) } points_random_value_dico[idx_point] = [[coor_x, coor_y], point_attr_dico] if debug >= 4: print("idx_point : " + str(idx_point)) print("pos_x : " + str(pos_x)) print("pos_y : " + str(pos_y)) print("coor_x : " + str(coor_x)) print("coor_y : " + str(coor_y)) print("val_class : " + str(val_class)) print("") # ETAPE 3-2 : CAS D'UN FICHIER DE POINTS DEJA EXISTANT MISE A JOUR DE LA DONNEE ISSU Du RASTER else: # Le fichier de points d'analyses existe is_sample_file = True cutVectorAll(vector_study, vector_sample_input, vector_sample_temp, format_vector) if input_ref_col != "": points_coordinates_dico = readVectorFilePoints( vector_sample_temp, [input_ref_col], format_vector) else: points_coordinates_dico = readVectorFilePoints( vector_sample_temp, [], format_vector) # Création du dico points_random_value_dico = {} points_coordonnees_list = [] for index_key in points_coordinates_dico: # Recuperer les valeurs des coordonnees coord_info_list = points_coordinates_dico[index_key] coor_x = coord_info_list[0] coor_y = coord_info_list[1] pos_x = int(round((coor_x - xmin) / abs(pixel_width))) pos_y = int(round((ymax - coor_y) / abs(pixel_height))) coordonnees_list = [pos_x, pos_y] points_coordonnees_list.append(coordonnees_list) # Lecture dans le fichier raster des valeurs values_list = getPixelsValueListImage(raster_cut, points_coordonnees_list) for index_key in points_coordinates_dico: # Récuperer les valeurs des coordonnees coord_info_list = points_coordinates_dico[index_key] coor_x = coord_info_list[0] coor_y = coord_info_list[1] # Récupérer la classe de référence dans le vecteur d'entrée if input_ref_col != "": label = coord_info_list[2] val_ref = label.get(input_ref_col) # Récupérer la classe issue du raster d'entrée val_class = values_list[index_key] # Création du dico contenant identifiant du point, valeur de référence, valeur du raster d'entrée point_attr_dico = { "Ident": index_key, val_ref_col: int(val_ref), val_class_col: int(val_class) } if debug >= 4: print("point_attr_dico: " + str(point_attr_dico)) points_random_value_dico[index_key] = [[coor_x, coor_y], point_attr_dico] # ETAPE 4 : CREATION ET DECOUPAGE DU FICHIER VECTEUR RESULTAT PAR LE SHAPE D'ETUDE # Creer le fichier de points if is_sample_file and os.path.exists(vector_sample_temp): attribute_dico = {val_class_col: ogr.OFTInteger} # Recopie du fichier removeVectorFile(vector_output_temp) copyVectorFile(vector_sample_temp, vector_output_temp) # Ajout des champs au fichier de sortie for field_name in attribute_dico: addNewFieldVector(vector_output_temp, field_name, attribute_dico[field_name], 0, None, None, format_vector) # Préparation des donnees field_new_values_list = [] for index_key in points_random_value_dico: point_attr_dico = points_random_value_dico[index_key][1] point_attr_dico.pop(val_ref_col, None) field_new_values_list.append(point_attr_dico) # Ajout des donnees setAttributeValuesList(vector_output_temp, field_new_values_list, format_vector) else: # Définir les attibuts du fichier résultat attribute_dico = { "Ident": ogr.OFTInteger, val_ref_col: ogr.OFTInteger, val_class_col: ogr.OFTInteger } createPointsFromCoordList(attribute_dico, points_random_value_dico, vector_output_temp, epsg, format_vector) # Découpage du fichier de points d'echantillons cutVectorAll(vector_study, vector_output_temp, vector_output, format_vector) # ETAPE 5 : SUPPRESIONS FICHIERS INTERMEDIAIRES INUTILES # Suppression des données intermédiaires if not save_results_intermediate: if cutting_action: removeFile(raster_cut) else: removeVectorFile(vector_study) removeFile(raster_study) if is_sample_file: removeVectorFile(vector_sample_temp) removeVectorFile(vector_output_temp) print(endC) print(bold + green + "## END : CREATE PRINT POINTS FILE FROM CLASSIF IMAGE" + endC) print(endC) # Mise à jour du Log ending_event = "estimateQualityClassification() : Masks creation ending : " timeLine(path_time_log, ending_event) return
def skyViewFactor(grid_input, grid_output, mns_input, classif_input, class_build_list, dim_grid_x, dim_grid_y, svf_radius, svf_method, svf_dlevel, svf_ndirs, epsg, no_data_value, path_time_log, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True): print(bold + yellow + "Début du calcul de l'indicateur Sky View Factor." + endC + "\n") timeLine(path_time_log, "Début du calcul de l'indicateur Sky View Factor : ") if debug >= 3: print(bold + green + "skyViewFactor() : Variables dans la fonction" + endC) print(cyan + "skyViewFactor() : " + endC + "grid_input : " + str(grid_input) + endC) print(cyan + "skyViewFactor() : " + endC + "grid_output : " + str(grid_output) + endC) print(cyan + "skyViewFactor() : " + endC + "mns_input : " + str(mns_input) + endC) print(cyan + "skyViewFactor() : " + endC + "class_build_list : " + str(class_build_list) + endC) print(cyan + "skyViewFactor() : " + endC + "classif_input : " + str(classif_input) + endC) print(cyan + "skyViewFactor() : " + endC + "dim_grid_x : " + str(dim_grid_x) + endC) print(cyan + "skyViewFactor() : " + endC + "dim_grid_y : " + str(dim_grid_y) + endC) print(cyan + "skyViewFactor() : " + endC + "svf_radius : " + str(svf_radius) + endC) print(cyan + "skyViewFactor() : " + endC + "svf_method : " + str(svf_method) + endC) print(cyan + "skyViewFactor() : " + endC + "svf_dlevel : " + str(svf_dlevel) + endC) print(cyan + "skyViewFactor() : " + endC + "svf_ndirs : " + str(svf_ndirs) + endC) print(cyan + "skyViewFactor() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "skyViewFactor() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "skyViewFactor() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "skyViewFactor() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "skyViewFactor() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "skyViewFactor() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "skyViewFactor() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + "skyViewFactor() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "skyViewFactor() : " + endC + "overwrite : " + str(overwrite) + endC) # Constantes liées aux fichiers SKY_VIEW_FIELD = 'SkyView' BASE_FILE_TILE = 'tile_' BASE_FILE_POLY = 'poly_' SUFFIX_VECTOR_BUFF = '_buff' SUFFIX_VECTOR_TEMP = '_temp' # Constantes liées à l'arborescence FOLDER_SHP = 'SHP' FOLDER_SGRD = 'SGRD' FOLDER_TIF = 'TIF' SUB_FOLDER_DEM = 'DEM' SUB_FOLDER_SVF = 'SVF' SUB_SUB_FOLDER_BUF = 'BUF' if not os.path.exists(grid_output) or overwrite: ############################################ ### Préparation générale des traitements ### ############################################ if os.path.exists(grid_output): removeVectorFile(grid_output) temp_path = os.path.dirname(grid_output) + os.sep + "SkyViewFactor" sky_view_factor_raster = temp_path + os.sep + "sky_view_factor" + extension_raster cleanTempData(temp_path) os.makedirs(temp_path + os.sep + FOLDER_SHP) os.makedirs(temp_path + os.sep + FOLDER_SGRD + os.sep + SUB_FOLDER_DEM) os.makedirs(temp_path + os.sep + FOLDER_SGRD + os.sep + SUB_FOLDER_SVF) os.makedirs(temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_DEM) os.makedirs(temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF) os.makedirs(temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF + os.sep + SUB_SUB_FOLDER_BUF) # Récupération de la résolution du raster d'entrée pixel_size_x, pixel_size_y = getPixelWidthXYImage(mns_input) print(bold + "Taille de pixel du fichier '%s' :" % (mns_input) + endC) print(" pixel_size_x = " + str(pixel_size_x)) print(" pixel_size_y = " + str(pixel_size_y) + "\n") ############################################### ### Création des fichiers emprise et grille ### ############################################### print(bold + cyan + "Création des fichiers emprise et grille :" + endC) timeLine(path_time_log, " Création des fichiers emprise et grille : ") emprise_file = temp_path + os.sep + "emprise" + extension_vector quadrillage_file = temp_path + os.sep + "quadrillage" + extension_vector # Création du fichier d'emprise createVectorMask(mns_input, emprise_file, no_data_value, format_vector) # Création du fichier grille createGridVector(emprise_file, quadrillage_file, dim_grid_x, dim_grid_y, None, overwrite, epsg, format_vector) ############################################################# ### Extraction des carreaux de découpage et bufferisation ### ############################################################# print(bold + cyan + "Extraction des carreaux de découpage :" + endC) timeLine(path_time_log, " Extraction des carreaux de découpage : ") split_tile_vector_list = splitVector(quadrillage_file, temp_path + os.sep + FOLDER_SHP, "", epsg, format_vector, extension_vector) split_tile_vector_buff_list = [] # Boucle sur les fichiers polygones quadrillage for split_tile_vector in split_tile_vector_list: repertory_temp_output = os.path.dirname(split_tile_vector) base_name = os.path.splitext( os.path.basename(split_tile_vector))[0] split_tile_buff_vector = repertory_temp_output + os.sep + base_name + SUFFIX_VECTOR_BUFF + extension_vector split_tile_buff_vector_temp = repertory_temp_output + os.sep + base_name + SUFFIX_VECTOR_BUFF + SUFFIX_VECTOR_TEMP + extension_vector # Bufferisation bufferVector(split_tile_vector, split_tile_buff_vector_temp, svf_radius, "", 1.0, 10, format_vector) # Re-découpage avec l'emprise si la taille intersecte avec l'emprise if cutVector(emprise_file, split_tile_buff_vector_temp, split_tile_buff_vector, overwrite, format_vector): split_tile_vector_buff_list.append(split_tile_buff_vector) ########################################################## ### Découpage du MNS/MNH à l'emprise de chaque carreau ### ########################################################## print(bold + cyan + "Découpage du raster en tuiles :" + endC) timeLine(path_time_log, " Découpage du raster en tuiles : ") # Boucle sur les fichiers polygones quadrillage bufferisés for i in range(len(split_tile_vector_list)): print("Traitement de la tuile " + str(int(i) + 1) + str(len(split_tile_vector_list)) + "...") split_tile_vector = split_tile_vector_list[i] repertory_temp_output = os.path.dirname(split_tile_vector) base_name = os.path.splitext( os.path.basename(split_tile_vector))[0] split_tile_buff_vector = repertory_temp_output + os.sep + base_name + SUFFIX_VECTOR_BUFF + extension_vector dem_tif_file = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_DEM + os.sep + BASE_FILE_TILE + str( i) + extension_raster if os.path.exists(split_tile_buff_vector): cutImageByVector(split_tile_buff_vector, mns_input, dem_tif_file, pixel_size_x, pixel_size_y, no_data_value, epsg, format_raster, format_vector) ################################################## ### Calcul du SVF pour chaque dalle du MNS/MNH ### ################################################## print(bold + cyan + "Calcul du SVF pour chaque tuile via SAGA :" + endC) timeLine(path_time_log, " Calcul du SVF pour chaque tuile via SAGA : ") svf_buf_tif_file_list = [] # Boucle sur les tuiles du raster d'entrée créées par chaque polygone quadrillage for i in range(len(split_tile_vector_list)): # Calcul de Sky View Factor par SAGA dem_tif_file = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_DEM + os.sep + BASE_FILE_TILE + str( i) + extension_raster svf_buf_tif_file = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF + os.sep + SUB_SUB_FOLDER_BUF + os.sep + BASE_FILE_TILE + str( i) + extension_raster if os.path.exists(dem_tif_file): computeSkyViewFactor(dem_tif_file, svf_buf_tif_file, svf_radius, svf_method, svf_dlevel, svf_ndirs, save_results_intermediate) svf_buf_tif_file_list.append(svf_buf_tif_file) ################################################################### ### Re-découpage des tuiles du SVF avec les tuilles sans tampon ### ################################################################### print(bold + cyan + "Re-découpage des tuiles du SVF avec les tuilles sans tampon :" + endC) timeLine( path_time_log, " Re-découpage des tuiles du SVF avec les tuilles sans tampon : " ) folder_output_svf = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF + os.sep # Boucle sur les tuiles du SVF bufferisées for i in range(len(split_tile_vector_list)): print("Traitement de la tuile " + str(int(i) + 1) + "/" + str(len(split_tile_vector_list)) + "...") split_tile_vector = split_tile_vector_list[i] svf_buf_tif_file = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF + os.sep + SUB_SUB_FOLDER_BUF + os.sep + BASE_FILE_TILE + str( i) + extension_raster base_name = os.path.splitext(os.path.basename(svf_buf_tif_file))[0] svf_tif_file = folder_output_svf + os.sep + base_name + extension_raster if os.path.exists(svf_buf_tif_file): cutImageByVector(split_tile_vector, svf_buf_tif_file, svf_tif_file, pixel_size_x, pixel_size_y, no_data_value, epsg, format_raster, format_vector) #################################################################### ### Assemblage des tuiles du SVF et calcul de l'indicateur final ### #################################################################### print( bold + cyan + "Assemblage des tuiles du SVF et calcul de l'indicateur final :" + endC) timeLine( path_time_log, " Assemblage des tuiles du SVF et calcul de l'indicateur final : " ) classif_input_temp = temp_path + os.sep + FOLDER_TIF + os.sep + "classif_input" + SUFFIX_VECTOR_TEMP + extension_raster sky_view_factor_temp = temp_path + os.sep + FOLDER_TIF + os.sep + "sky_view_factor" + SUFFIX_VECTOR_TEMP + extension_raster # Issu de l'assemblage des dalles sky_view_factor_temp_temp = temp_path + os.sep + FOLDER_TIF + os.sep + "sky_view_factor" + SUFFIX_VECTOR_TEMP + SUFFIX_VECTOR_TEMP + extension_raster # Issu du redécoupage pour entrer correctement dans le BandMath sky_view_factor_temp_temp_temp = temp_path + os.sep + FOLDER_TIF + os.sep + "sky_view_factor" + SUFFIX_VECTOR_TEMP + SUFFIX_VECTOR_TEMP + SUFFIX_VECTOR_TEMP + extension_raster # Issu de la suppression des pixels bâti # Assemblage des tuiles du SVF créées précédemment pour ne former qu'un seul raster SVF selectAssembyImagesByHold( emprise_file, [folder_output_svf], sky_view_factor_temp, False, False, epsg, False, False, False, False, 1.0, pixel_size_x, pixel_size_y, no_data_value, "_", 2, 8, "", path_time_log, "_error", "_merge", "_clean", "_stack", format_raster, format_vector, extension_raster, extension_vector, save_results_intermediate, overwrite) # Suppression des valeurs de SVF pour les bâtiments cutImageByVector(emprise_file, classif_input, classif_input_temp, pixel_size_x, pixel_size_y, no_data_value, epsg, format_raster, format_vector) cutImageByVector(emprise_file, sky_view_factor_temp, sky_view_factor_temp_temp, pixel_size_x, pixel_size_y, no_data_value, epsg, format_raster, format_vector) expression = "" for id_class in class_build_list: expression += "im1b1==%s or " % (str(id_class)) expression = expression[:-4] command = "otbcli_BandMath -il %s %s -out %s float -exp '%s ? -1 : im2b1'" % ( classif_input_temp, sky_view_factor_temp_temp, sky_view_factor_temp_temp_temp, expression) if debug >= 3: print(command) exit_code = os.system(command) if exit_code != 0: print(command) print( cyan + "skyViewFactor() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise command = "gdal_translate -a_srs EPSG:%s -a_nodata %s -of %s %s %s" % ( str(epsg), str(no_data_value), format_raster, sky_view_factor_temp_temp_temp, sky_view_factor_raster) if debug >= 3: print(command) exit_code = os.system(command) if exit_code != 0: print(command) print( cyan + "skyViewFactor() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande gdal_translate : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise # Croisement vecteur-raster pour récupérer la moyenne de SVF par polygone du fichier maillage d'entrée col_to_delete_list = [ "min", "max", "median", "sum", "std", "unique", "range" ] statisticsVectorRaster( sky_view_factor_raster, grid_input, grid_output, 1, False, False, True, col_to_delete_list, [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite ) ## Erreur NaN pour polygones entièrement bâtis (soucis pour la suite ?) renameFieldsVector(grid_output, ['mean'], [SKY_VIEW_FIELD], format_vector) ########################################## ### Nettoyage des fichiers temporaires ### ########################################## if not save_results_intermediate: deleteDir(temp_path) else: print(bold + magenta + "Le calcul du Sky View Factor a déjà eu lieu." + endC + "\n") print(bold + yellow + "Fin du calcul de l'indicateur Sky View Factor." + endC + "\n") timeLine(path_time_log, "Fin du calcul de l'indicateur Sky View Factor : ") return
def sobelToOuvrages(input_im_seuils_dico, output_dir, input_cut_vector, no_data_value, path_time_log, format_raster='GTiff', format_vector="ESRI Shapefile", extension_raster=".tif", extension_vector=".shp", save_results_intermediate=True, overwrite=True): # Constantes REPERTORY_TEMP = "temp_sobel" CODAGE_8B = "uint8" ID = "id" # Mise à jour du Log starting_event = "sobelToOuvrages() : Select Sobel to ouvrages starting : " timeLine(path_time_log,starting_event) # Création du répertoire de sortie s'il n'existe pas déjà if not os.path.exists(output_dir + os.sep + REPERTORY_TEMP): os.makedirs(output_dir + os.sep + REPERTORY_TEMP) # Affichage des paramètres if debug >= 3: print(bold + green + "Variables dans SobelToOuvrages - Variables générales" + endC) print(cyan + "sobelToOuvrages() : " + endC + "input_im_seuils_dico : " + str(input_im_seuils_dico) + endC) print(cyan + "sobelToOuvrages() : " + endC + "output_dir : " + str(output_dir) + endC) print(cyan + "sobelToOuvrages() : " + endC + "input_cut_vector : " + str(input_cut_vector) + endC) print(cyan + "sobelToOuvrages() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "sobelToOuvrages() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "sobelToOuvrages() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "sobelToOuvrages() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "sobelToOuvrages() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + "sobelToOuvrages() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "sobelToOuvrages() : " + endC + "overwrite : " + str(overwrite) + endC) sobel_ouvrages_shp_list = [] for elt in input_im_seuils_dico.split(): raw_image = elt.split(":")[0] sobel_image = elt.split(":")[1].split(",")[0] for i in range(1,len(elt.split(":")[1].split(","))): seuil = elt.split(":")[1].split(",")[i] # Initialisation des noms des fichiers en sortie image_name = os.path.splitext(os.path.basename(raw_image))[0] sobel_binary_mask = output_dir + os.sep + REPERTORY_TEMP + os.sep + "bin_mask_sobel_" + image_name + "_" + str(seuil) + extension_raster sobel_binary_mask_vector_name = "bin_mask_vect_sobel_" + image_name + "_" + str(seuil) sobel_binary_mask_vector = output_dir + os.sep + REPERTORY_TEMP + os.sep + sobel_binary_mask_vector_name + extension_vector sobel_binary_mask_vector_cleaned = output_dir + os.sep + REPERTORY_TEMP + os.sep + "bin_mask_vect_sobel_cleaned_" + image_name + "_" + str(seuil) + extension_vector sobel_decoup = output_dir + os.sep + "sobel_decoup_" + image_name + "_" + str(seuil) + extension_vector binary_mask_zeros_name = "b_mask_zeros_vect_" + image_name binary_mask_zeros_raster = output_dir + os.sep + REPERTORY_TEMP + os.sep + "b_mask_zeros_" + image_name + extension_raster binary_mask_zeros_vector = output_dir + os.sep + REPERTORY_TEMP + os.sep + binary_mask_zeros_name + extension_vector binary_mask_zeros_vector_simpl = output_dir + os.sep + REPERTORY_TEMP + os.sep + "b_mask_zeros_vect_simpl_" + image_name + extension_vector true_values_buffneg = output_dir + os.sep + REPERTORY_TEMP + os.sep + "true_values_buffneg_" + image_name + extension_vector ouvrages_decoup_final = output_dir + os.sep + "ouvrages_sobel_" + image_name + "_" + str(seuil) + extension_vector # Création du masque binaire createBinaryMask(sobel_image, sobel_binary_mask, float(seuil), True) # Découpe du masque binaire par le shapefile de découpe en entrée cutImageByVector(input_cut_vector, sobel_binary_mask, sobel_decoup, None, None, no_data_value, 0, format_raster, format_vector) # Vectorisation du masque binaire Sobel découpé polygonizeRaster(sobel_decoup, sobel_binary_mask_vector, sobel_binary_mask_vector_name) # Création masque binaire pour séparer les no data des vraies valeurs nodata_value = getNodataValueImage(raw_image) if no_data_value == None : no_data_value = 0 createBinaryMaskMultiBand(raw_image, binary_mask_zeros_raster, no_data_value, CODAGE_8B) # Vectorisation du masque binaire true data/false data -> polygone avec uniquement les vraies valeurs if os.path.exists(binary_mask_zeros_vector): removeVectorFile(binary_mask_zeros_vector, format_vector) # Polygonisation polygonizeRaster(binary_mask_zeros_raster, binary_mask_zeros_vector, binary_mask_zeros_name, ID, format_vector) # Simplification du masque obtenu simplifyVector(binary_mask_zeros_vector, binary_mask_zeros_vector_simpl, 2, format_vector) # Buffer négatif sur ce polygone bufferVector(binary_mask_zeros_vector_simpl, true_values_buffneg, -2, "", 1.0, 10, format_vector) cleanMiniAreaPolygons(sobel_binary_mask_vector, sobel_binary_mask_vector_cleaned, 15, ID, format_vector) # Découpe par le buffer négatif autour des true data cutVectorAll(true_values_buffneg, sobel_binary_mask_vector_cleaned, ouvrages_decoup_final, overwrite, format_vector) sobel_ouvrages_shp_list.append(ouvrages_decoup_final) return sobel_ouvrages_shp_list