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 request6(self): wms_bands_request = WmsRequest(data_folder='test_dir', layer='BANDS-S2-L1C', bbox=betsiboka_bbox, time='2017-12-15', width=512, height=856, image_format=MimeType.TIFF_d32f, config=config) wms_bands_img = wms_bands_request.get_data(save_data=True) import os for folder, _, filenames in os.walk(wms_bands_request.data_folder): for filename in filenames: print(os.path.join(folder, filename)) wms_bands_request_from_disk = WmsRequest( data_folder='test_dir', layer='BANDS-S2-L1C', bbox=betsiboka_bbox, time='2017-12-15', width=512, height=856, image_format=MimeType.TIFF_d32f, config=config) wms_bands_img_from_disk = wms_bands_request_from_disk.get_data() if np.array_equal(wms_bands_img[-1], wms_bands_img_from_disk[-1]): print('Arrays are equal.') else: print('Arrays are different.') wms_bands_img_redownload = wms_bands_request_from_disk.get_data( redownload=True)
def get_image(id, sp1s, sp1e, sp2s, sp2e): # betsiboka_coords_wgs84 = [23.11, 72.71, 23.46, 72.14] # betsiboka_coords_wgs84 = [46.16, -16.15, 46.51, -15.58] plotid = str(id) # print(id) # print(type(id)) file = open('coordinaes.txt', "r") temp = [line.strip() for line in file.readlines()] file.close() lat, lon = 23.02695648, 72.63268738 bliststr = [[141, 418], [257, 419], [274, 444], [245, 545], [200, 551], [119, 558]] for line in temp: x = line.split(';') if x[0] == plotid: lat = float(x[1]) lon = float(x[2]) bliststr = x[3] break bliststr = ast.literal_eval(bliststr) print(lat) print(lon) betsiboka_coords_wgs84 = boundingBox(lon, lat, 2) betsiboka_bbox = BBox(bbox=betsiboka_coords_wgs84, crs=CRS.WGS84) wi, he = geo_utils.bbox_to_dimensions(betsiboka_bbox, 2) wms_true_color_requestlatest = WmsRequest( layer='TRUE-COLOR-S2-L1C', bbox=betsiboka_bbox, # time=('2012-12-01', '2015-12-31'), time=(sp2s, sp2e), width=wi, height=he, maxcc=0.1, instance_id=INSTANCE_ID) wms_true_color_requesthistoric = WmsRequest( layer='TRUE-COLOR-S2-L1C', bbox=betsiboka_bbox, time=(sp1s, sp1e), # time='latest', width=wi, height=he, maxcc=0.1, instance_id=INSTANCE_ID) imagenew1 = wms_true_color_requestlatest.get_data() imageold1 = wms_true_color_requesthistoric.get_data() # print(wi) # print(he) # print('Returned data is of type = %s and length %d.' % # (type(wms_true_color_img), len(wms_true_color_img))) # # print('Single element in the list is of type {} and has shape {}'.format(type(wms_true_color_img[-1]), # wms_true_color_img[-1].shape)) dst, rem = plot_image(imagenew1[-1], imageold1[-1], pts=bliststr) return dst, rem, lat, lon
def check1(): bbox = [ 61.875000008613085, 40.979898074349165, 64.6875000090046, 43.06888777903171 ] bbox = [ 5138507.695017507, -1810221.6137981834, 5177469.516795154, -1744665.2835185674 ] # bbox = [61.5230, 40.58633, 64.4115, 43.50] geo_wms = WmsRequest( # request=None, layer='TRUE_COLOR', # styles=None, image_format=MimeType.JPG, custom_url_params={ CustomUrlParam.TRANSPARENT: False, CustomUrlParam.SHOWLOGO: False }, width=512, height=512, # maxcc=0.5, # bbox=BBox(bbox=[5009377.085697314, 6887893.492833803, 5322463.153553395, 7200979.560689886], crs=CRS.POP_WEB), # bbox=BBox(bbox=bbox, crs=CRS.WGS84), bbox=BBox(bbox=[ 5009377.085697314, 6887893.492833803, 5322463.153553395, 7200979.560689886 ], crs='EPSG:3857'), config=config) return geo_wms.get_data(decode_data=False)
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 request3(self): eval_script = ''' var bRatio = (B01 - 0.175) / (0.39 - 0.175); var NGDR = (B01 - B02) / (B01 + B02); function clip(a) { return a>0 ? (a<1 ? a : 1) : 0; } if (bRatio > 1) { var v = 0.5*(bRatio - 1); return [0.5*clip(B04), 0.5*clip(B03), 0.5*clip(B02) + v]; } if (bRatio > 0 && NGDR > 0) { var v = 5 * Math.sqrt(bRatio * NGDR); return [0.5 * clip(B04) + v, 0.5 * clip(B03), 0.5 * clip(B02)]; } return [2*B04, 2*B03, 2*B02]; ''' evalscript_wms_request = WmsRequest(layer='TRUE_COLOR', bbox=self._bbox, time='2017-12-20', width=512, custom_url_params={ CustomUrlParam.EVALSCRIPT: eval_script, CustomUrlParam.SHOWLOGO: False }, config=config) evalscript_wms_data = evalscript_wms_request.get_data() plot_image(evalscript_wms_data[0])
def get_cloud(lefttoplon, lefttoplat, rightbtmlon, rightbtmlat, time): """ Return cloud masks 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 bands_script = 'return [B01,B02,B04,B05,B08,B8A,B09,B10,B11,B12]' desired_coords_wgs84 = [lefttoplon, lefttoplat, rightbtmlon, rightbtmlat] desired_bbox = BBox(bbox=desired_coords_wgs84, crs=CRS.WGS84) wms_bands_request = WmsRequest( layer='TRUE_COLOR', custom_url_params={CustomUrlParam.EVALSCRIPT: bands_script}, bbox=desired_bbox, time=time, width=100, height=100, image_format=MimeType.TIFF_d32f, instance_id=INSTANCE_ID) all_cloud_masks = CloudMaskRequest(ogc_request=wms_bands_request, threshold=0.4) cloud_dates = all_cloud_masks.get_dates() cloud_masks = all_cloud_masks.get_cloud_masks(threshold=0.4) return cloud_masks, cloud_dates
def download_image(self, time, layer, path=None): """ Download images from single time range. :param time: time range in format ('time_from', 'time_to') :param layer: layer from sentinel-hub configuration :param path: path where to save images :return: None """ request = WmsRequest( layer=layer, bbox=self.bounding_box, time=time, # download from this time ranges maxcc=self.config.max_cloud_percentage, width=self.config.width, height=self.config.height, # photo dimensions custom_url_params=self.custom_url_params, instance_id=self.instance_id, ) images = request.get_data() if images: for index, image in enumerate(images): if path: image_name = self.image_name_template.format(path=path, index=index) logger.info("Saving image", image=image_name) SentinelDownloaderAPI._save_image(image, image_name) else: raise Exception("Path to image folder does not exists!")
def test_to_large_request(self): bbox = BBox((-5.23, 48.0, -5.03, 48.17), CRS.WGS84) request = WmsRequest(layer='TRUE-COLOR-S2-L1C', height=6000, width=6000, bbox=bbox, time=('2017-10-01', '2017-10-02')) with self.assertRaises(DownloadFailedException): request.get_data()
def main(): _bbox = utils_args() wms_request = WmsRequest( layer='TRUE_COLOR', # bbox=BBox( # bbox=[7215306.379154978, 4854643.0279353345, # 7177702.65516501, 4817350.823068645], # crs=CRS.POP_WEB), bbox=_bbox, width=512, height=512, maxcc=0.3, custom_url_params={ CustomUrlParam.SHOWLOGO: False, }, image_format=MimeType.JPG, config=config) # print(wms_request.get_url_list()) wms_data = wms_request.get_data() # print(len(wms_data)) # print(wms_data[0].shape) # plot_image(wms_data[0]) # print(len(wms_data)) plt.imshow(wms_data[0]) plt.show()
def fetch(): INSTANCE_ID = "9cd75fc0-6958-4d2e-8161-f9dd0665281d" bbox = [14.672, -24.487, 15.782, -22.705] bBox = BBox(bbox=bbox, crs=CRS.WGS84) wms_true_color_request = WmsRequest(layer='TRUE_COLOR', bbox=bBox, time=('2018-11-01', '2018-12-01'), width=512, height=900, instance_id=INSTANCE_ID) img = wms_true_color_request.get_data() img = np.array(img)[..., ::-1] os.chdir("tmp") # cv2.imwrite("img", img[0].tolist()) for i in range(img.__len__()): x = image_detection.white_percentage(img[i]) # cv2.imshow("imgMod", image_detection.divide_pic(img[i])) # cv2.waitKey(0) if (x < 40): cv2.imshow("img", img[i]) cv2.waitKey(0) string = "img" + str(i) + ".jpg" result = Image.fromarray(np.array(img[i])[..., ::-1]) result.save(string)
def setUpClass(cls): super().setUpClass() bbox1 = BBox([-90.9216499, 14.4190528, -90.8186531, 14.5520163], crs=CRS.WGS84) # From examples bbox2 = BBox([46.16, -16.15, 46.51, -15.58], crs=CRS.WGS84) # From sentinelhub-py examples cls.custom_url_params = { CustomUrlParam.SHOWLOGO: True, CustomUrlParam.TRANSPARENT: False, CustomUrlParam.EVALSCRIPT: 'return [B01]', CustomUrlParam.ATMFILTER: 'DOS1' } cls.wms_request = WmsRequest(layer='S2-DOS1', bbox=bbox1, time=('2017-12-01', '2017-12-31'), width=60, height=None, image_format=MimeType.TIFF, custom_url_params=cls.custom_url_params, instance_id=cls.CONFIG.instance_id) cls.wcs_request = WcsRequest(layer='S2-ATMCOR', bbox=bbox2, time='2016-07-18T07:14:04', resx='100m', resy='100m', image_format=MimeType.PNG, data_folder='.') cls.test_cases = [ TestCaseContainer('WMS', CloudMaskRequest(cls.wms_request, threshold=0.6, average_over=2, dilation_size=5), clm_min=0, clm_max=1, clm_mean=0.343827, clm_median=0, clp_min=0.00011, clp_max=0.99999, clp_mean=0.23959, clp_median=0.01897, mask_shape=(7, 81, 60)), TestCaseContainer('WCS, partial no data', CloudMaskRequest(cls.wcs_request, all_bands=True), clm_min=0, clm_max=1, clm_mean=0.04468, clm_median=0, clp_min=-50.0, clp_max=0.999635, clp_mean=-7.5472468, clp_median=0.011568, mask_shape=(1, 634, 374)) ]
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 get_S2_wmsrequest(layer, dam_bbox, date, width, height, maxcc): return WmsRequest(data_folder=None, layer=layer, bbox=dam_bbox, time=date.strftime('%Y-%m-%d') if isinstance(date, datetime) else date, width=width, height=height, image_format=MimeType.TIFF_d32f, maxcc=maxcc, time_difference=timedelta(hours=2), custom_url_params={CustomUrlParam.SHOWLOGO: False})
def request_single(self): image = WmsRequest(layer=self.data_type, bbox=self.bbox, time=self.date, width=self.width, height=self.height, maxcc=self.maxcc, image_format=MimeType.TIFF_d32f, config=self.config).get_data() return image
def request9(self): s1_asc_request = WmsRequest( # data_source=DataSource.SENTINEL1_IW_ASC, layer='TRUE_COLOR', bbox=self._bbox, time=('2017-10-03', '2017-10-05'), width=512, config=config) s1_asc_data = s1_asc_request.get_data() plot_image(s1_asc_data[-1])
def request8(self): s1_request = WmsRequest(data_source=DataSource.SENTINEL1_IW, layer='TRUE_COLOR', bbox=self._bbox, time='2017-08-20', width=512, config=config) s1_data = s1_request.get_data() plot_image(s1_data[-1])
def request7(self): l8_request = WmsRequest(data_source=DataSource.LANDSAT8, layer='TRUE_COLOR', bbox=self._bbox, time='2017-08-20', width=512, config=config) l8_data = l8_request.get_data() plot_image(l8_data[-1])
def request7(self): wms_true_color_request = WmsRequest(data_folder='test_dir_tiff', layer='TRUE-COLOR', bbox=betsiboka_bbox, time=('2017-12-01', '2017-12-31'), width=512, height=856, image_format=MimeType.TIFF, config=config) wms_true_color_request.save_data() os.listdir(wms_true_color_request.data_folder)
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 download(x1, x2, y1, y2, window, data_folder, width=512, height=512, satellite_id='L1C'): box_coords_wgs84 = [x1, y1, x2, y2] bbox = BBox(bbox=box_coords_wgs84, crs=CRS.WGS84) layer = 'ALL-BANDS-L1C' wms_bands_request = WmsRequest(data_folder=data_folder, layer=layer, bbox=bbox, time=window, width=width, height=height, image_format=MimeType.TIFF_d32f, instance_id=INSTANCE_ID, custom_url_params={ CustomUrlParam.ATMFILTER: 'ATMCOR', CustomUrlParam.TRANSPARENT: True, CustomUrlParam.SHOWLOGO: False }) #request and save image wms_img = wms_bands_request.get_data(save_data=True) #wait for tiffs to flush time.sleep(5) #turn tiffs into jpegs files = [ os.path.join(data_folder, file) for file in os.listdir(data_folder) ] for file in files: with rasterio.open(file) as im: r = im.read(range(2, 5)) r[r > 1] = 1 r[r < 0] = 0 r = np.transpose(r, (1, 2, 0)) r = np.sqrt(r) r = r * 255 imwrite(file.replace('.tiff', '.jpg'), r) os.remove(file) if not wms_img: # Image extraction Failed. return False else: return True # Image succesfully extracted.
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 save_sentinel_patch(x1, x2, y1, y2, window, width, height, data_folder, satellite_id='L2A'): ''' Little utility function that sends a request to sentinel-hub to extract a patch from sentinel1 or sentinel2 data. The returned patch is stored in .tiff format. Parameters: x1, x2, y1, y2: Are used to create a boundingbox in WGS84 format. window: Create the time window (either one timestamp or a window specified by beginning and end stamps. Format: %Y-%m-%d or [%Y-%m-%d, %Y-%m-%d]. width, height: The width and height in pixels of the patch. data_folder: The path to where the image will be stored. satellite_id: Should be one of the following: [L2A, L1C, SENTINEL1] (corresponding layers are created in the sentinel-hub configuration tool) ''' box_coords_wgs84 = [x1, y1, x2, y2] bbox = BBox(bbox=box_coords_wgs84, crs=CRS.WGS84) if satellite_id == 'L2A': layer = 'ALL-BANDS-L2A' elif satellite_id == 'L1C': layer = 'ALL-BANDS-L1C' elif satellite_id == 'SENTINEL1': layer = 'SENTINEL1' else: # No Valid satellite source was given. return False layer = 'TRUE_COLOR_11' wms_bands_request = WmsRequest(data_folder=data_folder, layer=layer, bbox=bbox, time=window, width=width, height=height, image_format=MimeType.TIFF_d32f, instance_id=INSTANCE_ID, custom_url_params={ CustomUrlParam.ATMFILTER: 'ATMCOR', CustomUrlParam.TRANSPARENT: True, CustomUrlParam.SHOWLOGO: False }) wms_img = wms_bands_request.get_data(save_data=True) if not wms_img: # Image extraction Failed. return False else: return True # Image succesfully extracted.
def get_landsat_image(self, layer: str, image_size: ImageSize, bbox: BBox, cloud_cov_perc: float, date: str) -> List[np.ndarray]: ''' date: 'latest' for latest image (str, str) for range ''' if layer not in ['RGB', 'LST', 'SENTINEL']: logging.warning( "SentinelHubAccessor: " + "@param layer should be one of RGB, LST, SENTINEL") if not isinstance(image_size, ImageSize): logging.error("SentinelHubAccessor: " + "@param image_size must be of type ImageSize") return [] if not isinstance(bbox, BBox): logging.error("SentinelHubAccessor: " + "@param bbox must be of type BBox") return [] if cloud_cov_perc < 0.0 or cloud_cov_perc > 1.0: logging.error("SentinelHubAccessor: " + "@param cloud_cov_perc must be in the range [0, 1]") return [] try: coords = [bbox.top_left.lon, bbox.top_left.lat, bbox.bottom_right.lon, bbox.bottom_right.lat] geometry = SentinelBBox(bbox=coords, crs=CRS.WGS84) data_source = DataSource.SENTINEL2_L1C if \ layer == 'SENTINEL' else DataSource.LANDSAT8 request = WmsRequest( data_source=data_source, layer=layer, bbox=geometry, time=date, width=image_size.width, # should be not to just use one of them height=image_size.height, instance_id=self.instance_id, maxcc=cloud_cov_perc, custom_url_params={ CustomUrlParam.SHOWLOGO: False}) logging.debug( f"SentinelHubAccessor: URLs: {request.get_url_list()}") data = request.get_data() if len(data): return data return [] except Exception: traceback.print_exc() return []
def get_location_img(bbox): wms_true_color_request = WmsRequest( layer='TRUE_COLOR', bbox=bbox, width=1000, height=1000, time='latest', maxcc=0, instance_id='0d1f2199-b4b9-4bad-b88b-8b2423e57b93') wms_true_color_img = wms_true_color_request.get_data() plot_img(wms_true_color_img[-1])
def get_cloud_data(bbox, start_time='2018-09-28', end_time='2019-09-28'): wms_true_color_request = WmsRequest( layer='CLOUD_LAYER', bbox=bbox, width=1000, height=1000, time=(start_time, end_time), maxcc=1, instance_id='0d1f2199-b4b9-4bad-b88b-8b2423e57b93') data = wms_true_color_request.get_data() print(data)
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 get_images(self, tiles: List[Tile]) -> Iterator[Tuple[Tile, bytes]]: for tile in tiles: # convert the tile index to a BBox with a buffer x, y, z = tile bbox = BBox(bounds((x, y, z)), crs=CRS.WGS84) # request the data from SentinelHub request = WmsRequest(**dict(bbox=bbox, **self.sentinel_wms_kwargs)) image_array = request.get_data(data_filter=[0])[0] img = Image.fromarray(image_array) img_bytes = BytesIO() img.save(img_bytes, format='png') yield (tile, img_bytes.getvalue())
def request6(self): dem_request = WmsRequest( data_source=DataSource.DEM, layer='DEM', bbox=self._bbox, width=512, image_format=MimeType.TIFF_d32f, custom_url_params={CustomUrlParam.SHOWLOGO: False}, config=config) dem_image = dem_request.get_data()[0] plot_image(dem_image, 1 / np.amax(dem_image))
def request5(self): wms_bands_request = WmsRequest(layer='BANDS-S2-L1C', bbox=betsiboka_bbox, time='2017-12-15', width=512, height=856, image_format=MimeType.TIFF_d32f, config=config) wms_bands_img = wms_bands_request.get_data() print("Shape:", wms_bands_img[-1][:, :, 12].shape) plot_image(wms_bands_img[-1][:, :, 12]) plot_image(wms_bands_img[-1][:, :, [3, 2, 1]], 2.5)