def get_valid_mask(inprod, xx, yy): valid_mask = inprod.getMaskGroup().get("quality_flags_invalid") valid_mask_asmask = jpy.cast(valid_mask, Mask) return valid_mask_asmask.getSampleInt(xx, yy)
def getS3bands(in_file, coords, band_names, s3_instrument, slstr_res): """Extract data from Sentinel-3 bands. Read the input S3 file and extract data from a list of given bands for the coordinates (in a provided list) located within the scene. Args: in_file (str): Path to a S3 OLCI image xfdumanisfest.xml file. coords (list): List of coordinates to extract the data from. band_names (list): List of bands names to extract the data from. errorfile (str): Path to the file where all errors are logged. s3_instrument (str): Sentinel-3 instrument name (OLCI or SLSTR). slstr_res (str): SLSTR reader resolution (500m or 1km). Returns: (dict): Dictionnary containing the band names and values for all coordinates extracted from the image. """ # Make a dictionnary to store results stored_vals = {} # Open SNAP product prod = open_prod(in_file, s3_instrument, slstr_res) # Loop over coordinates to extract values. for coord in coords: # Check if data exists at the queried location # Transform lat/lon to position to x, y in scene xx, yy = pixel_position(prod, coord[1], coord[2]) # Log if location is outside of file if not xx or not yy: pass else: # For OLCI scenes, save resources by working on a small subset # around each coordinates pair contained within the S3 scene. # Doesn't process if the coordinates pair is not in the product. if s3_instrument == "OLCI": try: prod_subset, pix_coords = subset(prod, coord[1], coord[2]) process_flag = True # Set a flag to process data except: # Bare except needed to catch the JAVA exception prod_subset = None if not prod_subset or pix_coords[0] is None: process_flag = False # None to stop processing else: # If SLSTR, open full image: because of the bands at different # resolutions, a resampling would be necessary before being # able to subset. Therefore set the flag to continue. prod_subset = prod process_flag = True # As th entire scene is used, set pix_coords to xx, yy pix_coords = xx, yy if process_flag: # Run the processing if OLCI subset exists # Before the processing, the validity of the opened product is # tested by opening the first band and querying the band at the # coordinate location. If SLSTR, just test the 500m product. # If the extraction test fails, an entry is created in the log. try: # Get a specified band depending on the sensor currentband = None if s3_instrument == "OLCI": # Extract pixel value for the band currentband = prod_subset.getBand("Oa01_radiance") else: # Try out with bands for either resolution currentband = prod_subset.getBand("S1_radiance_an") if currentband is None: currentband = prod_subset.getBand("F1_BT_in") currentband.loadRasterData() # Load raster band # Test if the retrieval is possible currentband.getPixelFloat(pix_coords[0], pix_coords[1]) currentband = None # Marker to continue processing processing = True except: # Bare except needed to catch the JAVA exception processing = False # Deactivate processing if processing: out_values = {} # Initialise outvalues # Extract bands from product for band in band_names: # Try to extract from band list if band in list(prod_subset.getBandNames()): currentband = None currentband = prod_subset.getBand(band) currentband.loadRasterData() out_values[band] = round( currentband.getPixelFloat( pix_coords[0], pix_coords[1]), 4, ) # If not in band list, try from TiePointGrid elif band in list(prod.getTiePointGridNames()): out_values[band] = round( getTiePointGrid_value( prod_subset, band, pix_coords[0], pix_coords[1], ), 4, ) # If not if TiePointGrid list try from Masks elif band in list( prod_subset.getMaskGroup().getNodeNames()): currentmask = prod_subset.getMaskGroup().get(band) currentmask_asmask = jpy.cast(currentmask, Mask) out_values[band] = currentmask_asmask.getSampleInt( pix_coords[0], pix_coords[1]) else: # Capture error raise SyntaxError( "Band '%s' does not exist in image: %s" % (band, prod.getName())) # Update the full dictionnary stored_vals.update({coord[0]: out_values}) # Garbage collector prod_subset = None # Garbage collector prod = None return stored_vals
bio_data = np.zeros( bioW * bioH, np.float32 ) #Return a new array of given shape and type, filled with zeros. Filled only x-ways. np.zeros(5) = {0,0,0,0,0} bioBand.readPixels( 0, 0, bioW, bioH, bio_data ) #readPixels(x,y,w,h, Array) x : x offset of upper left corner. y : y offset of upper left corner. w : width. h : height. Array : output array bio_data.shape = bioH, bioW # Prepare radar image r = ProductIO.readProduct(fileName) radarBand = r.getBand(bandName) radarW = radarBand.getRasterWidth() radarH = radarBand.getRasterHeight() # Initilization of raster band and geocoding for French Guyana and radar image raster_Band = jpy.cast(bioBand, RasterDataNode) raster_BandRadar = jpy.cast(radarBand, RasterDataNode) geo_Coding = jpy.cast(raster_Band.getGeoCoding(), GeoCoding) #get geocoding of biomass map geo_CodingRadar = jpy.cast(raster_BandRadar.getGeoCoding(), GeoCoding) #get geocoding of radar image # Create mask of ROI on French Guyana .tif polygon = pickle.load(open((maskPath + productName + 'Mask'), 'rb')) img = Image.new('L', (bioW, bioH), 0) ImageDraw.Draw(img).polygon(polygon, outline=1, fill=1) mask = np.array(img) imgplot = plt.imshow(mask) imgplot.write_png(productName + 'Mask.png')
# OpType can be one of {MIN, MAX, MEDIAN, MEAN, STDDEV, EROSION, DILATION, OPENING, CLOSING} opType = OpType.STDDEV iterationCount = 1 kernel_data = [ 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0 ] kernel = Kernel(9, 9, 4, 4, 1 / 64, kernel_data) filtered_band = GeneralFilterBand(filteredBandName, sourceRaster, opType, kernel, iterationCount) # Turn into real Band if realBand: target_band = Band(filtered_band.getName(), filtered_band.getDataType(), filtered_band.getRasterWidth(), filtered_band.getRasterHeight()) target_band.setSourceImage(filtered_band.getSourceImage()) else: target_band = filtered_band if isinstance(jpy.cast(sourceRaster, Band), Band): ProductUtils.copySpectralBandProperties(sourceRaster, target_band) product.addBand(target_band) ProductIO.writeProduct(product, out_file, 'BEAM-DIMAP')
bandName = 'band_1' savePath = 'D:/fyp-master/Polygon/' polygon = [] topLeftLat = 4.431921373298707 topLeftLon = -52.14877215477987 botLeftLat = 2.885133324526054 botLeftLon = -52.468809464281705 botRightLat = 3.051240184812927 botRightLon = -53.258843412884204 topRightLat = 4.59619348038011 topRightLon = -52.9405767847531 radarImage = ProductIO.readProduct(fileName) rasterBand = radarImage.getBand(bandName) rasterBio = jpy.cast(rasterBand, RasterDataNode) geo_CodingBio = jpy.cast(rasterBio.getGeoCoding(), GeoCoding) #Getting pixel positions #POLYGON ((-54.459992631546 1.8573631048202515, -54.823678525590225 3.605360746383667, -52.60408776706431 4.070178031921387, -52.24492652190336 2.3271737098693848, -54.459992631546 1.8573631048202515)) pixPos = getPixCoord(geo_CodingBio, topLeftLat, topLeftLon) print("Top Left: ", pixPos) polygon.append(pixPos) pixPos = getPixCoord(geo_CodingBio, botLeftLat, botLeftLon) print("Bot Left: ", pixPos) polygon.append(pixPos) pixPos = getPixCoord(geo_CodingBio, botRightLat, botRightLon) print("Bot Right: ", pixPos)