update alfonso

parent 21e896c5
#!/usr/bin/python
# -*- coding: utf-8 -*-
form ../geosentinel import APISentienel
sentinel = APISentinel.APISentinel('asalazarg', 'geo135asg')
#products = sentinel.getProducts("POLYGON((-89.99450683593753 21.279137394108716,-89.13757324218751 21.2996106049456,-89.30236816406251 20.68418377935238,-90.0494384765625 20.715015145512098,-89.99450683593753 21.279137394108716))", ('20151219', date(2015,12,29)), {"platformname":"Sentinel-2"})
print len(products)
#sentinel.downloadProducts(products,dir)
...@@ -13,17 +13,17 @@ Example: ...@@ -13,17 +13,17 @@ Example:
import os import os
from sentinelsat.sentinel import SentinelAPI from sentinelsat.sentinel import SentinelAPI
from datetime import date from datetime import date
from collections import OrderedDict
from osgeo import ogr
class APISentinel(object): class APISentinel(object):
""" Class for Sentinel satellites configuration """ Class for Sentinel satellites configuration
Test Case Test Case
>>> sentinel = APISentinel('asalazarg', 'geo135asg') >>> sentinel = APISentinel('asalazarg', 'geo135asg')
>>> dir="make"
>>> if not os.path.exists(dir):
... os.mkdir(dir)
>>> products = sentinel.getProducts("POLYGON((-89.99450683593753 21.279137394108716,-89.13757324218751 21.2996106049456,-89.30236816406251 20.68418377935238,-90.0494384765625 20.715015145512098,-89.99450683593753 21.279137394108716))", ('20151219', date(2015,12,29)), {"platformname":"Sentinel-2"}) >>> products = sentinel.getProducts("POLYGON((-89.99450683593753 21.279137394108716,-89.13757324218751 21.2996106049456,-89.30236816406251 20.68418377935238,-90.0494384765625 20.715015145512098,-89.99450683593753 21.279137394108716))", ('20151219', date(2015,12,29)), {"platformname":"Sentinel-2"})
>>> print len(products) >>> print len(products)
3 3
>>> sentinel.downloadProducts(products,dir)
""" """
...@@ -79,3 +79,41 @@ class APISentinel(object): ...@@ -79,3 +79,41 @@ class APISentinel(object):
""" """
os.chdir(dir) os.chdir(dir)
self.api.download_all(products) self.api.download_all(products)
def filterProducts(self, products_list, user_footprint, threshold):
products_down = OrderedDict()
products_down = products_list.copy()
products_df = self.api.to_dataframe(products_list)
polyfootprint = ogr.CreateGeometryFromWkt(user_footprint)
areafootprint = polyfootprint.GetArea()
for i in range(len(products_df)):
inputpoly = ogr.CreateGeometryFromWkt(products_df.footprint[i])
intersectionpoly = polyfootprint.Intersection(inputpoly)
intersectionpoly_area = intersectionpoly.GetArea()
por_intersection = (intersectionpoly_area * 100) / areafootprint
if (por_intersection <= threshold):
# Deleting element
del products_down[products_df.uuid[i]]
return products_down
sentinel = APISentinel('asalazarg', 'geo135asg')
dir="make1"
polygon = "POLYGON((-89.81053770202163 21.11585680707654,-89.75755340340068 21.11585680707654,-89.75755340340068 21.15331224168125,-89.81053770202163 21.15331224168125,-89.81053770202163 21.11585680707654))"
options = {"platformname": "Sentinel-2", "cloudcoverpercentage": "[0 TO 30]"} #, "footprint": "Intersects("+polygon+")"}
print options
products = sentinel.getProducts(polygon, ('20150801', date(2018,05,15)), options)
print len(products)
products = sentinel.filterProducts(products, polygon, 95)
print len(products)
sentinel.downloadProducts(products,dir)
# -*- coding: utf-8 -*-
# @package Download Image Sentinel
"""
Install:
$ pip install sentinelsat
Example:
$ python -m doctest -v APISentinel.py
"""
import os
from sentinelsat.sentinel import SentinelAPI
from datetime import date
class APISentinel(object):
""" Class for Sentinel satellites configuration
Test Case
>>> sentinel = APISentinel('asalazarg', 'geo135asg')
>>> dir="make"
>>> products = sentinel.getProducts("POLYGON((-89.99450683593753 21.279137394108716,-89.13757324218751 21.2996106049456,-89.30236816406251 20.68418377935238,-90.0494384765625 20.715015145512098,-89.99450683593753 21.279137394108716))", ('20151219', date(2015,12,29)), {"platformname":"Sentinel-2"})
>>> print len(products)
3
>>> sentinel.downloadProducts(products,dir)
"""
def __init__(self,usernam,passw):
"""The constructor Initialize Sentinel Data.
Args:
self: The object pointer.
usernam (str): Username, access credentials to https://scihub.copernicus.eu/dhus/#/home.
passw (str): Password, access credentials to https://scihub.copernicus.eu/dhus/#/home.
Returns:
pointer: The object pointer.
"""
self.username = usernam
self.password = passw
self.URL_Sentinel = 'https://scihub.copernicus.eu/dhus'
# self.plot_width = 7
# self.plot_height = 7
# self.intersection_th = 30
self.api = SentinelAPI(self.username, self.password, self.URL_Sentinel)
def getProducts(self, area, date, searchParameters):
"""Gets Sentinel products list that match the search parameters.
Args:
self (pointer): The object pointer.
area (str): area of interest using a Polygon in WKT format.
Example:
"POLYGON((-89.99 21.27,-89.13 21.29,-89.30 20.68,-90.04 20.71,-89.99 21.27))"
date (str): Initial date and end date.
searchParameters (str): Type platform Sentinel-1 or Sentinel-2
Other Parameters: Additional keywords can be used to specify other query parameters, e.g. relativeorbitnum-
ber=70. See https://scihub.copernicus.eu/twiki/do/view/SciHubUserGuide/3FullTextSearch for a full list. Ran-
ge values can be passed as two-element tuples, e.g. cloudcoverpercentage=(0, 30). The time interval formats
accepted by the ``date`` parameter can also be used with any other parameters that expect time intervals
(that is:'beginposition', 'endposition',
Returns:
OrderedDict: Sentinel Product list found.
"""
products_list = self.api.query(area, date, **searchParameters)
return products_list
def downloadProducts(self,products,dir):
"""Download product(s) list Sentinel
Args:
self (pointer): The object pointer.
products (OrderedDict): Product(s) to download.
dir (str): destination directory.
"""
os.chdir(dir)
self.api.download_all(products)
sentinel = APISentinel('asalazarg', 'geo135asg')
dir="make1"
products = sentinel.getProducts("POLYGON((-89.74867455832637 20.870461460298557,-89.49323446602745 20.870461460298557,-89.49323446602745 21.09542302174667,-89.74867455832637 21.09542302174667,-89.74867455832637 20.870461460298557))", ('20150801', date(2018,05,15)), {"platformname":"Sentinel-2","cloudcoverpercentage":"0"})
print len(products)
sentinel.downloadProducts(products,dir)
...@@ -6,13 +6,17 @@ Example: ...@@ -6,13 +6,17 @@ Example:
$ python -m doctest -v Merge.py $ python -m doctest -v Merge.py
""" """
import os,sys import os,sys,cv2
from PIL import Image
from os.path import expanduser from os.path import expanduser
home = expanduser("~") home = expanduser("~")
a=os.path.join(os.path.expandvars(home),".snap/snap-python/") a=os.path.join(os.path.expandvars(home),".snap/snap-python/")
sys.path.append(a) sys.path.append(a)
import snappy,numpy import snappy,numpy
from snappy import jpy,ProductData,ProgressMonitor,ProductUtils from snappy import jpy,ProductData,ProgressMonitor,ProductUtils
from osgeo import ogr
from osgeo import gdal
from osgeo.gdalconst import *
from tools import (tools) from tools import (tools)
from readProduct import (readProduct) from readProduct import (readProduct)
...@@ -34,27 +38,23 @@ class Merge(object): ...@@ -34,27 +38,23 @@ class Merge(object):
... Mergee.merges(product, file) ... Mergee.merges(product, file)
""" """
def __init__(self,ResolSize,TypeMerge): def __init__(self,TypeMerge):
"""The constructor Initialize Sentinel Data. """The constructor Initialize Sentinel Data.
Args: Args:
self: The object pointer. self: The object pointer.
ResolSize (str): destination directory.
TypeMerge (str): RGB TypeMerge (str): RGB
Returns: Returns:
pointer: The object pointer. pointer: The object pointer.
""" """
self.resolution=ResolSize
self.ext=".jpg" self.ext=".jpg"
self.Type_Merge="_"+TypeMerge self.Type_Merge="_"+TypeMerge
self.HashMap = jpy.get_type('java.util.HashMap')
self.looks = jpy.get_type('org.esa.snap.core.datamodel.quicklooks.QuicklookGenerator') self.looks = jpy.get_type('org.esa.snap.core.datamodel.quicklooks.QuicklookGenerator')
self.File = jpy.get_type('java.io.File') self.File = jpy.get_type('java.io.File')
self.ImageManager = jpy.get_type('org.esa.snap.core.image.ImageManager')
(self.h, self.w) = (None, None)
def merges(self, product, file): #def merges(self, product, file):
def merges(self, product, products,file):
"""Index Files Sentinel """Index Files Sentinel
Args: Args:
...@@ -63,6 +63,8 @@ class Merge(object): ...@@ -63,6 +63,8 @@ class Merge(object):
file (str): local path to image. file (str): local path to image.
""" """
############################################################################
#code ESA jpg
blue = product.getBand('B2') blue = product.getBand('B2')
green = product.getBand('B3') green = product.getBand('B3')
red = product.getBand('B4') red = product.getBand('B4')
...@@ -72,6 +74,67 @@ class Merge(object): ...@@ -72,6 +74,67 @@ class Merge(object):
info = ProductUtils.createImageInfo(RGB, True, ProgressMonitor.NULL) info = ProductUtils.createImageInfo(RGB, True, ProgressMonitor.NULL)
image = ProductUtils.createRgbImage(RGB, info, ProgressMonitor.NULL) image = ProductUtils.createRgbImage(RGB, info, ProgressMonitor.NULL)
salida = file[:-4] + self.Type_Merge + self.ext salida = file[:-5] + self.Type_Merge + self.ext
savefile = self.File(salida) savefile = self.File(salida)
self.looks.writeImage(image, savefile) self.looks.writeImage(image, savefile)
############################################################################
##OpenCV using .SAFE Images and searchBandsCombination
dataset1=cv2.imread(products[2], cv2.IMREAD_ANYCOLOR)#B2 B cv2.IMREAD_ANYCOLOR
print"B ",products[2]
dataset2=cv2.imread(products[1], cv2.IMREAD_ANYCOLOR)#B4 R
print"R ", products[1]
dataset3=cv2.imread(products[0], cv2.IMREAD_ANYCOLOR)#B3 G
print"G ", products[0]
##sys.exit()
salida = file[:-5] + self.Type_Merge
image = cv2.merge([dataset1, dataset3, dataset2])
cv2.imwrite(salida + 'OpenCV.png', image)
############################################################################
TotImage = len(products)
# Get Raster
dataset1 = gdal.Open(products[2], GA_ReadOnly)#B
dataset2 = gdal.Open(products[1], GA_ReadOnly)#R
dataset3 = gdal.Open(products[0], GA_ReadOnly)#G
# Get metadata raster
projectionfrom = dataset1.GetProjection()
geotransform = dataset1.GetGeoTransform()
band1 = dataset1.GetRasterBand(1)
xsize = band1.XSize
ysize = band1.YSize
datatype1 = band1.DataType
band2 = dataset2.GetRasterBand(1)
datatype2 = band2.DataType
band3 = dataset3.GetRasterBand(1)
datatype3 = band3.DataType
# Reading the raster values
gtiff = gdal.GetDriverByName('GTiff')
#output_file = file[:-5] + "_" + self.Type_Merge + ".tif"
output_file = file[:-5] + self.Type_Merge + ".tif"
values1 = band1.ReadRaster(0, 0, xsize, ysize, xsize, ysize, datatype2)
values2 = band2.ReadRaster(0, 0, xsize, ysize, xsize, ysize, datatype3)
values3 = band3.ReadRaster(0, 0, xsize, ysize, xsize, ysize, datatype1)
# Combination bands
output_dataset = gtiff.Create(output_file, xsize, ysize, TotImage, GDT_Int16)
output_dataset.SetProjection(projectionfrom)
output_dataset.SetGeoTransform(geotransform)
output_dataset.GetRasterBand(1).WriteRaster(0, 0, xsize, ysize, values1)
output_dataset.GetRasterBand(2).WriteRaster(0, 0, xsize, ysize, values2)
output_dataset.GetRasterBand(3).WriteRaster(0, 0, xsize, ysize, values3)
output_dataset = None
Files = tools("all") #IW_SLC,IW_GRDH,MSIL1C
dir="make/"
platform='Sentinel-2'
list_files=Files.findFilesSentinel(dir,platform,2)#4 for resample_subset.dim
print 'There is/are %d ' % len(list_files) + platform + ' file(s)'
Read=readProduct(dir,platform)
TypeMerge="RGB"
Mergee=Merge(TypeMerge)
for image in list_files:
file = dir + image
products = Files.search_band_combination(file, TypeMerge)
print"Applying Merge "+TypeMerge+"... ", image
product=Read.ReadFilesSentinel(file,2)#The flag 2 ReadFiles .dim
#Mergee.merges(product, file)#for resample_subset.dim
Mergee.merges(product, products,file)#for .SAFE
...@@ -81,3 +81,26 @@ class tools(object): ...@@ -81,3 +81,26 @@ class tools(object):
print"Files not found..." print"Files not found..."
sys.exit() sys.exit()
return files return files
def search_band_combination(self, sentinel_image,Type_Merge):
Granule = "/GRANULE"
path = sentinel_image + Granule
file = os.listdir(path)
path = path + "/" + file[0]
Img_Data = "/IMG_DATA"
path = path + Img_Data
file = os.listdir(path)
products = []
if Type_Merge == "RGB":
ext1 = "B04.jp2"
ext2 = "B03.jp2"
ext3 = "B02.jp2"
raster = [f for f in file if f.endswith(ext1) or f.endswith(ext2) or f.endswith(ext3)]
for raster in raster:
product = path + "/" + raster
a = os.path.join(os.getcwd(), product)
#print"RUTA.....",a
#sys.exit()
products.append(a)
# combinations_bands_sentinel(sentinel_image, Type_Merge, products)
return products
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment