def computeAreaMicro(repertory_output, table_input_name, data_base_name, micro): sql_temporary_file = repertory_output + os.sep + "spatialiteTemp.txt" requete = sqlSurfaceMicro(table_input_name, "ID", micro, data_base_name) exitCode = os.system("%s > %s"%(requete,sql_temporary_file)) if exitCode != 0: raise NameError(cyan + "computeAreaMicro() : " + bold + red + "An error occured during fileCreation command. See error message above." + endC) # Calculer la surface de la microclasse area_micro = float(readTextFileBySeparator(sql_temporary_file, " ")[0][0]) removeFile(sql_temporary_file) return area_micro
def readQualityIndicatorsFile(indicators_input_file) : print(cyan + "readQualityIndicatorsFile() : " + bold + green + "Indicators quality file reading... \n" + endC) # creer un dictionaire contenant tous les indicateurs de classes et un dictionaire des indicateurs généraux contenu dans le fichier indicator_macro_dico = [] indicator_general_dico = {} indicator_general_label = [] indicator_general_value = [] indicators_list = [] composants_list = readTextFileBySeparator(indicators_input_file, ";") for idx_line in range(len(composants_list)) : composant = composants_list[idx_line] # cas des indicateurs pour chaque macro classes if idx_line < len(composants_list)-2 : if debug >= 4: print(composant) if idx_line == 0 : line_zero_list = composant for id_elem in range(1, len(line_zero_list)): class_elm = cleanSpaceText(line_zero_list[id_elem]) class_dico = {} class_dico[cleanSpaceText(line_zero_list[0])] = class_elm indicator_macro_dico.append(class_dico) else : line_list = composant for id_elem in range(1, len(line_list)): indic_elm = cleanSpaceText(line_list[id_elem]) indicator_macro_dico[id_elem-1][cleanSpaceText(line_list[0])] = indic_elm # liste (labels) des indicateurs generaux elif idx_line == len(composants_list)-1 : if debug >= 4: print(composant) for elem in composant : indicator_general_value.append(cleanSpaceText(elem)) # Valeurs des indicateurs generaux else : if debug >= 4: print(composant) for elem in composant : indicator_general_label.append(cleanSpaceText(elem)) # creation dico indicateurs generaux for indicator_idx in range(len(indicator_general_label)) : indicator_general_dico[indicator_general_label[indicator_idx]] = indicator_general_value[indicator_idx] print(cyan + "readQualityIndicatorsFile() : " + bold + green + "Indicators quality file readed \n" + endC) # retourne les deux dictionaires return indicator_macro_dico,indicator_general_dico
def readCentroidsFiles(centroids_input_files_list) : print(cyan + "readCentroidsFile() : " + bold + green + "Centroids file reading...\n" + endC) microclass_centroides_list = [] for centroids_file in centroids_input_files_list: if debug >= 4: print("file centroides : " + centroids_file) composants_list = readTextFileBySeparator(centroids_file, " ") microclass_centroides_list.append(composants_list) for composant in composants_list : if debug >= 4: print(composant) print(cyan + "readCentroidsFile() : " + bold + green + "Centroids file readed \n" + endC) return microclass_centroides_list
def relaunchFtp(ftp, file_error, local_path): files_list = readTextFileBySeparator(file_error, '\n') for files in files_list: file_ftp = files[0] repertory = os.path.dirname(file_ftp) filename = os.path.basename(file_ftp) local_filename = local_path + os.sep + file_ftp print(cyan + "relaunchFtp() : " + endC + "Tentative de re-chargement de image file : " + file_ftp + endC) try: ftp.cwd(repertory) ftp.retrbinary("RETR " + filename ,open(local_filename, 'wb').write) ftp.cwd("/") except RuntimeError: print(cyan + "relaunchFtp() : " + bold + red + "Rechargement impossible du fichier : " + file_ftp + endC, file=sys.stderr) continue return
def computeAverageAreaMacro(repertory_output, class_labels_list, table_input_name, data_base_name): average_area_macro_list = [] sql_temporary_file = repertory_output + os.sep + "spatialiteTemp.txt" for class_label in class_labels_list: requete = sqlSurfaceAverageMacro(table_input_name, "ID", class_label, data_base_name) exitCode = os.system("%s > %s"%(requete,sql_temporary_file)) if exitCode != 0: raise NameError(cyan + "computeAverageAreaMacro() : " + bold + red + "An error occured during file creation. See error message above." + endC) requete_result = readTextFileBySeparator(sql_temporary_file, " ") print(requete_result) if requete_result == []: average_area_macro_list.append(0) else: average_area_macro_list.append(float(requete_result[0][0])) removeFile(sql_temporary_file) return average_area_macro_list
def classRasterSubSampling(satellite_image_input, classified_image_input, image_output, table_reallocation, sub_sampling_number, no_data_value, path_time_log, rand_otb=0, ram_otb=0, number_of_actives_pixels_threshold=8000, extension_raster=".tif", save_results_intermediate=False, overwrite=True) : # Mise à jour du Log starting_event = "classRasterSubSampling() : Micro class subsampling on classification image starting : " timeLine(path_time_log,starting_event) if debug >= 3: print(cyan + "classRasterSubSampling() : " + endC + "satellite_image_input : " + str(satellite_image_input) + endC) print(cyan + "classRasterSubSampling() : " + endC + "classified_image_input : " + str(classified_image_input) + endC) print(cyan + "classRasterSubSampling() : " + endC + "image_output : " + str(image_output) + endC) print(cyan + "classRasterSubSampling() : " + endC + "table_reallocation : " + str(table_reallocation) + endC) print(cyan + "classRasterSubSampling() : " + endC + "sub_sampling_number : " + str(sub_sampling_number) + endC) print(cyan + "classRasterSubSampling() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "classRasterSubSampling() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "classRasterSubSampling() : " + endC + "rand_otb : " + str(rand_otb) + endC) print(cyan + "classRasterSubSampling() : " + endC + "ram_otb : " + str(ram_otb) + endC) print(cyan + "classRasterSubSampling() : " + endC + "number_of_actives_pixels_threshold : " + str(number_of_actives_pixels_threshold) + endC) print(cyan + "classRasterSubSampling() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "classRasterSubSampling() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "classRasterSubSampling() : " + endC + "overwrite : " + str(overwrite) + endC) # Constantes CODAGE = "uint16" CODAGE_8B = "uint8" TEMP = "TempSubSampling_" MASK_SUF = "_Mask" SUB_SAMPLE_SUF = "_SubSampled" CENTROID_SUF = "_Centroids" TEMP_OUT = "_temp_out" EXTENSION_TXT = ".txt" # Contenu de la nouvelle table text_new_table = "" # CREATION DES NOMS DE CHEMINS UTILES name = os.path.splitext(os.path.basename(image_output))[0] input_classified_image_path = os.path.dirname(classified_image_input) # Ex : D2_Par_Zone/Paysage_01/Corr_2/Resultats/Temp/ temp_sub_sampling_path = input_classified_image_path + os.sep + TEMP + name + os.sep # Dossier contenant les fichiers temporaires de cette brique. Ex : D2_Par_Zone/Paysage_01/Corr_2/Resultats/Temp/Temp_Sub_Sampling/ input_classified_image_complete_name = os.path.basename(classified_image_input) # Ex : Paysage_01_raw.tif input_classified_image_name = os.path.splitext(input_classified_image_complete_name)[0] # Ex : Paysage_01_raw input_classified_image_extend = os.path.splitext(input_classified_image_complete_name)[1] # Ex : .tif image_output_temp = os.path.splitext(image_output)[0] + TEMP_OUT + extension_raster # Ex : D2_Par_Zone/Paysage_01/Corr_2/Resultats/Temp/Temp_Sub_Sampling/Paysage_01_raw_temp.tif # Création de temp_sub_sampling_path s'il n'existe pas if not os.path.isdir(os.path.dirname(temp_sub_sampling_path)) : os.makedirs(os.path.dirname(temp_sub_sampling_path)) print(cyan + "classRasterSubSampling() : " + bold + green + "START ...\n" + endC) # Lecture du fichier table de proposition supp_class_list, reaff_class_list, macro_reaff_class_list, sub_sampling_class_list, sub_sampling_number_list = readReallocationTable(table_reallocation, sub_sampling_number) # Fonction de Lib_text info_table_list = readTextFileBySeparator(table_reallocation, "\n") # Recherche de la liste des micro classes contenu dans le fichier de classification d'entrée class_values_list = identifyPixelValues(classified_image_input) # Supression dans la table des lignes correspondant aux actions "-2" for ligne_table in info_table_list: if not "-2" in ligne_table[0]: text_new_table += str(ligne_table[0]) + "\n" if debug >= 3: print("supp_class_list : " + str(supp_class_list)) print("reaff_class_list : " + str(reaff_class_list)) print("macro_reaff_class_list : " + str(macro_reaff_class_list)) print("sub_sampling_class_list : " + str(sub_sampling_class_list)) print("sub_sampling_number_list : " + str(sub_sampling_number_list)) # Dans cettre brique, on ne s'intéresse qu'à la partie sous echantillonage # Gestion du cas de suppression if len(supp_class_list) > 0: print(cyan + "classRasterSubSampling() : " + bold + yellow + "ATTENTION : Les classes ne sont pas supprimees pour le fichier classification format raster." + '\n' + endC) # Gestion du cas de réaffectation if len(reaff_class_list) > 0: print(cyan + "classRasterSubSampling() : " + bold + yellow + "ATTENTION : la brique SpecificSubSampling ne traite pas les reaffectation. A l'issue de cette brique, verifier la table de reallocation et executer la brique de reallocation." + '\n' + endC) if len(sub_sampling_class_list) > 0 : if debug >= 3: print(cyan + "classRasterSubSampling() : " + bold + green + "DEBUT DU SOUS ECHANTILLONAGE DES CLASSES %s " %(sub_sampling_class_list) + endC) # Parcours des classes à sous échantilloner processing_pass_first = False for idx_class in range(len(sub_sampling_class_list)) : # INITIALISATION DU TRAITEMENT DE LA CLASSE # Classe à sous échantilloner. Ex : 21008 class_to_sub_sample = sub_sampling_class_list[idx_class] if idx_class == 0 or not processing_pass_first : # Image à reclassifier : classified_image_input au premier tour image_to_sub_sample = classified_image_input else : # Image à reclassifier : la sortie de la boucle précédente ensuite image_to_sub_sample = image_output # determiner le label disponible de la classe base_subclass_label = int(class_to_sub_sample/100)*100 subclass_label = base_subclass_label for class_value in class_values_list: if (class_value > subclass_label) and (class_value < base_subclass_label + 100) : subclass_label = class_value subclass_label += 1 # subclass_label = int(class_to_sub_sample/100)*100 + 20 + class_to_sub_sample%20 * 5 # Label de départ des sous classes. Formule proposée : 3 premiers chiffres de class_to_sub_sample puis ajout de 20 + 5 * class_to_sub_sample modulo 20. Ex : 21000 -> 21020, 21001-> 21025, 21002-> 21030 etc... # Part du principe qu'il y a moins de 20 micro classes et que chacune est sous échantillonnée au maximum en 5 sous parties. Si ce n'est pas le cas : A ADAPTER number_of_sub_samples = sub_sampling_number_list[idx_class] # Nombre de sous classes demandées pour le sous échantillonage de class_to_sub_sample. Ex : 4 class_mask_raster = temp_sub_sampling_path + input_classified_image_name + "_" + str(class_to_sub_sample) + MASK_SUF + input_classified_image_extend # Ex : D2_Par_Zone/Paysage_01/Corr_2/Resultats/Temp/Temp_Sub_Sampling/Paysage_01_raw_21008_Mask.tif class_subsampled_raster = temp_sub_sampling_path + input_classified_image_name + "_" + str(class_to_sub_sample) + SUB_SAMPLE_SUF + input_classified_image_extend # Ex : D2_Par_Zone/Paysage_01/Corr_2/Resultats/Temp/Temp_Sub_Sampling/Paysage_01_raw_21008_SubSampled.tif centroid_file = temp_sub_sampling_path + input_classified_image_name + "_" + str(class_to_sub_sample) + CENTROID_SUF + EXTENSION_TXT # Ex : D2_Par_Zone/Paysage_01/Corr_2/Resultats/Temp/Temp_Sub_Sampling/Paysage_01_raw_21008_Centroid.txt if debug >= 5: print(cyan + "classRasterSubSampling() : " + endC + "class_to_sub_sample :" , class_to_sub_sample) print(cyan + "classRasterSubSampling() : " + endC + "subclass_label :" , subclass_label) print(cyan + "classRasterSubSampling() : " + endC + "number_of_sub_samples :" , number_of_sub_samples) print(cyan + "classRasterSubSampling() : " + endC + "class_mask_raster :" , class_mask_raster) print(cyan + "classRasterSubSampling() : " + endC + "class_subsampled_raster :" , class_subsampled_raster) print(cyan + "classRasterSubSampling() : " + endC + "centroid_file :" , centroid_file) if debug >= 3: print(cyan + "classRasterSubSampling() : " + bold + green + "CLASSE %s/%s : SOUS ECHANTILLONAGE DE %s EN %s CLASSES " %(idx_class+1, len(sub_sampling_class_list), class_to_sub_sample, number_of_sub_samples) + endC) # ETAPE 1/5 : EXTRACTION DU MASQUE BINAIRE DES PIXELS CORRESPONDANT A LA CLASSE expression_masque = "\"im1b1 == %s? 1 : 0\"" %(class_to_sub_sample) command = "otbcli_BandMath -il %s -out %s %s -exp %s" %(classified_image_input, class_mask_raster, CODAGE_8B, expression_masque) if debug >=2: print("\n" + cyan + "classRasterSubSampling() : " + bold + green + "CLASSE %s/%s - ETAPE 1/5 : Debut de l extraction du masque binaire de la classe %s" %(idx_class+1, len(sub_sampling_class_list),class_to_sub_sample) + endC) print(command) os.system(command) if debug >=2: print(cyan + "classRasterSubSampling() : " + bold + green + "CLASSE %s/%s - ETAPE 1/5 : Fin de l extraction du masque binaire de la classe %s, disponible ici : %s" %(idx_class+1, len(sub_sampling_class_list),class_to_sub_sample, class_mask_raster) + endC) # TEST POUR SAVOIR SI ON EST EN CAPACITE D'EFFECTUER LE KMEANS number_of_actives_pixels = countPixelsOfValue(class_mask_raster, 1) # Comptage du nombre de pixels disponibles pour effectuer le kmeans if number_of_actives_pixels > (number_of_sub_samples * number_of_actives_pixels_threshold) : # Cas où il y a plus de pixels disponibles pour effectuer le kmeans que le seuil # ETAPE 2/5 : CLASSIFICATION NON SUPERVISEE DES PIXELS CORRESPONDANT A LA CLASSE if debug >= 3: print("\n" + cyan + "classRasterSubSampling() : " + bold + green + "CLASSE %s/%s - ETAPE 2/5 : Il y a assez de pixels pour faire le sous echantillonage : %s sur %s requis au minimum " %(idx_class+1, len(sub_sampling_class_list), number_of_actives_pixels, int(number_of_sub_samples) * number_of_actives_pixels_threshold) + endC) if debug >=2: print("\n" + cyan + "classRasterSubSampling() : " + bold + green + "CLASSE %s/%s - ETAPE 2/5 : Debut du sous echantillonage par classification non supervisee en %s classes " %(idx_class+1, len(sub_sampling_class_list), number_of_sub_samples) + endC) # appel du kmeans input_mask_list = [] input_mask_list.append(class_mask_raster) output_masked_image_list = [] output_masked_image_list.append(class_subsampled_raster) output_centroids_files_list = [] output_centroids_files_list.append(centroid_file) macroclass_sampling_list = [] macroclass_sampling_list.append(number_of_sub_samples) macroclass_labels_list = [] macroclass_labels_list.append(subclass_label) applyKmeansMasks(satellite_image_input, input_mask_list, "", "", output_masked_image_list, output_centroids_files_list, macroclass_sampling_list, macroclass_labels_list, no_data_value, path_time_log, 200, 1, -1, 0.0, rand_otb, ram_otb, number_of_actives_pixels_threshold, extension_raster, save_results_intermediate, overwrite) if debug >=2: print(cyan + "classRasterSubSampling() : " + bold + green + "CLASSE %s/%s - ETAPE 2/5 : Fin du sous echantillonage par classification non supervisee en %s classes, disponible ici %s : " %(idx_class+1, len(sub_sampling_class_list), number_of_sub_samples, class_subsampled_raster) + endC) # ETAPE 3/5 : INTEGRATION DES NOUVELLES SOUS CLASSES DANS LA TABLE DE REALLOCATION # Ouveture du fichier table de proposition pour re-ecriture for i in range(number_of_sub_samples): class_values_list.append(subclass_label + i) text_new_table += str(subclass_label + i) + ";" + str(subclass_label + i) + "; METTRE A JOUR MANUELLEMENT (origine : " + str(class_to_sub_sample) + ")" + "\n" # ETAPE 4/5 : APPLICATION DU SOUS ECHANTILLONAGE AU RESULTAT DE CLASSIFICATION expression_application_sous_echantillonage = "\"im1b1 == %s? im2b1 : im1b1\"" %(class_to_sub_sample) command = "otbcli_BandMath -il %s %s -out %s %s -exp %s" %(image_to_sub_sample, class_subsampled_raster, image_output_temp, CODAGE, expression_application_sous_echantillonage) if debug >=2: print("\n" + cyan + "classRasterSubSampling() : " + bold + green + "CLASSE %s/%s - ETAPE 4/5 : Debut de l application du sous echantillonage present dans %s sur %s" %(idx_class+1, len(sub_sampling_class_list), class_subsampled_raster, classified_image_input) + endC) print(command) os.system(command) if debug >=2: print(cyan + "classRasterSubSampling() : " + bold + green + "CLASSE %s/%s - ETAPE 4/5 : Fin de l application du sous echantillonage present dans %s sur %s, sortie disponible ici : %s" %(idx_class+1, len(sub_sampling_class_list), class_subsampled_raster, classified_image_input, image_output_temp) + endC) # ETAPE 5/5 : GESTION DES RENOMMAGES ET SUPPRESSIONS if debug >=2: print("\n" + cyan + "classRasterSubSampling() : " + bold + green + "CLASSE %s/%s - ETAPE 5/5 : Debut du renommage et suppression des dossiers intermediaires" %(idx_class+1, len(sub_sampling_class_list)) + endC) if debug >=3 : print("\n" + green + "classified image input: %s" %(classified_image_input) + endC) print("\n" + green + "image to sub sample: %s" %(image_to_sub_sample) + endC) print("\n" + green + "image temp : %s" %(image_output_temp) + endC) print("\n" + green + "image output : %s" %(image_output) + endC) # Si l'image d'entrée et l'image de sorte sont le même fichier on efface le fichier d'entrée pour le re-creer avec le fichier re-travaillé if image_output == classified_image_input and os.path.isfile(classified_image_input) : removeFile(classified_image_input) os.rename(image_output_temp,image_output) processing_pass_first = True # SUPPRESSION DES FICHIERS TEMPORAIRES if not save_results_intermediate : if os.path.isfile(class_mask_raster) : removeFile(class_mask_raster) if os.path.isfile(class_subsampled_raster) : removeFile(class_subsampled_raster) if os.path.isfile(centroid_file) : removeFile(centroid_file) if debug >=2: print(cyan + "classRasterSubSampling() : " + bold + green + "CLASSE %s/%s - ETAPE 5/5 : Fin du renommage et suppression des dossiers intermediaires" %(idx_class+1, len(sub_sampling_class_list)) + endC) else: # Cas où il n'y a pas assez de pixels pour effectuer le kmeans if debug >=2: print("\n" + cyan + "classRasterSubSampling() : " + bold + yellow + "CLASSE %s/%s - ETAPE 2/5 : Nombre insuffisant de pixels disponibles pour appliquer le kmeans : %s sur %s requis au minimum " %(idx_class+1, len(sub_sampling_class_list), number_of_actives_pixels, int(number_of_sub_samples) * number_of_actives_pixels_threshold) + endC) print(cyan + "classRasterSubSampling() : " + bold + yellow + "CLASSE %s/%s - ETAPE 2/5 : SOUS ECHANTILLONAGE NON APPLIQUE A LA CLASSE %s" %(idx_class+1, len(sub_sampling_class_list), class_to_sub_sample) + endC + "\n") # MISE A JOUR DU FICHIER image_to_sub_sample if idx_class == 0: processing_pass_first = False # MISE A JOUR DE LA TABLE DE REALLOCATION text_new_table += str(class_to_sub_sample) + ";" + str(class_to_sub_sample) + ";CLASSE TROP PETITE POUR SOUS ECHANTILLONAGE" + "\n" # SUPPRESSION DU MASQUE if not save_results_intermediate and os.path.isfile(class_mask_raster) : removeFile(class_mask_raster) else: shutil.copy2(classified_image_input, image_output) # Copie du raster d'entree si pas de sous-echantillonnage # Ecriture de la nouvelle table dans le fichier writeTextFile(table_reallocation, text_new_table) # SUPPRESSION DU DOSSIER ET DES FICHIERS TEMPORAIRES if not save_results_intermediate and os.path.isdir(os.path.dirname(temp_sub_sampling_path)) : shutil.rmtree(os.path.dirname(temp_sub_sampling_path)) print(cyan + "classRasterSubSampling() : " + bold + green + "END\n" + endC) # Mise à jour du Log ending_event = "classRasterSubSampling() : Micro class subsampling on classification image ending : " timeLine(path_time_log,ending_event) return
def vectorsListToOcs(input_text, output_raster, footprint_vector, reference_raster, codage_raster='uint8', epsg=2154, no_data_value=0, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster='.tif', extension_vector='.shp', path_time_log='', save_results_intermediate=False, overwrite=True): if debug >= 3: print( '\n' + bold + green + "OCS raster à partir d'une liste de vecteurs - Variables dans la fonction :" + endC) print(cyan + " vectorsListToOcs() : " + endC + "input_text : " + str(input_text) + endC) print(cyan + " vectorsListToOcs() : " + endC + "output_raster : " + str(output_raster) + endC) print(cyan + " vectorsListToOcs() : " + endC + "footprint_vector : " + str(footprint_vector) + endC) print(cyan + " vectorsListToOcs() : " + endC + "reference_raster : " + str(reference_raster) + endC) print(cyan + " vectorsListToOcs() : " + endC + "codage_raster : " + str(codage_raster) + endC) print(cyan + " vectorsListToOcs() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + " vectorsListToOcs() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + " vectorsListToOcs() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + " vectorsListToOcs() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + " vectorsListToOcs() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + " vectorsListToOcs() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + " vectorsListToOcs() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + " vectorsListToOcs() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + " vectorsListToOcs() : " + endC + "overwrite : " + str(overwrite) + endC + '\n') # Définition des constantes SUFFIX_TEMP = '_temp' SUFFIX_CUT = '_cut' SUFFIX_FILTER = '_filter' SUFFIX_BUFFER = '_buffer' TEXT_SEPARATOR = ':' # Mise à jour du log starting_event = "vectorsListToOcs() : Début du traitement : " timeLine(path_time_log, starting_event) print(cyan + "vectorsListToOcs() : " + bold + green + "DEBUT DES TRAITEMENTS" + endC + '\n') # Définition des variables 'basename' output_raster_basename = os.path.basename( os.path.splitext(output_raster)[0]) output_raster_dirname = os.path.dirname(output_raster) # Définition des variables temp temp_directory = output_raster_dirname + os.sep + output_raster_basename + SUFFIX_TEMP temp_raster = temp_directory + os.sep + output_raster_basename + SUFFIX_TEMP + extension_raster # Nettoyage des traitements précédents if overwrite: if debug >= 3: print(cyan + "vectorsListToOcs() : " + endC + "Nettoyage des traitements précédents." + '\n') removeFile(output_raster) cleanTempData(temp_directory) else: if os.path.exists(output_raster): print(cyan + "vectorsListToOcs() : " + bold + yellow + "Le fichier de sortie existe déjà et ne sera pas regénéré." + endC) raise if not os.path.exixts(temp_directory): os.makedirs(temp_directory) pass # Test de l'emprise des fichiers vecteur d'emprise et raster de référence (le raster doit être de même taille ou plus grand que le vecteur) xmin_fpt, xmax_fpt, ymin_fpt, ymax_fpt = getEmpriseFile( footprint_vector, format_vector=format_vector) xmin_ref, xmax_ref, ymin_ref, ymax_ref = getEmpriseImage(reference_raster) if round(xmin_fpt, 4) < round(xmin_ref, 4) or round(xmax_fpt, 4) > round( xmax_ref, 4) or round(ymin_fpt, 4) < round(ymin_ref, 4) or round( ymax_fpt, 4) > round(ymax_ref, 4): print(cyan + "vectorsListToOcs() : " + bold + red + "xmin_fpt, xmax_fpt, ymin_fpt, ymax_fpt" + endC, xmin_fpt, xmax_fpt, ymin_fpt, ymax_fpt, file=sys.stderr) print(cyan + "vectorsListToOcs() : " + bold + red + "xmin_ref, xmax_ref, ymin_ref, ymax_ref" + endC, xmin_ref, xmax_ref, ymin_ref, ymax_ref, file=sys.stderr) raise NameError( cyan + "vectorsListToOcs() : " + bold + red + "The extend of the footprint vector (%s) is greater than the reference raster (%s)." % (footprint_vector, reference_raster) + endC) # Récupération des traitements à faire dans le fichier texte d'entrée text_list = readTextFileBySeparator(input_text, TEXT_SEPARATOR) #################################################################### print(cyan + "vectorsListToOcs() : " + bold + green + "Début de la génération de l'OCS raster à partir de vecteurs." + endC + '\n') # Boucle sur les traitements à réaliser for text in text_list: idx = text_list.index(text) + 1 class_label = int(text[0]) vector_file = text[1] if debug >= 3: print(cyan + "vectorsListToOcs() : " + endC + bold + "Génération %s/%s : " % (idx, len(text_list)) + endC + "traitement du fichier %s (label %s)." % (vector_file, str(class_label)) + '\n') # Gestion des noms des fichiers temporaires vector_file_basename = os.path.basename( os.path.splitext(vector_file)[0]) vector_file_cut = temp_directory + os.sep + vector_file_basename + SUFFIX_CUT + extension_vector vector_file_filter = temp_directory + os.sep + vector_file_basename + SUFFIX_FILTER + extension_vector vector_file_buffer = temp_directory + os.sep + vector_file_basename + SUFFIX_BUFFER + extension_vector vector_file_raster = temp_directory + os.sep + vector_file_basename + extension_raster # Gestion des variables de traitement (tampon et filtrage SQL) try: buffer_len = float(text[2]) except ValueError: buffer_len = text[2] except Exception: buffer_len = '' try: sql_filter = text[3] except Exception: sql_filter = '' # Découpage à l'emprise de la zone d'étude if debug >= 3: print(cyan + "vectorsListToOcs() : " + endC + "Découpage à l'emprise de la zone d'étude." + '\n') cutVectorAll(footprint_vector, vector_file, vector_file_cut, overwrite=overwrite, format_vector=format_vector) # Filtrage SQL (facultatif) if sql_filter != '': if debug >= 3: print(cyan + "vectorsListToOcs() : " + endC + "Application du filtrage SQL : %s." % sql_filter + '\n') attr_names_list = getAttributeNameList(vector_file_cut, format_vector=format_vector) column = "'" for attr_name in attr_names_list: column += attr_name + ", " column = column[:-2] column += "'" filterSelectDataVector(vector_file_cut, vector_file_filter, column, sql_filter, overwrite=overwrite, format_vector=format_vector) else: vector_file_filter = vector_file_cut # Application d'un tampon (facultatif) if buffer_len != '' and buffer_len != 0: if debug >= 3: print(cyan + "vectorsListToOcs() : " + endC + "Application d'un buffer : %s." % buffer_len + '\n') if type(buffer_len) is float: bufferVector(vector_file_filter, vector_file_buffer, buffer_len, col_name_buf='', fact_buf=1.0, quadsecs=10, format_vector=format_vector) else: bufferVector(vector_file_filter, vector_file_buffer, 0, col_name_buf=buffer_len, fact_buf=1.0, quadsecs=10, format_vector=format_vector) else: vector_file_buffer = vector_file_filter # Rastérisation du vecteur préparé if debug >= 3: print(cyan + "vectorsListToOcs() : " + endC + "Rastérisation du vecteur préparé." + '\n') rasterizeBinaryVector(vector_file_buffer, reference_raster, vector_file_raster, label=class_label, codage=codage_raster) # Ajout de l'information dans le raster de sortie if debug >= 3: print(cyan + "vectorsListToOcs() : " + endC + "Ajout de l'information dans le raster de sortie." + '\n') if idx == 1: shutil.copy(vector_file_raster, output_raster) else: removeFile(temp_raster) shutil.copy(output_raster, temp_raster) removeFile(output_raster) expression = "im1b1!=%s ? im1b1 : im2b1" % no_data_value rasterCalculator([temp_raster, vector_file_raster], output_raster, expression, codage=codage_raster) print(cyan + "vectorsListToOcs() : " + bold + green + "Fin de la génération de l'OCS raster à partir de vecteurs." + endC + '\n') #################################################################### # Suppression des fichiers temporaires if not save_results_intermediate: if debug >= 3: print(cyan + "vectorsListToOcs() : " + endC + "Suppression des fichiers temporaires." + '\n') deleteDir(temp_directory) print(cyan + "vectorsListToOcs() : " + bold + green + "FIN DES TRAITEMENTS" + endC + '\n') # Mise à jour du log ending_event = "vectorsListToOcs() : Fin du traitement : " timeLine(path_time_log, ending_event) return 0