def request8(self): print("asdasd") betsiboka_bbox_large = BBox([45.88, -16.12, 47.29, -15.45], crs=CRS.WGS84) wms_true_color_request = WmsRequest(layer='AGRICULTURE', bbox=betsiboka_bbox_large, time='2015-12-01', width=960, image_format=MimeType.PNG, config=config) wms_true_color_img = wms_true_color_request.get_data() plot_image(wms_true_color_img[0]) plot_image(wms_true_color_img[1]) wms_true_color_request_with_deltat = WmsRequest( layer='AGRICULTURE', bbox=betsiboka_bbox_large, time='2015-12-01', width=960, image_format=MimeType.PNG, time_difference=datetime.timedelta(hours=2), config=config) wms_true_color_img = wms_true_color_request_with_deltat.get_data() print('These %d images were taken on the following dates:' % len(wms_true_color_img)) for index, date in enumerate( wms_true_color_request_with_deltat.get_dates()): print(' - image %d was taken on %s' % (index, date)) plot_image(wms_true_color_img[-1])
def get_data(lefttoplon, lefttoplat, rightbtmlon, rightbtmlat, time, maxcc=1, NDWI=True): """ Return the NDWI imageries given a bounding box and time """ if abs(lefttoplon) > 180 or abs(rightbtmlon) > 180: print("wrong longitude") return None if abs(lefttoplat) > 90 or abs(rightbtmlat) > 90: print("wrong latitude") return None if NDWI: layer = 'NDWI' else: layer = 'TRUE_COLOR' desired_coords_wgs84 = [lefttoplon, lefttoplat, rightbtmlon, rightbtmlat] desired_bbox = BBox(bbox=desired_coords_wgs84, crs=CRS.WGS84) wms_request = WmsRequest(layer=layer, bbox=desired_bbox, time=time, maxcc=maxcc, width=100, height=100, instance_id=INSTANCE_ID) wms_img = wms_request.get_data() return wms_img, wms_request.get_dates()
def get_days(bbox, start_time, end_time): wms_true_color_request = WmsRequest( layer='TRUE_COLOR', bbox=bbox, width=1500, height=1500, time=(start_time, end_time), instance_id='0d1f2199-b4b9-4bad-b88b-8b2423e57b93') return wms_true_color_request.get_dates()
def request2(self): wms_true_color_request = WmsRequest(layer='TRUE-COLOR', bbox=betsiboka_bbox, time='latest', width=512, height=856, config=config) wms_true_color_img = wms_true_color_request.get_data() plot_image(wms_true_color_img[-1]) print( 'The latest Sentinel-2 image of this area was taken on {}.'.format( wms_true_color_request.get_dates()[-1]))
def pic_request_SENTINEL(lat, long, ang_width): bound_box = bbox_coord_SENTINEL(lat, long, ang_width) wms_true_color_request = WmsRequest(layer='TRUE-COLOR-S2-L1C', bbox=bound_box, time='latest', width=1024, height=1024, maxcc=0.1, instance_id=INSTANCE_ID) wms_dates = wms_true_color_request.get_dates() wms_true_color_img = wms_true_color_request.get_data() return wms_dates, wms_true_color_img
def get_avg_cloud_cover(bbox, start_time='2018-09-28', end_time='2019-09-28', verbose=True): """ Finds the number of days for each cloud coverage from 0 to 100%, and returns it as a list. If verbose is set to True, the progress, output, and some extra info is printer to stdout. """ length_prev = 0 clouds = [] for cc in range(0, 11, 1): # Setting query parameters wms_true_color_request = WmsRequest( layer='TRUE_COLOR', bbox=bbox, width=1000, height=1000, time=(start_time, end_time), maxcc=cc / 10, instance_id='0d1f2199-b4b9-4bad-b88b-8b2423e57b93') # TODO: Only one satellite image per day if verbose: print("Finding %3d%% cloud coverage images..." % (cc * 10)) # Getting date data data = wms_true_color_request.get_dates() length_now = len(data) clouds.append(length_now - length_prev) length_prev = length_now # Get mean cloud cover if verbose: avg_cld = 0 index = 0 for x in range(0, len(clouds)): avg_cld += (index * 10) * clouds[index] index += 1 avg_cld /= sum(clouds) # Verbose output if verbose: print(clouds) print("Total days: %d" % sum(clouds)) print("Days with <50%% cloud coverage: %d" % sum(clouds[0:4])) print("Average cloud cover: %d%%" % avg_cld) return clouds
def request3(self): wms_true_color_request = WmsRequest(layer='TRUE-COLOR', bbox=betsiboka_bbox, time=('2017-12-01', '2017-12-31'), width=512, height=856, config=config) wms_true_color_img = wms_true_color_request.get_data() print('There are %d Sentinel-2 images available for December 2017.' % len(wms_true_color_img)) plot_image(wms_true_color_img[2]) print('These %d images were taken on the following dates:' % len(wms_true_color_img)) for index, date in enumerate(wms_true_color_request.get_dates()): print(' - image %d was taken on %s' % (index, date))
def get_all_bands(bbox, layer, SRS="epsg:3912"): minx, miny = bbox[0][0] #bbox[0:2] maxx, maxy = bbox[0][2] #bbox[4:6] right, bot = transform(Proj(init=SRS), Proj(init='epsg:4326'), maxx, miny) left, top = transform(Proj(init=SRS), Proj(init='epsg:4326'), minx, maxy) bounding_box = BBox([top, left, bot, right], crs=CRS.WGS84) #lat, lon = top-bot, right-left height, width = round(maxy - miny), round(maxx - minx) bands_script = "return [B01,B02,B03,B04,B05,B08,B8A,B09,B10,B11,B12]" wms_bands_request = WmsRequest(layer=layer, custom_url_params={ CustomUrlParam.EVALSCRIPT: bands_script, CustomUrlParam.ATMFILTER: 'NONE' }, bbox=bounding_box, time=('2017-01-01', '2018-12-01'), width=width, height=height, image_format=MimeType.TIFF_d32f, instance_id=api_key) all_cloud_masks = CloudMaskRequest(ogc_request=wms_bands_request, threshold=0.1) masks = [] wms_bands = [] for idx, [prob, mask, data] in enumerate(all_cloud_masks): masks.append(mask) wms_bands.append(data) return wms_bands, masks, wms_bands_request.get_dates()
######################################################## ### Sentinel-2 # check for the last available S-2 image with less than 30% cloud cover # only in RGB color for visualization wms_true_color_request = WmsRequest(layer='TRUE-COLOR-S2-L1C', bbox=cauquenes_bbox, time=('2017-12-01', '2017-12-31'), maxcc=0.2, width=3570, height=3600, instance_id=INSTANCE_ID) # get all images to python session wms_true_color_img = wms_true_color_request.get_data() print('These %d images were taken on the following dates:' % len(wms_true_color_img)) for index, date in enumerate(wms_true_color_request.get_dates()): print(' - image %d was taken on %s' % (index, date)) # see images one by one plot_image(wms_true_color_img[1]) # Download raw bands of the selected image with 20m pixel size wms_bands_request = WmsRequest(data_folder='test_dir_tiff', layer='BANDS-S2-L1C', bbox=cauquenes_bbox, time='2017-12-10', width=1570, height=1600, image_format=MimeType.TIFF_d32f, instance_id=INSTANCE_ID, custom_url_params={CustomUrlParam.ATMFILTER: 'ATMCOR'}) # save image to disk just in case
def process(self, arguments): start_time = time.time() collection_id = self.validate_parameter(arguments, "id", required=True, allowed_types=[str]) spatial_extent = self.validate_parameter(arguments, "spatial_extent", required=True) temporal_extent = self.validate_parameter(arguments, "temporal_extent", required=True) temporal_extent = _clean_temporal_extent(temporal_extent) bands = self.validate_parameter(arguments, "bands", default=None, allowed_types=[type(None), list]) if bands is not None and not len(bands): raise ProcessArgumentInvalid("The argument 'bands' in process 'load_collection' is invalid: At least one band must be specified.") bbox = load_collectionEOTask._convert_bbox(spatial_extent) # check if the bbox is within the allowed limits: options = arguments.get("options", {}) if options.get("width") or options.get("height"): width = options.get("width", options.get("height")) height = options.get("height", options.get("width")) else: width, height = sentinelhub.geo_utils.bbox_to_dimensions(bbox, 10.0) band_aliases = {} if collection_id == 'S2L1C': dataset = "S2L1C" ALL_BANDS = AwsConstants.S2_L1C_BANDS bands = validate_bands(bands, ALL_BANDS, collection_id) DEFAULT_RES = '10m' kwargs = dict( layer=SENTINELHUB_LAYER_ID_S2L1C, maxcc=1.0, # maximum allowed cloud cover of original ESA tiles ) dataFilter_params = { "previewMode": "EXTENDED_PREVIEW", } band_aliases = { "nir": "B08", "red": "B04", } elif collection_id == 'S1GRDIW': dataset = "S1GRD" # https://docs.sentinel-hub.com/api/latest/#/data/Sentinel-1-GRD?id=available-bands-and-data ALL_BANDS = ['VV', 'VH'] bands = validate_bands(bands, ALL_BANDS, collection_id) # https://docs.sentinel-hub.com/api/latest/#/data/Sentinel-1-GRD?id=resolution-pixel-spacing # Value Description # HIGH 10m/px for IW and 25m/px for EW # MEDIUM 40m/px for IW and EW # https://sentinel-hub.com/develop/documentation/eo_products/Sentinel1EOproducts # Sensing Resolution: # - Medium # - High # Similarly to polarization, not all beam mode/polarization combinations will have data # at the chosen resolution. IW is typically sensed in High resolution, EW in Medium. DEFAULT_RES = '10m' kwargs = dict( layer=SENTINELHUB_LAYER_ID_S1GRD, ) dataFilter_params = {} band_aliases = {} else: raise ProcessArgumentInvalid("The argument 'id' in process 'load_collection' is invalid: unknown collection id") self.logger.debug(f'Requesting dates between: {temporal_extent}') request = WmsRequest( **kwargs, instance_id=SENTINELHUB_INSTANCE_ID, bbox=bbox, time=temporal_extent, width=width, height=height, ) dates = request.get_dates() orbit_dates = get_orbit_dates(dates) response_data,orbit_times_middle = download_data(self, dataset, orbit_dates, width, height, bbox, temporal_extent, bands, dataFilter_params) mask = response_data[:, :, :, -1:] # ":" keeps the dimension mask = np.repeat(mask, len(bands), axis=-1).astype(bool) data = response_data[:, :, :, :-1] masked_data = da.ma.masked_array(data, mask=~mask) xrdata = xr.DataArray( masked_data, dims=('t', 'y', 'x', 'band'), coords={ 'band': bands, 't': orbit_times_middle, }, attrs={ "band_aliases": band_aliases, "bbox": bbox, }, ) self.logger.debug(f'Returning xarray, job [{self.job_id}] execution time: {time.time() - start_time}') return xrdata
def get_sunlight_data(bbox, center=DEFAULT_COORDS, start_time='2016-09-28', end_time='2019-09-28'): sun = Sun(center[1], center[0]) for cc in range(0, 11, 1): wms_true_color_request = WmsRequest( layer='TRUE_COLOR', bbox=bbox, width=1000, height=1000, time=(start_time, end_time), maxcc=cc / 10, instance_id='0d1f2199-b4b9-4bad-b88b-8b2423e57b93') data = wms_true_color_request.get_dates() for date in data: sunrise = sun.get_sunrise_time(date) sunset = sun.get_sunset_time(date) suntime = (sunset - sunrise) suntime_hour = (sunset.hour - sunrise.hour) suntime_minute = (sunset.minute - sunrise.minute) sunrise_f = "%02d:%02d" % (sunrise.hour, sunrise.minute) sunset_f = "%02d:%02d" % (sunset.hour, sunset.minute) # print(sunrise_f) # print(sunset_f) suntime_number_uf = (int(suntime_hour) + round(int(suntime_minute) / 60, 2)) suntime_number_f = '{:0>5.02f}'.format(suntime_number_uf) #print("number: ", suntime_number_uf) pw = ((suntime_number_uf * 0.2 * 1) + (suntime_number_uf * 0.2 * 0.7) + (suntime_number_uf * 0.3 * 0.4) + (suntime_number_uf * 0.3 * 0.2)) * 1000 real_cc = cc / 10 if (real_cc < 0.31): kwh = pw * 1 elif (real_cc >= 0.31 and real_cc < 0.71): kwh = pw * 0.6 elif (real_cc >= 0.71 and real_cc < 0.91): kwh = pw * 0.3 elif (real_cc >= 0.91): kwh = pw * 0.1 sunlight_data.append([ date, sunrise_f, sunset_f, "%d%%" % (cc * 10), suntime, suntime_number_f, round(pw), round(kwh) ]) # print(sunlight_data) return remove_duplicates(sunlight_data)
LAYER_NAME = 'TRUE_COLOR' #AYER_NAME = '1_TRUE_COLOR' wms_true_color_request = WmsRequest(layer=LAYER_NAME, bbox=bounding_box, time=('2015-01-01', '2015-12-31'), width=600, height=None, image_format=MimeType.PNG, instance_id=INSTANCE_ID) wms_true_color_imgs = wms_true_color_request.get_data() plot_previews(np.asarray(wms_true_color_imgs), wms_true_color_request.get_dates(), cols=4, figsize=(15, 10)) bands_script = 'return [B01,B02,B04,B05,B08,B8A,B09,B10,B11,B12]' wms_bands_request = WmsRequest(layer=LAYER_NAME, custom_url_params={ CustomUrlParam.EVALSCRIPT: bands_script, CustomUrlParam.ATMFILTER: 'NONE' }, bbox=bounding_box, time=('2017-12-01', '2017-12-31'), width=600, height=None, image_format=MimeType.TIFF_d32f, instance_id=INSTANCE_ID)
Utility function for plotting RGB images. """ fig = plt.subplots(1, 1, figsize=(15, 7)) if np.issubdtype(image.dtype, np.floating): plt.imshow(np.minimum(image * factor, 1)) else: plt.imshow(image) spain_bbox = BBox(bbox=[(-3.303790, 40.116775), (-3.703790, 40.416775)], crs=CRS.WGS84) #layers = ['SWIR','TRUE-COLOR-S2-L2A','TRUE-COLOR-S2-L1C'] #In case we want to use other data from sentinel apart from RGB images three_band_req = WmsRequest( layer= 'TRUE-COLOR-S2-L1C', #Select the layer we want (this has been configured in the CONFIGURATION OPTIONS of the app bbox=spain_bbox, #Define the LON_LAT box to see time='latest', #Date of the image, in this case, the latest available width=512, height=856, #Size of the image in pixels maxcc= 0.01, #Maximim % of cloud coverage. The higher, the more clouds we allow on the image instance_id=INSTANCE_ID) #The user ID three_band_img = three_band_req.get_data() plot_image(three_band_img[-1]) print('These %d images were taken on the following dates:' % len(three_band_img)) for index, date in enumerate(three_band_req.get_dates()): print(' - image %d was taken on %s' % (index, date)) plt.show()