From aba2612643ec5e4ad0c6934d1afd914f00aa042a Mon Sep 17 00:00:00 2001
From: Commandre Benjamin <benjamin.commandre@irstea.fr>
Date: Tue, 23 Apr 2019 11:40:28 +0200
Subject: [PATCH] Utilisation des bandes 'FRE' pour Sentinel2, ajout d'un seuil
 d'ennuagement, utilisation de la fonction 'Warp' au lieu de 'Translate'

---
 app/Archive.py    | 15 ++++++---------
 app/Outils.py     |  6 +++---
 app/Processing.py | 11 ++++++-----
 app/Satellites.py |  2 +-
 main.py           | 14 +++-----------
 5 files changed, 19 insertions(+), 29 deletions(-)

diff --git a/app/Archive.py b/app/Archive.py
index 058bba0..64727ce 100644
--- a/app/Archive.py
+++ b/app/Archive.py
@@ -509,14 +509,12 @@ class Archive():
         tuiles_nuage = []
 
         # Options Gdal pour la fusion des bandes
-        options_vrt     	= gdal.ParseCommandLine('-resolution highest -srcnodata -10000 -vrtnodata NaN -separate')
-        options_translate   = gdal.ParseCommandLine('-of Mem -ot Float32 -a_nodata NaN')
+        options_vrt = gdal.ParseCommandLine('-resolution highest -srcnodata -10000 -vrtnodata NaN -separate')
 
         self.logger.info("Extraction des images")
 
         # Pour chaque archive
         for idx, content in enumerate(liste_content) :
-
             # Lecture de l'archive
             tzip = zipfile.ZipFile(io.BytesIO(content))
 
@@ -546,6 +544,8 @@ class Archive():
             image = Outils.clip(vrt, self.zone_etude)
             _, aire = self.calcul_aire(image)
 
+            del image
+
             if aire > 0.0 :
                 tuiles_image.append(vrt)
 
@@ -579,18 +579,15 @@ class Archive():
 
             if len(tuiles_nuage) == 0 or self.calcul_ennuagement(tuiles_nuage) <= self.seuil_nuage:
 
-                # On effectue une mosaïque des images qu'on découpe selon l'emprise.
-                image = Outils.clip(tuiles_image, self.emprise)
-
                 self.logger.info("Sauvegarde des images")
 
                 dossier = "{0}/{1}/Images".format(self.dossier_sortie, date[:4])
 
                 self.logger.debug("Dossier image : {0}".format(dossier))
 
-                self.ecriture_geotiff(image, "{0}/{1}.tif".format(dossier,date))
+                # On effectue une mosaïque des images qu'on découpe selon l'emprise.
+                Outils.clip(tuiles_image, self.emprise, form="GTiff", dst="{0}/{1}.tif".format(dossier,date))
 
                 del tuiles_nuage
 
-            del tuiles_image
-            del image
\ No newline at end of file
+            del tuiles_image
\ No newline at end of file
diff --git a/app/Outils.py b/app/Outils.py
index efec4bc..f78a986 100644
--- a/app/Outils.py
+++ b/app/Outils.py
@@ -97,7 +97,7 @@ def limitation_temporelle(secondes):
 # except TimeoutException:
 #     pass
 
-def clip(image, cut, form="Mem", dst="", type=gdal.GDT_Float32, nodata="NaN"):
+def clip(image, cut, form="Mem", dst="", type_sortie=gdal.GDT_Float32, nodata="NaN"):
 	"""
 		Découpe une image selon un shapefile donné. Si le type de l'image en sortie
 		n'est pas spécifié, l'image sera retournée en pointeur mémoire et ne sera pas sauvegardée.
@@ -114,8 +114,8 @@ def clip(image, cut, form="Mem", dst="", type=gdal.GDT_Float32, nodata="NaN"):
 		:param dst: Chemin de l'image en sortie.
 		:type dst: Chaîne de caractères
 	"""
-        
+
 	option_clip = gdal.WarpOptions(cropToCutline=True,\
-	cutlineDSName=cut, outputType=type , format=form, dstNodata=nodata)
+	cutlineDSName=cut, outputType=type_sortie , format=form, dstNodata=nodata)
 
 	return gdal.Warp(dst, image, options=option_clip)
\ No newline at end of file
diff --git a/app/Processing.py b/app/Processing.py
index 3c72971..5974dd9 100644
--- a/app/Processing.py
+++ b/app/Processing.py
@@ -61,7 +61,7 @@ class Processing(object):
 			Méthode effectuant le calcul du NDVI via le module OTB : 'RadiometricIndices'
 		"""
 
-		options_vrt = gdal.BuildVRTOptions(separate=True)
+		options_vrt	= gdal.ParseCommandLine('-resolution highest -separate')
 		
 		otb_NDVI = otb.Registry.CreateApplication("RadiometricIndices")
 		otb_NDVI.SetParameterInt("channels.blue", 1)
@@ -84,13 +84,14 @@ class Processing(object):
 
 				chemin_ndvi = "{}/ndvi_{}".format(dossier_NDVI, os.path.basename(img))
 
-				if not str2bool(sauvegarde[os.path.basename(img)[:-4]]["NDVI"]) :
+				if not str2bool(sauvegarde[os.path.basename(img)[:-4]]["NDVI"]):
 					otb_NDVI.SetParameterString("in", img)
 					otb_NDVI.SetParameterString("out", chemin_ndvi)
 					otb_NDVI.ExecuteAndWriteOutput()
 					sauvegarde[os.path.basename(img)[:-4]]["NDVI"] = "True"
 
-			vrt = gdal.BuildVRT("", self.liste_dossier[annee], options=options_vrt)
+			liste_ndvi = sorted([x for x in glob.glob("{}/*".format(dossier_NDVI)) if x.endswith(".tif") and "stack" not in x])
+			vrt = gdal.BuildVRT("", liste_ndvi, options=options_vrt)
 			gdal.Translate("{}/{}/NDVI/stack_ndvi.tif".format(self.resultats, annee), vrt)
 
 			with open("{}/{}/sauvegarde.ini".format(self.resultats, annee), 'w') as configfile:
@@ -100,5 +101,5 @@ class Processing(object):
 		"""
 			Calul le ndvi, fusionnne en une seule image puis lance le module OTBPhenology
 		"""
-		# self.calcul_ndvi()
-		# self.otbPhenologie()
\ No newline at end of file
+		self.calcul_ndvi()
+		self.otbPhenologie()
\ No newline at end of file
diff --git a/app/Satellites.py b/app/Satellites.py
index 5680095..1a3d0ce 100644
--- a/app/Satellites.py
+++ b/app/Satellites.py
@@ -14,7 +14,7 @@ SATELLITE["SENTINEL2"]["resto"] = "resto2"
 SATELLITE["SENTINEL2"]["token_type"] = "text"
 SATELLITE["SENTINEL2"]["R"] = 2
 SATELLITE["SENTINEL2"]["PIR"] = 3
-SATELLITE["SENTINEL2"]["LEVEL2A"] 	= ['_SRE_B2.tif', '_SRE_B3.tif', '_SRE_B4.tif', '_SRE_B8.tif']
+SATELLITE["SENTINEL2"]["LEVEL2A"] 	= ['_FRE_B2.tif', '_FRE_B3.tif', '_FRE_B4.tif', '_FRE_B8.tif']
 SATELLITE["SENTINEL2"]["NUAGE"] 	= ['_CLM_R1.tif']
 SATELLITE["SENTINEL2"]["LEVEL3A"] 	= ['_FRC_B2.tif', '_FRC_B3.tif', '_FRC_B4.tif', '_FRC_B8.tif']
 
diff --git a/main.py b/main.py
index 055fe53..c563df6 100644
--- a/main.py
+++ b/main.py
@@ -43,7 +43,7 @@ class Telechargement(Processing):
 			raise "L'année de départ est requise."
 		
 		self.annee_fin = "{}".format(configfile["donnees"]["annee_fin"])
-		self.seuil_nuage = float("{}".format(configfile["donnees"]["seuil_nuage"]))/100.0
+		self.seuil_nuage = float("{}".format(configfile["donnees"]["seuil_nuage"]))/100.0 if "{}".format(configfile["donnees"]["seuil_nuage"]) else 0.0
 		
 		# Emprise et zone de l'étude
 		self.emprise 	= "{}".format(configfile["donnees"]["chemin_emprise"])
@@ -62,7 +62,7 @@ class Telechargement(Processing):
 		"""
 			Fonction pour lancer le programme
 		"""		
-		Début du processus
+		# Début du processus
 		debut = time.time()
 		
 		# Recherche de nouvelles images non traitées et téléchargement de celles-ci le cas échéant
@@ -81,12 +81,4 @@ class Telechargement(Processing):
 if __name__ == "__main__":
 
 	app = Telechargement()
-
-	SUCCESS = False
-
-	while not SUCCESS :
-		try:
-			sys.exit(app.run())
-			SUCCESS = True
-		except Exception as e:
-			pass	
\ No newline at end of file
+	sys.exit(app.run())
-- 
GitLab