def main(): # set configuration CLIENT_ID = '' CLIENT_SECRET = '' config = SHConfig() if CLIENT_ID and CLIENT_SECRET: config.sh_client_id = CLIENT_ID config.sh_client_secret = CLIENT_SECRET if config.sh_client_id == '' or config.sh_client_secret == '': print( "Warning! To use Sentinel Hub services, please provide the credentials (client ID and client secret)." ) # set coordinates, bounding box and a resolution (Naklo) TODO -> use input coordinates # [Longitude (x1), Latitude (y1) ... ] # betsiboka_coords_wgs84 = [14.2864, 46.2335, 14.3741, 46.2912] # Naklo betsiboka_coords_wgs84 = [14.3964, 46.2369, 14.4555, 46.2744] resolution = 10 betsiboka_bbox = BBox(bbox=betsiboka_coords_wgs84, crs=CRS.WGS84) betsiboka_size = bbox_to_dimensions(betsiboka_bbox, resolution=resolution) print(f'Image shape at {resolution} m resolution: {betsiboka_size} pixels') # get snow and vegetation data weatherDragons(betsiboka_coords_wgs84)
def test_bad_credentials(self): evalscript = """ //VERSION=3 function setup() { return { input: ["B02", "B03", "B04"], sampleType: "UINT16", output: { bands: 3 } }; } function evaluatePixel(sample) { return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02]; } """ request_params = dict( evalscript=evalscript, input_data=[ SentinelHubRequest.input_data( data_source=DataSource.SENTINEL2_L1C, time_interval=('2017-12-15T07:12:03', '2017-12-15T07:12:04'), ) ], responses=[SentinelHubRequest.output_response('default', 'tiff')], bbox=BBox(bbox=[46.16, -16.15, 46.51, -15.58], crs=CRS.WGS84), size=(512, 856)) bad_credentials_config = SHConfig() bad_credentials_config.sh_client_secret = 'test-wrong-credentials' request = SentinelHubRequest(**request_params, config=bad_credentials_config) with self.assertRaises(CustomOAuth2Error): request.get_data() missing_credentials_config = SHConfig() missing_credentials_config.sh_client_secret = '' request = SentinelHubRequest(**request_params, config=missing_credentials_config) with self.assertRaises(ValueError): request.get_data()
def __init__(self): # Set environment config = SHConfig() if os.getenv("CLIENT_ID") and os.getenv("CLIENT_SECRET"): config.sh_client_id = os.getenv("CLIENT_ID") config.sh_client_secret = os.getenv("CLIENT_SECRET") else: raise Exception("Client id and client secret is empty.") self.config = config
def login_config(CLIENT_ID, CLIENT_SECRET, instance_id): config = SHConfig() config.instance_id = instance_id if CLIENT_ID and CLIENT_SECRET: config.sh_client_id = CLIENT_ID config.sh_client_secret = CLIENT_SECRET if config.sh_client_id == '' or config.sh_client_secret == '' or config.instance_id == '': print( "Warning! To use Sentinel Hub services, please provide the credentials (client ID and client secret)." ) # config.save() return config
def set_sh_config(config: BaseConfig) -> SHConfig: """ Set AWS and SH credentials in SHConfig file to allow usage of download and io tasks """ sh_config = SHConfig() sh_config.aws_access_key_id = config.aws_access_key_id sh_config.aws_secret_access_key = config.aws_secret_access_key if all(key in config.__annotations__.keys() for key in ['sh_client_id', 'sh_client_secret']): sh_config.sh_client_id = config.sh_client_id sh_config.sh_client_secret = config.sh_client_secret sh_config.save() return sh_config
def authorize(): """ Set cridentials for sentinel hub services. :return: sentinel hub service configurations """ sh_config = SHConfig() if config.CLIENT_ID and config.CLIENT_SECRET: sh_config.sh_client_id = config.CLIENT_ID sh_config.sh_client_secret = config.CLIENT_SECRET if sh_config.sh_client_id == '' or sh_config.sh_client_secret == '': print( "Warning! To use Sentinel Hub services, please provide the credentials (client ID and client secret)." ) return sh_config
def do_magic(lat, lng): payload = {} # set configuration CLIENT_ID = '' CLIENT_SECRET = '' config = SHConfig() if CLIENT_ID and CLIENT_SECRET: config.sh_client_id = CLIENT_ID config.sh_client_secret = CLIENT_SECRET if config.sh_client_id == '' or config.sh_client_secret == '': print( "Warning! To use Sentinel Hub services, please provide the credentials (client ID and client secret)." ) # set coordinates, bounding box and a resolution (Naklo) TODO -> use input coordinates # [Longitude (x1), Latitude (y1) ... ] # betsiboka_coords_wgs84 = [14.2864, 46.2335, 14.3741, 46.2912] # Naklo # betsiboka_coords_wgs84 = [14.3964, 46.2369, 14.4555, 46.2744] # Sencur bbox = get_bounding_box(lat, lng, 5000) payload['bbox'] = [[bbox[0], bbox[3]], [bbox[2], bbox[1]]] #if 1 == 1: # return payload resolution = 20 betsiboka_bbox = BBox(bbox=bbox, crs=CRS.WGS84) betsiboka_size = bbox_to_dimensions(betsiboka_bbox, resolution=resolution) print(f'Image shape at {resolution} m resolution: {betsiboka_size} pixels') # get snow and vegetation data weatherData = weatherDragons(bbox) payload['weather'] = weatherData vegData = snowyVegetation(betsiboka_bbox, betsiboka_size, config) payload['vegetation'] = vegData return payload
""" Utility function for plotting RGB images. """ fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(5, 5)) if clip_range is not None: ax.imshow(np.clip(image * factor, *clip_range), **kwargs) else: ax.imshow(image * factor, **kwargs) ax.set_xticks([]) ax.set_yticks([]) fig.savefig('plot2.png') config = SHConfig() config.sh_client_id = 'dd0d9906-9ccb-470a-b80e-1ff099f833cc' config.sh_client_secret = 'CZ!T.hY-PFj272{v{)J}~9%BK*d2ph,8,5v0V5By' @app.route('/test', methods=['POST']) @cross_origin() def getVars(): if request.method == 'POST': jsonData = request.get_json() longitude = float(jsonData['longitude']) latitude = float(jsonData['latitude']) distance = float(jsonData['distance']) coords = [(longitude - (distance / 2)), (latitude - (distance / 2)), (longitude + (distance / 2)), (latitude + (distance / 2))] bbbox = BBox(coords, crs=CRS.WGS84)
import os import datetime import numpy as np import matplotlib.pyplot as plt from sentinelhub import SHConfig import datetime as dt from sentinelhub import MimeType, CRS, BBox, SentinelHubRequest, SentinelHubDownloadClient, \ DataCollection, bbox_to_dimensions, DownloadRequest config = SHConfig() CLIENT_ID = '9f7a0f53-d397-46ec-bc2c-7d109acc1dce' CLIENT_SECRET = 'J<2/_MJx9G,wf5n+U6q,mls[hga>nK-LTHjRi!p/' if CLIENT_ID and CLIENT_SECRET: config.sh_client_id = CLIENT_ID config.sh_client_secret = CLIENT_SECRET def plot_image(image, factor=1.0, clip_range=None, **kwargs): """ Utility function for plotting RGB images. """ fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(15, 15)) if clip_range is not None: ax.imshow(np.clip(image * factor, *clip_range), **kwargs) else: ax.imshow(image * factor, **kwargs) ax.set_xticks([]) ax.set_yticks([]) # plt.show()
# defines the region around the AOI; grid_size x grid_size grid of blocks, each with size block_width x block_height in degrees; grid_size must be an odd number block_width = 0.15 block_height = 0.10 grid_size = 7 # defines when a block is worth being processed cloud_threshold = 0.9 cloud_max_cover = 0.3 min_valid_area = 0.9 # sentinel-hub credentials config = SHConfig() config.instance_id = '***REMOVED***' config.sh_client_id = '***REMOVED***' config.sh_client_secret = '***REMOVED***' # ---------------------------------------------------------------------------------------------------------- # # Helper functions # # ---------------------------------------------------------------------------------------------------------- # # measures the distance in meters between two geographic coordinates def geo_dist(lat1, lon1, lat2, lon2): R = 6378.137 d_lat = lat2 * np.pi / 180.0 - lat1 * np.pi / 180.0 d_lon = lon2 * np.pi / 180.0 - lon1 * np.pi / 180.0 a = np.sin(d_lat / 2.0) * np.sin(d_lat / 2.0) + np.cos( lat1 * np.pi / 180.0) * np.cos(lat2 * np.pi / 180.0) * np.sin( d_lon / 2.0) * np.sin(d_lon / 2.0) c = 2.0 * np.arctan2(np.sqrt(a), np.sqrt(1.0 - a))
def add_coordinates(): filename = "picture.png" data = request.json #print(data) """ leftBottomLat: 46.09728117681059 leftBottomLng: 14.524612426757812 rightTopLat: 46.12728117681059 rightTopLng: 14.554612426757812 """ # PLS do not abuse CLIENT_ID = 'ec4f50ed-33c6-4e8d-806c-f6ca435c18bd' CLIENT_SECRET = '&E}d~KiDvRmIUmZ>fd+h_TF*mg#:g~[<bPI<ix<E' config = SHConfig() if CLIENT_ID and CLIENT_SECRET: config.sh_client_id = CLIENT_ID config.sh_client_secret = CLIENT_SECRET betsiboka_coords_wgs84 = [ data_json["leftBottomLng"], data_json["leftBottomLat"], data_json["rightTopLng"], data_json["rightTopLat"] ] #betsiboka_coords_wgs84 = [13.430786,45.565987,15.548401,46.464349] #filename = #f"hi{str(sum(betsiboka_coords_wgs84))}.png" # GET DEM DATA resolution, betsiboka_bbox, betsiboka_size = get_resolution( betsiboka_coords_wgs84) dem_data = get_dem_data(betsiboka_bbox, betsiboka_size) rays = get_rays(center_point, dem_data) evalscript_true_color = """ //VERSION=3 function setup() { return { input: [{ bands: ["B02", "B03", "B04"] }], output: { bands: 3 } }; } function evaluatePixel(sample) { return [sample.B04, sample.B03, sample.B02]; } """ request_true_color = SentinelHubRequest( evalscript=evalscript_true_color, input_data=[ SentinelHubRequest.input_data( data_collection=DataCollection.SENTINEL2_L1C, time_interval=('2020-04-01', '2020-08-30'), mosaicking_order='leastCC') ], responses=[ SentinelHubRequest.output_response('default', MimeType.PNG) ], bbox=betsiboka_bbox, size=betsiboka_size, config=config) true_color_imgs = request_true_color.get_data() image = true_color_imgs[0] print(f'Image type: {image.dtype}') figsize = (12, 8 * n / m) fig, ax = plot_image(image, factor=0.017, clip_range=(0, 1), figsize=figsize) ax.set_ylim(dem_data.shape[1] - 1, 0) p1 = None for ray in rays: if random.random() < 0.1: see_ray = seeable_points_on_ray(list(ray.keys()), list(ray.values())) #print(see_ray) for p in see_ray: if see_ray[p] == 1: p1 = p #seeable.add((p[0],p[1])) plt.plot(p[0], p[1], 'o', color='y', alpha=1, markersize=3) plt.plot(p1[0], p1[1], 'o', color='y', alpha=1, label="visible area") #x_seeable, y_seeable = list(map(lambda x : x[0], seeable)), list(map(lambda x : x[1], seeable)) #plt.plot(x[:5],y[:5],'o', color='b') plt.plot(center_point[0], center_point[1], '*', color='r', label="our location") ax.legend() #plt.show() #seeable_points(z) plt.savefig(filename) return send_file("../" + filename, as_attachment=True)