def topophaseRemoval(product): if debug >= 2: print(cyan + "topophaseRemoval() : " + bold + green + "Run to SNAP... " + endC) # Instance de GPF GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() # Def operateur SNAP operator = 'TopoPhaseRemoval' # Set des parametres parameters = HashMap() parameters.put("Orbit Interpolation Degree", 3) parameters.put("Digital Elevation Model", "SRTM 1Sec HGT (Auto Download)") parameters.put("Tile Extension[%]", 100) parameters.put("Output topographic phase band", True) parameters.put("Output elevation band", False) if debug >= 2: print(parameters) # Get snappy Operators result = GPF.createProduct(operator, parameters, product) if debug >= 2: print(cyan + "topophaseRemoval() : " + bold + green + "Done... " + endC) return result
def describe_operators(): """This function provides a Python dictionary with all SNAP operators. Args: None. Returns Python dictionary with all SNAP operators. Raises: None. """ desc_dict = {} GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() op_spi_it = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpis().iterator() while op_spi_it.hasNext(): op_spi = op_spi_it.next() alias = op_spi.getOperatorDescriptor().getAlias() description = op_spi.getOperatorDescriptor().getDescription() desc_dict[alias] = description print( "{} - {}".format( alias, description ) ) return desc_dict
def backGeocoding(product): if debug >= 2: print(cyan + "backGeocoding() : " + bold + green + "Run to SNAP... " + endC) # Instance de GPF GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() # Def operateur SNAP operator = 'Back-Geocoding' # Set des parametres parameters = HashMap() parameters.put("Digital Elevation Model", "SRTM 1Sec HGT (Auto Download)") parameters.put("DEM Resampling Method", "BICUBIC_INTERPOLATION") parameters.put("Resampling Type", "BISINC_5_POINT_INTERPOLATION") parameters.put("Mask out areas with no elevation", True) parameters.put("Output Deramp and Demod Phase", False) if debug >= 2: print(parameters) # Get snappy Operators result = GPF.createProduct(operator, parameters, product) if debug >= 2: print(cyan + "backGeocoding() : " + bold + green + "Done... " + endC) return result
def interferogram(product): if debug >= 2: print(cyan + "interferogram() : " + bold + green + "Run to SNAP... " + endC) # Instance de GPF GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() # Def operateur SNAP operator = 'Interferogram' # Set des parametres parameters = HashMap() parameters.put("Subtract flat-earth phase", True) parameters.put("Degree of \"Flat Earth\" polynomial", 5) parameters.put("Number of \"Flat Earth\" estimation points", 501) parameters.put("Orbit interpolation degree", 3) parameters.put("Include coherence estimation", True) parameters.put("Square Pixel", False) parameters.put("Independent Window Sizes", False) parameters.put("Coherence Azimuth Window Size", 10) parameters.put("Coherence Range Window Size", 10) if debug >= 2: print(parameters) # Get snappy Operators result = GPF.createProduct(operator, parameters, product) if debug >= 2: print(cyan + "interferogram() : " + bold + green + "Done... " + endC) return result
def _band_math(self, product, name, expression): GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() HashMap = jpy.get_type('java.util.HashMap') BandDescriptor = jpy.get_type( 'org.esa.snap.core.gpf.common.BandMathsOp$BandDescriptor') targetBand = BandDescriptor() targetBand.name = name targetBand.type = 'float32' targetBand.expression = expression bands = jpy.array( 'org.esa.snap.core.gpf.common.BandMathsOp$BandDescriptor', 1) bands[0] = targetBand parameters = HashMap() parameters.put('targetBands', bands) productMap = HashMap() if isinstance(product, list): for ind in range(len(product)): print('p{}'.format(ind + 1)) productMap.put('p{}'.format(ind + 1), product[ind]) result = GPF.createProduct('BandMaths', parameters, productMap) else: result = GPF.createProduct('BandMaths', parameters, product) return result
def subset(product, borderRectInGeoCoor): from snappy import jpy from snappy import ProductIO from snappy import GPF from snappy import HashMap xmin = borderRectInGeoCoor[0] ymin = borderRectInGeoCoor[1] xmax = borderRectInGeoCoor[2] ymax = borderRectInGeoCoor[3] p1 = '%s %s' % (xmin, ymin) p2 = '%s %s' % (xmin, ymax) p3 = '%s %s' % (xmax, ymax) p4 = '%s %s' % (xmax, ymin) wkt = "POLYGON((%s, %s, %s, %s, %s))" % (p1, p2, p3, p4, p1) WKTReader = jpy.get_type('com.vividsolutions.jts.io.WKTReader') geom = WKTReader().read(wkt) HashMap = jpy.get_type('java.util.HashMap') GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() parameters = HashMap() parameters.put('copyMetadata', True) parameters.put('geoRegion', geom) parameters.put('outputImageScaleInDb', False) subset = GPF.createProduct('Subset', parameters, product) return subset
def topsarDeburst(product): if debug >= 2: print(cyan + "topsarDeburst() : " + bold + green + "Run to SNAP... " + endC) # Instance de GPF GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() # Def operateur SNAP operator = 'TOPSAR-Deburst' # Set des parametres parameters = HashMap() parameters.put("Polarisations", "VV") if debug >= 2: print(parameters) # Get snappy Operators result = GPF.createProduct(operator, parameters, product) if debug >= 2: print(cyan + "topsarDeburst() : " + bold + green + "Done... " + endC) return result
def goldsteinPhasefiltering(product): if debug >= 2: print(cyan + "goldsteinPhasefiltering() : " + bold + green + "Run to SNAP... " + endC) # Instance de GPF GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() # Def operateur SNAP operator = 'GoldsteinPhaseFiltering' # Set des parametres parameters = HashMap() parameters.put("Adaptive Filter Exponent in(0,1]:", 1.0) parameters.put("FFT Size", 64) parameters.put("Window Size", 3) parameters.put("Use coherence mask", False) parameters.put("Coherence Threshold in[0,1]:", 0.2) if debug >= 2: print(parameters) # Get snappy Operators result = GPF.createProduct(operator, parameters, product) if debug >= 2: print(cyan + "goldsteinPhasefiltering() : " + bold + green + "Done... " + endC) return result
def resample(DIR, band, resolution): """ resamples a band of a SENTINEL product to a given target resolution :param DIR: base directory of Sentinel2 directory tree :param band: band name (e.g. B4) :param resolution: target resolution in meter (e.g 10) :return: resampled band """ from snappy import GPF GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() HashMap = jpy.get_type('java.util.HashMap') BandDescriptor = jpy.get_type( 'org.esa.snap.core.gpf.common.BandMathsOp$BandDescriptor') parameters = HashMap() parameters.put('targetResolution', resolution) parameters.put('upsampling', 'Bicubic') parameters.put('downsampling', 'Mean') parameters.put('flagDownsampling', 'FlagMedianAnd') parameters.put('resampleOnPyramidLevels', True) product = ProductIO.readProduct(DIR) product = GPF.createProduct('Resample', parameters, product) rsp_band = product.getBand(band) return rsp_band
def topsarSplit(product): if debug >= 2: print(cyan + "applyingOrbitFile() : " + bold + green + "Run to SNAP... " + endC ) # Instance de GPF GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() # Def operateur SNAP operator = 'TOPSAR-Split' # Set des parametres parameters = HashMap() op_spi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(operator) op_params = op_spi.getOperatorDescriptor().getParameterDescriptors() for param in op_params: if debug >= 2: print(cyan + "topsarSplit() : " + bold + green + str(param.getName()) + " : " + str(param.getDefaultValue()) + endC) parameters.put(param.getName(), param.getDefaultValue()) parameters.put('subswath', 'IW1') parameters.put('selectedPolarisations', 'VV') if debug >= 2: print(parameters) # Get snappy Operators result = GPF.createProduct(operator, parameters, product) if debug >= 2: print(cyan + "topsarSplit() : " + bold + green + "Done... " + endC) return result
def list_operators(): """This function provides a Python dictionary with all SNAP operators. Args: None. Returns Python dictionary with all SNAP operators. Raises: None. """ GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() op_spi_it = GPF.getDefaultInstance().getOperatorSpiRegistry( ).getOperatorSpis().iterator() snap_operators = [] while op_spi_it.hasNext(): op_spi = op_spi_it.next() snap_operators.append(op_spi.getOperatorAlias()) return snap_operators
def __init__(self): # HashMap # Key-Value pairs. # https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html self.HashMap = jpy.get_type('java.util.HashMap') # Get snappy Operators GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis()
def classify(prepros_folder): for file in os.listdir(prepros_folder): ### Folder, date & timestamp classification = rootpath + "\\classification" scene_name = str(prepros_folder.split("\\")[X])[:32] # [X] element of filepath, change this to match scene name. [:32] first caracters of element print("scene_name:", scene_name) output_folder = os.path.join(classification, scene_name) print("output_folder:", output_folder) polarization = str(file)[46:48] # polarization from filename if not os.path.exists(output_folder): os.mkdir(output_folder) GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() HashMap = snappy.jpy.get_type('java.util.HashMap') gc.enable() sentinel_1 = ProductIO.readProduct(os.path.join(prepros_folder, file)) res = [20, 50] # parameters for CFAR for r in res: resolution = r gd_window = resolution * 12.0 bg_window = resolution * 37.0 # AdaptiveThresholding (Constant False Alarm Rate CFAR) parameters = HashMap() parameters.put('targetWindowSizeInMeter', resolution) parameters.put('guardWindowSizeInMeter', gd_window) parameters.put('backgroundWindowSizeInMeter', bg_window) parameters.put('pfa', 6.0) target_1 = GPF.createProduct("AdaptiveThresholding", parameters, sentinel_1) parameters = None # Subset (extracting classification band) parameters = HashMap() parameters.put('bandNames', 'Sigma0_' + polarization + '_ship_bit_msk') outfile = output_folder + "\\" + scene_name + "_" + polarization + "_cfar_" + str(resolution) + "m" target_2 = GPF.createProduct("Subset", parameters, target_1) ProductIO.writeProduct(target_2, outfile, 'GeoTIFF-BigTIFF', pm) # Classification to vector ds = gdal.Open(str(outfile + ".tif")) rasterband = ds.GetRasterBand(1) dst_layername = outfile + "_Iceberg_outline" drv = ogr.GetDriverByName("GeoJSON") dst_ds = drv.CreateDataSource(dst_layername + ".geojson") dest_srs = ogr.osr.SpatialReference() dest_srs.ImportFromEPSG(4326) dst_layer = dst_ds.CreateLayer(dst_layername, dest_srs) gdal.Polygonize(rasterband, rasterband, dst_layer, -1, [], callback=None) # (input, mask, dest_layer,,,)
def bandMathSnap(input_dim, output_file, expression_list, format_file='float32'): if debug >= 2: print(cyan + "bandmathSnap() : " + bold + green + "Import Dim to SNAP : " + endC + input_dim) # Info input file product = ProductIO.readProduct(input_dim) width = product.getSceneRasterWidth() height = product.getSceneRasterHeight() name = product.getName() description = product.getDescription() band_names = product.getBandNames() if debug >= 2: print(cyan + "bandmathSnap() : " + bold + green + "Product: %s, %d x %d pixels, %s" % (name, width, height, description) + endC) print(cyan + "bandmathSnap() : " + bold + green + "Bands: %s" % (list(band_names)) + endC) # Instance de GPF GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() # Def operateur SNAP operator = 'BandMaths' BandDescriptor = jpy.get_type( 'org.esa.snap.core.gpf.common.BandMathsOp$BandDescriptor') targetBands = jpy.array( 'org.esa.snap.core.gpf.common.BandMathsOp$BandDescriptor', len(expression_list)) # Get des expressions d'entréées i = 0 for expression in expression_list: targetBand = BandDescriptor() targetBand.name = 'band_' + str(i + 1) targetBand.type = format_file targetBand.expression = expression targetBands[i] = targetBand i += 1 # Set des parametres parameters = HashMap() parameters.put('targetBands', targetBands) # Get snappy Operators result = GPF.createProduct(operator, parameters, product) ProductIO.writeProduct(result, output_file, 'BEAM-DIMAP') if debug >= 2: print(cyan + "bandmathSnap() : " + bold + green + "Writing Done : " + endC + str(output_file)) return result
def extract_values(self, file): if not exists(self.plots): mkdir(self.plots) coords = [] with open(file, 'r') as f: for line in f: line = line.replace('\n', '') coords.append([float(x) for x in line.split(' ')]) GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() HashMap = jpy.get_type('java.util.HashMap') Coords = jpy.array('org.esa.snap.pixex.Coordinate', len(coords)) Coord = jpy.get_type('org.esa.snap.pixex.Coordinate') for ind, coord in enumerate(coords): c = Coord('Coord{}'.format(ind), coord[0], coord[1], None) Coords[ind] = c parameters = HashMap() parameters.put('exportBands', True) parameters.put('exportTiePoints', False) parameters.put('exportMasks', False) parameters.put('coordinates', Coords) parameters.put('outputDir', '.') pre = self._extract_values(parameters, self.product_pre) post = self._extract_values(parameters, self.product_post) waves = pre.meta['comments'][-1].replace('\t', ' ') waves = waves.replace('Wavelength:', '').split(' ') waves = filter(lambda x: x != '', waves) waves = [float(x) for x in waves] waves = filter(lambda x: x != 0, waves) bands = ['B{}'.format(ind) for ind in range(1, 9)] bands += ['B8A', 'B9'] bands += ['B{}'.format(ind) for ind in range(11, 13)] print(pre.colnames) print(post.colnames) for ind in range(len(pre)): f, ax = plt.subplots() ax.set_xlabel('Wavelength (nm)') ax.set_ylabel('dl') radiances = list(pre[bands][ind]) ax.plot(waves, radiances, color='g', label='pre') ax.scatter(waves, radiances, color='g') radiances = list(post[bands][ind]) ax.plot(waves, radiances, color='b', label='post') ax.scatter(waves, radiances, color='b') lat = pre['Latitude'][ind] lon = pre['Longitude'][ind] ax.set_title("{}, {}".format(lat, lon)) plt.legend() save = "{}/{}.pdf".format(self.plots, pre['Name'][ind]) f.savefig(save, bbox_inches="tight")
def listParams(operator_name): GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() op_spi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi( operator_name) print('Op name:', op_spi.getOperatorDescriptor().getName()) print('Op alias:', op_spi.getOperatorDescriptor().getAlias()) param_Desc = op_spi.getOperatorDescriptor().getParameterDescriptors() for param in param_Desc: print(param.getName())
def do_resampling (source): print ('\tResampling ...') HashMap = jpy.get_type('java.util.HashMap') parameters = HashMap() GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() parameters.put('targetResolution', 10) output = GPF.createProduct('Resample', parameters, source) return output
def c2rcc_params(): GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() op_spi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi('c2rcc.msi') print(dir(op_spi)) print('Op name:', op_spi.getOperatorDescriptor().getName()) print('Op alias:', op_spi.getOperatorDescriptor().getAlias()) param_Desc = op_spi.getOperatorDescriptor().getParameterDescriptors() for param in param_Desc: print(param.getName(), "or", param.getAlias())
def preprocesado(): ##Aplicar correccion orbital global product global product_calibrated global HashMap print(product) parameters = HashMap() GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() parameters.put('orbitType', 'Sentinel Precise (Auto Download)') parameters.put('polyDegree', '3') parameters.put('continueOnFail', 'false') apply_orbit_file = GPF.createProduct('Apply-Orbit-File', parameters, product) ##Recortar la imagen r = shapefile.Reader(archivo_shape) g = [] for s in r.shapes(): g.append(pygeoif.geometry.as_shape(s)) m = pygeoif.MultiPoint(g) wkt = str(m.wkt).replace("MULTIPOINT", "POLYGON(") + ")" #Usar el shapefile para cortar la imagen SubsetOp = snappy.jpy.get_type('org.esa.snap.core.gpf.common.SubsetOp') bounding_wkt = wkt geometry = WKTReader().read(bounding_wkt) HashMap = snappy.jpy.get_type('java.util.HashMap') GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() parameters = HashMap() parameters.put('copyMetadata', True) parameters.put('geoRegion', geometry) product_subset = snappy.GPF.createProduct('Subset', parameters, apply_orbit_file) #Mostrar las dimensiones de la imagen width = product_subset.getSceneRasterWidth() print("Width: {} px".format(width)) height = product_subset.getSceneRasterHeight() print("Height: {} px".format(height)) band_names = product_subset.getBandNames() print("Band names: {}".format(", ".join(band_names))) band = product_subset.getBand(band_names[0]) print(band.getRasterSize()) #plotBand(product_subset, "Intensity_VV", 0, 100000) ##Aplicar la calibracion de la imagen parameters = HashMap() parameters.put('outputSigmaBand', True) parameters.put('sourceBands', 'Intensity_VV') parameters.put('selectedPolarisations', "VV") parameters.put('outputImageScaleInDb', False) product_calibrated = GPF.createProduct("Calibration", parameters, product_subset) #plotBand(product_calibrated, "Sigma0_VV", 0, 1) print("PREPROCESAMIENTO HECHO EXITOSAMENTE")
def subset(product, x, y, width, heigth, toPrint=True): # subset of the Sentinel-1 GRD product by specify a rectangle whose top most left corner is defined by x and y coordinates HashMap = jpy.get_type('java.util.HashMap') GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() parameters = HashMap() parameters.put('copyMetadata', True) parameters.put('region', "%s,%s,%s,%s" % (x, y, width, height)) subset = GPF.createProduct('Subset', parameters, product) if toPrint: print("Bands: %s" % (list(subset.getBandNames()))) return subset
def do_biophysical_parameter (source): print ('\tBiophysical Parameters ...') HashMap = jpy.get_type('java.util.HashMap') parameters = HashMap() GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() parameters.put('targetResolution', 10) parameters.put('computeLAI', True) ##parameters.put('computeFcover', True) output = GPF.createProduct('BiophysicalOp', parameters, source) return output
def Subset(data, x, y, w, h): print('Subsetting the image...') HashMap = jpy.get_type('java.util.HashMap') GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() parameters = HashMap() parameters.put('copyMetadata', True) parameters.put('region', "%s,%s,%s,%s" % (x, y, w, h)) return GPF.createProduct('Subset', parameters, data)
def ApplyOrbitFile(data): print('Aplying Orbit File...') parameters = HashMap() GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() parameters.put('orbitType', 'Sentinel Precise (Auto Download)') parameters.put('polyDegree', '3') parameters.put('continueOnFail', 'false') return GPF.createProduct('Apply-Orbit-File', parameters, data)
def BandMathList(stack): product = ProductIO.readProduct(stack) band_names = product.getBandNames() GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() BandDescriptor = jpy.get_type( 'org.esa.snap.core.gpf.common.BandMathsOp$BandDescriptor') bandlist = list(band_names) #targetBands = list() x = 0 y = 1 bandlength = len(bandlist) runs = (bandlength - 1) targetBands = jpy.array( 'org.esa.snap.core.gpf.common.BandMathsOp$BandDescriptor', runs) for i in bandlist: while y <= runs: #print('{}_minus_{}'.format(bandlist[x], bandlist[y])) #targetBand1 = '{}_minus_{}'.format(bandlist[x], bandlist[y]) targetBand1 = BandDescriptor() targetBand1.name = '{}_minus_{}'.format(bandlist[x], bandlist[y]) targetBand1.type = 'float32' targetBand1.expression = '(({} - {})<(-2))? 255 : 0'.format( bandlist[x], bandlist[y]) print("Writing Band {} : {}_minus_{}".format( x, bandlist[x], bandlist[y])) #targetBands.append(targetBand1) targetBands[x] = targetBand1 x = x + 1 y = y + 1 """targetBand1 = BandDescriptor() targetBand1.name = 'first_{}_minus_last_{}'.format(bandlist[0], bandlist[bandlength]) targetBand1.type = 'float32' targetBand1.expression = '(({} - {})<(-2))? 255 : 0'.format(bandlist[x], bandlist[y]) print("Writing Band first_{}_minus_last_{}".format(bandlist[0], bandlist[bandlength]) targetBands[bandlength] = targetBand1""" parameters = HashMap() parameters.put('targetBands', targetBands) result = GPF.createProduct('BandMaths', parameters, product) print("Writing...") ProductIO.writeProduct(result, 'BandMaths.dim', 'BEAM-DIMAP') print("BandMaths.dim Done.") ProductIO.writeProduct(result, 'BandMaths.tif', "GeoTIFF-BigTIFF") print("BandMaths.tif Done.")
def __init__(self): # HashMap # Key-Value pairs. # https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html self.HashMap = jpy.get_type('java.util.HashMap') # Get snappy Operators GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() # Variables # Describes a target band to be generated by this operator. # http://step.esa.int/docs/v2.0/apidoc/engine/org/esa/snap/core/gpf/common/BandMathsOp.BandDescriptor.html self.Variables = jpy.get_type( 'org.esa.snap.core.gpf.common.MosaicOp$Variable')
def __init__(self, product, wkt_footprint, working_dir, external_dem_dir): """Prepare to use SNAPPY as a subprocess This class prepares commands and runs SNAPPY as a python3.4 subprocess """ self.working_dir = working_dir self.product_meta = product self.wkt_footprint = wkt_footprint self.dem_dir = external_dem_dir GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() # Set object parameterisation dictionary self.HashMap = jpy.get_type('java.util.HashMap') # Set start time and loop counter self.start_time = datetime.datetime.now() # for calculation self.start_time_string = self.start_time.strftime("%Y-%m-%d %H:%M:%S") print("Processing start time:", self.start_time) self.name = self.product_meta['name'] self.name_with_safe = self.name + '.SAFE' self.product_path = os.path.join(self.working_dir, self.name + '.zip') self.preprocess_path = working_dir self.manifest_path = os.path.join(self.working_dir, self.name_with_safe, 'manifest.safe') # for rs2 self.productxml_path = os.path.join(self.working_dir, self.name, 'product.xml') # Read S1 raw data product and assigns source bands for given file # readProduct(File file, String... formatNames) if product['name'].startswith("S1"): self.dataproduct_r = snappy.ProductIO.readProduct(self.manifest_path) # self.srcbands = ["Intensity_VV", "Intensity_VH", "Amplitude_VV", "Amplitude_VH"] self.srcbands = ["Intensity_VV", "Intensity_VH"] print("Reading S1 data product with polarization bands:", self.srcbands) # Read RS2 raw data product and assigns source bands for given file else: self.dataproduct_r = snappy.ProductIO.readProduct(self.productxml_path) # self.srcbands = ["Intensity_VV", "Intensity_VH", "Amplitude_VV", "Amplitude_VH"] print("Reading RS2 data product with polarization bands:", self.srcbands) self.intermediate_product = None self.operations_list = []
def get_operator_help(operator): """This function prints the human readable information about a SNAP operator Args: operator: SNAP operator Returns The human readable information about the provided SNAP operator. Raises: None. """ op_spi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(operator) logging.info('Operator name: {}'.format(op_spi.getOperatorDescriptor().getName())) logging.info('Operator alias: {}\n'.format(op_spi.getOperatorDescriptor().getAlias())) logging.info('Parameters:\n') param_Desc = op_spi.getOperatorDescriptor().getParameterDescriptors() for param in param_Desc: logging.info('{}: {}\nDefault Value: {}\n'.format(param.getName(), param.getDescription(), param.getDefaultValue())) logging.info('Possible values: {}\n').format(list(param.getValueSet()))
def get_snap_parameters(operator): op_spi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(operator) op_params = op_spi.getOperatorDescriptor().getParameterDescriptors() return op_params
def _resample(self, name): p = ProductIO.readProduct(name) # path of the xml file GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() HashMap = jpy.get_type('java.util.HashMap') parameters = HashMap() parameters.put('targetResolution', 10) parameters.put('upsampling', 'Nearest') parameters.put('downsampling', 'First') parameters.put('upsampling', 'Nearest') parameters.put('flagDownsampling', 'First') parameters.put('resampleOnPyramidLevels', True) product = GPF.createProduct('Resample', parameters, p) return product
def convertDim2Tiff(input_dim, output_file, name_file, format_file='float32', type_file='GeoTIFF'): if debug >= 2: print(cyan + "convertDim2Tiff() : " + bold + green + "Import Dim to SNAP : " + endC + input_dim) # Info input file product = ProductIO.readProduct(input_dim) band = product.getBand(name_file) width = product.getSceneRasterWidth() height = product.getSceneRasterHeight() # Instance de GPF GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() # Def operateur SNAP operator = 'BandMaths' BandDescriptor = jpy.get_type( 'org.esa.snap.core.gpf.common.BandMathsOp$BandDescriptor') targetBands = jpy.array( 'org.esa.snap.core.gpf.common.BandMathsOp$BandDescriptor', 1) # Get des expressions d'entréées targetBand = BandDescriptor() targetBand.name = 'band_0' targetBand.type = format_file targetBand.expression = name_file targetBands[0] = targetBand # Set des parametres parameters = HashMap() parameters.put('targetBands', targetBands) result = GPF.createProduct(operator, parameters, product) ProductIO.writeProduct(result, output_file, type_file) if debug >= 2: print(cyan + "convertDim2Tiff() : " + bold + green + "Writing Done : " + endC + str(output_file)) return
sys.exit(1) file = sys.argv[1] print("Reading...") product = ProductIO.readProduct(file) width = product.getSceneRasterWidth() height = product.getSceneRasterHeight() name = product.getName() description = product.getDescription() band_names = product.getBandNames() print("Product: %s, %d x %d pixels, %s" % (name, width, height, description)) print("Bands: %s" % (list(band_names))) GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() HashMap = jpy.get_type('java.util.HashMap') BandDescriptor = jpy.get_type('org.esa.snap.core.gpf.common.BandMathsOp$BandDescriptor') targetBand1 = BandDescriptor() targetBand1.name = 'band_1' targetBand1.type = 'float32' targetBand1.expression = '(radiance_10 - radiance_7) / (radiance_10 + radiance_7)' targetBand2 = BandDescriptor() targetBand2.name = 'band_2' targetBand2.type = 'float32' targetBand2.expression = '(radiance_9 - radiance_6) / (radiance_9 + radiance_6)' targetBands = jpy.array('org.esa.snap.core.gpf.common.BandMathsOp$BandDescriptor', 2)