def speckleFilter(product): parameters = HashMap() filterSizeY = '5' filterSizeX = '5' parameters.put('sourceBands', 'Sigma0_VV') parameters.put('filter', 'Lee') parameters.put('filterSizeX', filterSizeX) parameters.put('filterSizeY', filterSizeY) parameters.put('dampaingFactor', '2') parameters.put('estimateENL', 'true') parameters.put('enl', '1.0') parameters.put('numLooksStr', '1') parameters.put('targetWindowSizeStr', '3x3') parameters.put('sigmaStr', '0.9') parameters.put('anSize', '50') return GPF.createProduct('Speckle-Filter', parameters, product)
def do_calibration(source, polarization, pols): print('\tCalibration...') parameters = HashMap() parameters.put('outputSigmaBand', True) if polarization == 'DH': parameters.put('sourceBands', 'Intensity_HH,Intensity_HV') elif polarization == 'DV': parameters.put('sourceBands', 'Intensity_VH,Intensity_VV') elif polarization == 'SH' or polarization == 'HH': parameters.put('sourceBands', 'Intensity_HH') elif polarization == 'SV': parameters.put('sourceBands', 'Intensity_VV') else: print("different polarization!") parameters.put('selectedPolarisations', pols) parameters.put('outputImageScaleInDb', False) output = GPF.createProduct("Calibration", parameters, source) return output
def resize(sarImgDir, imgDst=None, maxSize=400): ''' Get water body of reservoir from a tif image :type sarImgDir: string :type imgDst: string :type maxSize: int :param sarImgDir: directory to sentinel-1 .tif image :param imgDst: directory to resized image. If none, use default name :param maxSize: maximum value of width and height after resizing :return: string - directory to resized image ''' import math from snappy import jpy from snappy import ProductIO from snappy import GPF from snappy import HashMap GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() HashMap = jpy.get_type('java.util.HashMap') p = ProductIO.readProduct(sarImgDir) firstBand = p.getBands()[0] width = firstBand.getRasterWidth() height = firstBand.getRasterHeight() ratio = width / height parameters = HashMap() if ratio <= 1: parameters.put('targetHeight', maxSize) parameters.put('targetWidth', math.ceil(maxSize * ratio)) else: parameters.put('targetWidth', maxSize) parameters.put('targetHeight', math.ceil(maxSize / ratio)) product = GPF.createProduct('Resample', parameters, p) if imgDst is None: sourceName = imgDir.split('/')[:-4] imgDst = sourceName + '_resized.tif' ProductIO.writeProduct(product, imgDst, 'GeoTiff') del p, product return imgDst
def get_glcm_config(): parameters = HashMap() parameters.put("windowSizeStr", "11x11") parameters.put("angleStr", "ALL") parameters.put("quantizerStr", "Probabilistic Quantizer") parameters.put("quantizationLevelsStr", "32") parameters.put("displacement", 4) # features of GLCM parameters.put("outputContrast", True) parameters.put("outputDissimilarity", False) parameters.put("outputHomogeneity", False) parameters.put("outputASM", False) parameters.put("outputEnergy", False) parameters.put("outputMAX", False) parameters.put("outputEntropy", False) parameters.put("outputMean", True) parameters.put("outputVariance", True) parameters.put("outputCorrelation", False) return parameters
def SpeckleFilter(data, source_band, filter, filterSizeX, filterSizeY): print('Aplying the Speckle Filter...') parameters = HashMap() parameters.put('sourceBands', source_band) parameters.put('filter', filter) parameters.put('filterSizeX', '%s' % (filterSizeX)) parameters.put('filterSizeY', '%s' % (filterSizeY)) parameters.put('dampingFactor', '2') parameters.put('estimateENL', 'true') parameters.put('enl', '1.0') parameters.put('numLooksStr', '1') parameters.put('targetWindowSizeStr', '3x3') parameters.put('sigmaStr', '0.9') parameters.put('anSize', '50') return GPF.createProduct('Speckle-Filter', parameters, data)
def apply_rayleigh_correction(product, bands): #Must be BEAM-DIMAP product or will throw null pointer error parameters = HashMap() bands_string = "" for band in bands: bands_string += band + "," bands_string = bands_string[:-1] #print(bands_string) parameters.put("sourceBandNames", bands_string) parameters.put("computeTaur", "false") parameters.put("computeRBrr", "true") parameters.put("computeRtoa", "false") parameters.put("addAirMass", "false") parameters.put("s2MsiTargetResolution", 20) parameters.put("s2MsiSeaLevelPressure", 1013.25) parameters.put("s2MsiOzone", 300.0) rayleigh_output = GPF.createProduct('RayleighCorrection', parameters, product) return rayleigh_output
def applyingOrbitFile(product): if debug >= 2: print(cyan + "applyingOrbitFile() : " + bold + green + "Run to SNAP... " + endC) # Get input file #product = ProductIO.readProduct(input_dim) # Instance de GPF GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() # Def operateur SNAP operator = 'Apply-Orbit-File' # 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 + "applyingOrbitFile() : " + bold + green + str(param.getName()) + " : " + str(param.getDefaultValue()) + endC) parameters.put(param.getName(), param.getDefaultValue()) #parameters.put("Orbit State Vectors", "Sentinel Precise (Auto Download)") #parameters.put("Polynomial Degree", 3) if debug >= 2: print(parameters) # Get snappy Operators result = GPF.createProduct(operator, parameters, product) #ProductIO.writeProduct(result, output_file, 'BEAM-DIMAP') if debug >= 2: print(cyan + "applyingOrbitFile() : " + bold + green + "Done... " + endC) return result
def reproject(self, epsg): """ Get the corner coordinates from the opened satellite image. Fetches a list of latitude and longitude values for the boundary of a given satellite product with a given pixel step along the border. Args: (self.product): The snappy product opened using snappy. step (int): the step size in pixels Returns: (list): a list containing the boundary coordinates.""" # Empty HashMap parameters = HashMap() # Snap operator parameters for reprojection parameters.put("addDeltaBands", "false") parameters.put("crs", str(epsg)) parameters.put("resampling", "Nearest") parameters.put("noDataValue", "-9999") parameters.put("orthorectify", "false") parameters.put("pixelSizeX", 300.0) parameters.put("pixelSizeY", 300.0) # Check if the image rasters are all the same size, if not, offer to # resample if self.product.isMultiSize(): raise ValueError("Product contains bands of different sizes and" " can not be " "processed. Resampling neccessary so that all" " rasters have the same size.") # TODO add an option to resample or not else: # Call the operator depending on the resample reprojProd = GPF.createProduct("Reproject", parameters, self.product) # Update product self.product = reprojProd # Close dataset reprojProd = None
def compute_vegeation_index(product, index): index = ''.join(index) 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 = index targetBand.type = 'float32' targetBand.expression = indices_expr[index] targetBands = jpy.array( 'org.esa.snap.core.gpf.common.BandMathsOp$BandDescriptor', 1) targetBands[0] = targetBand parameters = HashMap() parameters.put('targetBands', targetBands) print("Start to compute:" + indices_expr[index]) result = GPF.createProduct('BandMaths', parameters, product) print('Expression computed: ' + indices_expr[index]) print result.getBand(index) return result.getBand(index)
def do_sar_mosaic(products): # Object to hold parameters parameters = HashMap() # SNAP SAR Mosaic parameters parameters.put('resamplingMethod', 'BILINEAR_INTERPOLATION') parameters.put('average', 'false') parameters.put('normalizeByMean', 'false') parameters.put('gradientDomainMosaic', 'false') parameters.put('pixelSize', '10.0') parameters.put('sceneWidth', '9407') parameters.put('sceneHeight', '6661') parameters.put('feather', '0') parameters.put('maxIterations', '5000') parameters.put('convergenceThreshold', '1.0E-4') # Applies SAR Mosaic to create a single product output = GPF.createProduct('SAR-Mosaic', parameters, products) return output
def do_terrain_correction(product): # Object to hold parameters parameters = HashMap() # Modify to fit the projection of the images proj = 'PROJCS["UTM Zone 14 / World Geodetic System 1984",GEOGCS["World Geodetic System 1984",DATUM["World Geodetic System 1984",SPHEROID["WGS 84", 6378137.0, 298.257223563, AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich", 0.0, AUTHORITY["EPSG","8901"]],UNIT["degree", 0.017453292519943295],AXIS["Geodetic longitude", EAST],AXIS["Geodetic latitude", NORTH]],PROJECTION["Transverse_Mercator"],PARAMETER["central_meridian", -99.0],PARAMETER["latitude_of_origin", 0.0],PARAMETER["scale_factor", 0.9996],PARAMETER["false_easting", 500000.0],PARAMETER["false_northing", 0.0],UNIT["m", 1.0],AXIS["Easting", EAST],AXIS["Northing", NORTH]]' # SNAP Terrain Correction parameters parameters.put('demName', 'SRTM 1Sec HGT') parameters.put('externalDEMNoDataValue', '0.0') parameters.put('externelDEMApplyEGM', 'true') parameters.put('demResamplingMethod', 'BILINEAR_INTERPOLATION') parameters.put('imgResamplingMethod', 'BILINEAR_INTERPOLATION') parameters.put('pixelSpacingInMeter', '10.0') parameters.put('pixelSpacingInDegree', '0.0') parameters.put('mapProjection', proj) parameters.put('alignToStandardGrid', 'false') parameters.put('standardGridOriginX', '0.0') parameters.put('standardGridOriginY', '0.0') parameters.put('noDataValueAtSea', 'true') parameters.put('saveDEM', 'false') parameters.put('saveLatLon', 'false') parameters.put('saveIncidenceAngleFromEllipsoid', 'false') parameters.put('saveLocalIncidenceAngle', 'false') parameters.put('saveProjectedLocalIncidenceAngle', 'false') parameters.put('saveSelectedSourceBand', 'true') parameters.put('outputComplex', 'false') parameters.put('applyRadiometricNormalization', 'false') parameters.put('saveSigmaNought', 'false') parameters.put('saveGammaNought', 'false') parameters.put('saveBetaNought', 'false') parameters.put('incidenceAngleForSigma0', 'Use projected local incidence angle from DEM') parameters.put('incidenceAngleForGamma0', 'Use projected local incidence angle from DEM') parameters.put('auxFile', 'Latest Auxiliary File') # Applies Terrain Correction to given product output = GPF.createProduct('Terrain-Correction', parameters, product) return output
def do_speckle_filter(product): # Object to hold parameters parameters = HashMap() # SNAP Speckle Filter parameters parameters.put('filter', 'Boxcar') parameters.put('filterSizeX', '5') parameters.put('filterSizeY', '5') parameters.put('dampingFactor', '2') parameters.put('estimateENL', 'true') parameters.put('enl', '1.0') parameters.put('numLooksStr', '1') parameters.put('windowSize', '7x7') parameters.put('targetWindowSizeStr', '3x3') parameters.put('sigmaStr', '0.9') parameters.put('anSize', '50') # Applies Speckle Filter to given product output = GPF.createProduct('Speckle-Filter', parameters, product) return output
def idepix_cloud(in_prod, xpix, ypix): """ Run the experimental cloud over snow processor. The function is written based on the Idepix cloud 1.0 plugin. The function returns the values from the Ideoix cloud over snow band in the Idepix processor output. Args: inprod (java.lang.Object): snappy java object: SNAP image product xpix (float): x position in product to query ypix (float): y position in product to query """ parameters = HashMap() parameters.put("demBandName", "band_1") idepix_cld = GPF.createProduct("Snap.Idepix.Olci.S3Snow", parameters, in_prod) cloudband = idepix_cld.getBand("cloud_over_snow") cloudband.loadRasterData() return cloudband.getPixelInt(xpix, ypix)
def get_cross_correlation_config(): parameters = HashMap() parameters.put("numGCPtoGenerate", 2000) parameters.put("coarseRegistrationWindowWidth", 128) parameters.put("coarseRegistrationWindowHeight", 128) parameters.put("rowInterpFactor", 4) parameters.put("columnInterpFactor", 4) parameters.put("maxIteration", 10) parameters.put("gcpTolerance", 0.25) parameters.put("applyFineRegistration", True) parameters.put("inSAROptimized", True) parameters.put("fineRegistrationWindowWidth", 32) parameters.put("fineRegistrationWindowHeight", 32) parameters.put("fineRegistrationWindowAccAzimuth", 16) parameters.put("fineRegistrationWindowAccRange", 16) parameters.put("fineRegistrationOversampling", 16) parameters.put("coherenceWindowSize", 3) parameters.put("coherenceThreshold", 0.6) parameters.put("useSlidingWindow", False) parameters.put("computeOffset", False) parameters.put("onlyGCPsOnLand", False) return parameters
def Enhanced_Spectral_Diversity(product): parameters = HashMap() # parameters.put("fineWinWidthStr2",512) # parameters.put("fineWinHeightStr",512) # parameters.put("fineWinAccAzimuth",16) # parameters.put("fineWinAccRange",16) # parameters.put("fineWinOversampling",128) # parameters.put("xCorrThreshold",0.1) # parameters.put("cohThreshold",0.3) # parameters.put("numBlocksPerOverlap",10) # parameters.put("esdEstimator",'Periodogram') # parameters.put("weightFunc",'Inv Quadratic') # parameters.put("temporalBaselineType",'Number of images') # parameters.put("maxTemporalBaseline",4) # parameters.put("integrationMethod",'L1 and L2') # parameters.put("doNotWriteTargetBands",False) # parameters.put("useSuppliedRangeShift",False) # parameters.put("overallRangeShift",0) # parameters.put("useSuppliedAzimuthShift",False) # parameters.put("overallAzimuthShift",0) return GPF.createProduct("Enhanced-Spectral-Diversity", parameters, 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
def BandMath(stack): product = ProductIO.readProduct(stack) band_names = product.getBandNames() print(list(band_names)) band1 = input("Enter Band 1:") band2 = input("Enter Band 2 which will be subtracted:") GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() ## Band Math targetBands = jpy.array( 'org.esa.snap.core.gpf.common.BandMathsOp$BandDescriptor', 2) #print('{}_minus_{}'.format(bandlist[x], bandlist[y])) targetBand1 = BandDescriptor() targetBand1.name = '{}_minus_{}'.format(band1, band2) targetBand1.type = 'float32' #targetBand1.expression = '(({} - {})<(-2))? 255 : 0'.format(band1, band2) targetBand1.expression = '(({} - {})<(-2))? 255 : 0'.format(band1, band2) parameters = HashMap() parameters.put('targetBands', targetBands) result = GPF.createProduct('BandMaths', parameters, product) print("Writing...") ProductIO.writeProduct(result, '{}_minus_{}.dim'.format(band1, band2), 'BEAM-DIMAP') print('{}_minus_{}.dim Done.'.format(band1, band2))
def get_terrain_correction_config(map_projection): parameters = HashMap() parameters.put("demResamplingMethod", "BILINEAR_INTERPOLATION") parameters.put("imgResamplingMethod", "BILINEAR_INTERPOLATION") parameters.put("externalDEMApplyEGM", True) parameters.put("externalDEMNoDataValue", 0.0) parameters.put("demName", SRTM1SEC) # ~25 to 30m parameters.put("alignToStandardGrid", False) parameters.put("saveDEM", False) parameters.put("saveLatLon", False) parameters.put("saveIncidenceAngleFromEllipsoid", False) parameters.put("saveLocalIncidenceAngle", False) parameters.put("saveProjectedLocalIncidenceAngle", False) parameters.put("outputComplex", False) parameters.put("saveSelectedSourceBand", True) parameters.put("standardGridOriginX", 0.0) parameters.put("standardGridOriginY", 0.0) parameters.put("nodataValueAtSea", True) parameters.put("outputComplex", False) parameters.put("saveSigmaNought", False) parameters.put("incidenceAngleForSigma0", "Use projected local incidence angle from DEM") parameters.put("mapProjection", map_projection) return parameters
def subset_s2(path, file, aoi): # Read Data________________________________________________________________ print("SUBSET: Read Product...") sentinel = ProductIO.readProduct(path+file) print("SUBSET: Done reading!") # Get Band Names and print info name = sentinel.getName() print("SUBSET: Image ID: %s" % name) band_names = sentinel.getBandNames() print("SUBSET: Bands: %s" % (list(band_names))) # Preprocessing ___________________________________________________________ # Resampling parameters = HashMap() parameters.put('targetResolution', 10) print("SUBSET: resample target resolution: 10m") product_resample = snappy.GPF.createProduct('Resample', parameters, sentinel) # Geojson to wkt with open(aoi) as f: gjson = json.load(f) for feature in gjson['features']: polygon = (feature['geometry']) str_poly = json.dumps(polygon) gjson_poly = geojson.loads(str_poly) poly_shp = shape(gjson_poly) wkt = poly_shp.wkt # Subset geom = WKTReader().read(wkt) op = SubsetOp() op.setSourceProduct(product_resample) op.setGeoRegion(geom) product_sub = op.getTargetProduct() # Write Data_______________________________________________________ print("SUBSET: Writing subset.") subset = path + name + '_subset_' ProductIO.writeProduct(product_sub, subset, "BEAM-DIMAP") print("SUBSET: Done and saved in %s" % path)
def rad2refl( inprod, sensor="OLCI", mode="RAD_TO_REFL", tpg="False", flags="False", nonspec="False", ): """ Radiance to Reflectance. Convert a Sentinel 3 OLCI L1C radiance bands to TOA reflectance. Args: inprod (java.lang.Object): snappy java object: SNAP image product sensor (str): satellite sensor that produced the input scene tpg (str): include or not the TiePointGrids in output flags (str): include or not the Product flags in output nonspec (str): include or not the non spectral bands in output Returns: toa_refl (java.lang.Object): snappy TOA reflectance product """ # Empty HashMap parameters = HashMap() # Put parameters for snow albedo processor parameters.put("sensor", sensor) parameters.put("conversionMode", mode) parameters.put("copyTiePointGrids", tpg) parameters.put("copyFlagBandsAndMasks", flags) parameters.put("copyNonSpectralBands", nonspec) toa_refl = GPF.createProduct("Rad2Refl", parameters, inprod) return toa_refl
def resample(imgDir): import math from snappy import jpy from snappy import ProductIO from snappy import GPF from snappy import HashMap GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() HashMap = jpy.get_type('java.util.HashMap') p = ProductIO.readProduct(imgDir) firstBand = p.getBands()[0] width = firstBand.getRasterWidth() height = firstBand.getRasterHeight() ratio = width/height parameters = HashMap() parameters.put('targetHeight', 1000) parameters.put('targetWidth', math.ceil(1000*ratio)) product = GPF.createProduct('Resample', parameters, p) sourceName = imgDir.split('/')[-1] targetDir = '../DataResampled/' + sourceName ProductIO.writeProduct(product, targetDir, 'GeoTiff') return targetDir
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
### SUBSET WKTReader = snappy.jpy.get_type('com.vividsolutions.jts.io.WKTReader') # wkt = "POLYGON((12.76221 53.70951, " \ # "12.72085 54.07433, " \ # "13.58674 54.07981, " \ # "13.59605 53.70875, " \ # "12.76221 53.70951))" wkt = "POLYGON((19.277 59.113, " \ "19.277 59.463, " \ "17.628 59.463, " \ "17.628 59.113, " \ "19.277 59.113))" geom = WKTReader().read(wkt) param_sub = HashMap() param_sub.put('geoRegion', geom) param_sub.put('outputImageScaleInDb', False) print("Subset...") sub = GPF.createProduct("Subset", param_sub, flt) ProductIO.writeProduct(sub, saveNamePrefix + "tpr_ml204_flt_sub", 'BEAM-DIMAP', pm) ### Terrain-Correction print("Terrain-Correction...") TC = GPF.createProduct("Terrain-Correction", parameters, flt) ProductIO.writeProduct(TC, saveNamePrefix + "tpr_ml204_flt_sub_TC80", 'BEAM-DIMAP', pm) print("================ finished! ==================")
def Multilook_config(): parameters = HashMap() parameters.put("GR Square Pixel", True) parameters.put("nRgLooks", 8) parameters.put("nAzLooks", 2) return parameters
def TOPSAR_Deburst_config(): parameters = HashMap() parameters.put('selectedPolarisations', 'VV') return parameters
def ApplyOrbitFile_config(): parameters = HashMap() parameters.put('orbitType', 'Sentinel Precise (Auto Download)') parameters.put('polyDegree', 3) parameters.put('continueOnFail', True) return parameters
def SliceAssembly_config(): parameters = HashMap() parameters.put('selectedPolarizations', 'VV') return parameters
def CreateStack_config(): parameters = HashMap() parameters.put("resamplingType", "NONE") parameters.put("extent", "Master") parameters.put("initialOffsetMethod", "Product Geolocation") return parameters
def RadiometricCalibration_config(): parameters = HashMap() parameters.put('outputSigmaBand', True) return parameters
def Default_config(): return HashMap()