Ejemplo n.º 1
0
def get_bounding_boxes(geojson, crs=CRS.WGS84):
    """
    A tool that converts GeoJSON file to Shapely polygon format and splits the given area into smaller parts.
    Returns the lat/lon bounding box for each part.

    Parameters:
    geojson (GeoJSON): A GeoJSON file describing the area of interest
    crs (CRS): Coordinate reference system of GeoJSON file

    Returns:
    bounding_boxes (ndarray): Array of bounding boxes
    """

    # Loading geometry of area of interest (AOI)
    geojson = read_data(geojson)
    AOI = shape(geojson['features'][0]['geometry'])

    # Split the area into smaller bounding boxes which can be used for obtaining data by calling WMS/WCS requests.
    osm_splitter = OsmSplitter([AOI], crs, zoom_level=10)

    bounding_boxes = []
    for bbox in osm_splitter.get_bbox_list():
      bounding_boxes.append(list(bbox))
    bounding_boxes = np.array(bounding_boxes)

    return bounding_boxes
Ejemplo n.º 2
0
    def setUpClass(cls):
        geojson = read_data(os.path.join(cls.INPUT_FOLDER,
                                         'cies_islands.json'))
        cls.area = shape(geojson)

        cls.test_cases = [
            cls.SplitterTestCase('BBoxSplitter',
                                 BBoxSplitter([cls.area],
                                              CRS.WGS84,
                                              5,
                                              reduce_bbox_sizes=True),
                                 bbox_len=19),
            cls.SplitterTestCase('OsmSplitter',
                                 OsmSplitter([cls.area],
                                             CRS.WGS84,
                                             15,
                                             reduce_bbox_sizes=True),
                                 bbox_len=24),
            cls.SplitterTestCase('TileSplitter',
                                 TileSplitter(
                                     [cls.area],
                                     CRS.WGS84, ('2017-10-01', '2018-03-01'),
                                     tile_split_shape=40,
                                     data_source=DataSource.SENTINEL2_L1C,
                                     reduce_bbox_sizes=True),
                                 bbox_len=13)
        ]
Ejemplo n.º 3
0
    def setUpClass(cls):
        super().setUpClass()

        geojson = read_data(os.path.join(cls.INPUT_FOLDER, 'cies_islands.json'))
        cls.area = shapely.geometry.shape(geojson)

        bbox_grid = [BBox((x / 10, y / 100, (x + 1) / 10, (y + 1) / 100), CRS.WGS84)
                     for x, y in itertools.product(range(-90, -87), range(4200, 4250))]

        cls.test_cases = [
            cls.SplitterTestCase('BBoxSplitter',
                                 BBoxSplitter([cls.area], CRS.WGS84, 5, reduce_bbox_sizes=True), bbox_len=19),
            cls.SplitterTestCase('OsmSplitter',
                                 OsmSplitter([cls.area], CRS.WGS84, 15, reduce_bbox_sizes=True), bbox_len=24),
            cls.SplitterTestCase('TileSplitter',
                                 TileSplitter([cls.area], CRS.WGS84, ('2017-10-01', '2018-03-01'), tile_split_shape=40,
                                              data_source=DataSource.SENTINEL2_L1C, reduce_bbox_sizes=True),
                                 bbox_len=13),
            cls.SplitterTestCase('CustomGridSplitter',
                                 CustomGridSplitter([cls.area], CRS.WGS84, bbox_grid, bbox_split_shape=(3, 4),
                                                    reduce_bbox_sizes=False),
                                 bbox_len=41),
            cls.SplitterTestCase('UTMGridSplitter',
                                 UtmGridSplitter([cls.area], CRS.WGS84, bbox_size=(1200, 1200)), bbox_len=16),
            cls.SplitterTestCase('UTMZoneSplitter',
                                 UtmZoneSplitter([cls.area], CRS.WGS84, bbox_size=(1000, 1000)), bbox_len=19)
        ]
Ejemplo n.º 4
0
# reduce the bboxes so that they do not include area outside the geomtry
bbox_splitter_reduced = BBoxSplitter([hawaii_area],
                                     CRS.WGS84, (5, 4),
                                     reduce_bbox_sizes=True)

show_splitter(bbox_splitter_reduced,
              show_legend=True,
              title="BBoxSplitter (finer)")
"""
The second option is to have a splitting grid idpt from the given geometries. This means that if the geometries change 
slightly, the grid will (likely) stay the same. The splitter below implements Open Street Map's (OSM) grid.

The obtained Sentinel-2 tiles intersect each other, so this splitter is only useful if we are analysing data on level
of the original satellite tiles.
"""
osm_splitter = OsmSplitter([hawaii_area], CRS.WGS84, zoom_level=10)

print(repr(osm_splitter.get_bbox_list()[0]))
print(osm_splitter.get_info_list()[0])

show_splitter(osm_splitter, show_legend=True, title="OsmSplitter")
"""
The third option is to work on a level of satellite tiles and split them using TileSplitter. This requires an instance
ID to utilise Sentinel Hub WFS.
"""

INSTANCE_ID = 'cae04732-5ed8-40c2-a2c6-461e44f55720'
if INSTANCE_ID:
    config = SHConfig()
    config.instance_id = INSTANCE_ID
else:
Ejemplo n.º 5
0
        tile_color = tuple(list(cm(i))[:3] + [alpha])
        ax.add_patch(
            plt_polygon(np.array(wgs84_bbox),
                        closed=True,
                        facecolor=tile_color,
                        edgecolor='green'))

        if show_legend:
            legend_shapes.append(plt.Rectangle((0, 0), 1, 1, fc=cm(i)))

    if show_legend:
        legend_names = []
        for info in info_list:
            legend_name = '{},{}'.format(info['index_x'], info['index_y'])

            for prop in ['grid_index', 'tile']:
                if prop in info:
                    legend_name = '{},{}'.format(info[prop], legend_name)

            legend_names.append(legend_name)

        plt.legend(legend_shapes, legend_names)
    plt.tight_layout()
    plt.show()


madagascar = [46.16, -16.15, 46.51, -15.58]
bbox = BBox(bbox=madagascar, crs=CRS.WGS84)
osm = OsmSplitter(shape_list=[bbox.geometry], crs=CRS.WGS84, zoom_level=10)
show_splitter(splitter=osm, show_legend=True)
Ejemplo n.º 6
0
class WCSRequest:
    # ------>>>>>>>>>>> Custom URL Parametres <<<<<<<<<<<-------- #
    @staticmethod
    def get_custom_url_params():
        for custom in CustomUrlParam:
            print(custom)

    # ------>>>>>>>>>>> Data Sources <<<<<<<<<<<-------- #
    @staticmethod
    def get_available_srcs():
        for sent in DataSource.get_available_sources():
            print(sent)

    _coords_wgs84 = [61.875000, 40.979898, 61.9, 41.162114]

    # _coords_wgs84 = [46.16, -16.15, 46.51, -15.58] or [5138507.695018, -1822100.150029, 5177469.516795, -1756135.024601]
    # _coords_wgs84 = [6887893.492833803, 5009377.085697314, 7200979.560689886, 5322463.153553395]
    _coords_wgs84 = [
        5138507.695018, -1822100.150029, 5177469.516795, -1756135.024601
    ]
    # osm_splitter = OsmSplitter(shape_list=((6887893.492833803, 5009377.085697314, 6887893.492833803, 5322463.153553395, 7200979.560689886, 5322463.153553395, 7200979.560689886, 5009377.085697314, 6887893.492833803, 5009377.085697314)), crs=CRS.POP_WEB, zoom_level=5)
    _bbox = BBox(bbox=_coords_wgs84, crs=CRS.POP_WEB)
    osm_splitter = OsmSplitter(shape_list=[_bbox.geometry],
                               crs=CRS.POP_WEB,
                               zoom_level=50)
    # print(_bbox.geometry)
    __bbox = osm_splitter.get_world_bbox()

    # _bbox = BBox(bbox=_coords_wgs84, crs=CRS.WGS84)

    # ************** True color with specified resolution ************** #
    def request1(self):
        wcs_true_color_request = WcsRequest(
            layer='TRUE_COLOR',
            bbox=self._bbox,
            # time='2017-12-15',
            resx='10m',
            resy='10m',
            custom_url_params=self.customUrlParam,
            config=config)

        wcs_true_color_img = wcs_true_color_request.get_data()
        print('''Single element in the list is of type = {} and has shape {}
            '''.format(type(wcs_true_color_img[-1]),
                       wcs_true_color_img[-1].shape))
        plot_image(wcs_true_color_img[-1])

    # ************** Using Custom URL Parameters ************** #
    def request2(self):
        custom_wms_request = WmsRequest(
            layer='SWIR',
            bbox=self.__bbox,
            # time='2019-11-05',
            width=512,
            height=512,
            maxcc=100,
            custom_url_params={
                # CustomUrlParam.ATMFILTER: 'ATMCOR',
                CustomUrlParam.TRANSPARENT: True,
                CustomUrlParam.SHOWLOGO: False
            },
            image_format=MimeType.PNG,
            config=config)
        wms_data = custom_wms_request.get_data()
        print(len(wms_data))
        plot_image(wms_data[0])

    # ************** Evalscript ************** #
    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])

    # ************** Evalscript URL ************** #
    def request4(self):
        _url = 'https://raw.githubusercontent.com/sentinel-hub/custom-scripts/master/sentinel-2/ndmi_special/script.js'

        evalscripturl_wms_request = WmsRequest(
            layer='TRUE_COLOR',  # Layer parameter can be any existing layer
            bbox=self._bbox,
            time='2017-12-20',
            width=512,
            custom_url_params={
                CustomUrlParam.EVALSCRIPTURL: _url,
                CustomUrlParam.SHOWLOGO: False
            },
            config=config)

        evalscripturl_wms_data = evalscripturl_wms_request.get_data()
        plot_image(evalscripturl_wms_data[0])

    # ************** Sentinel-2 L2A ************** #
    def request5(self):
        volcano_bbox = BBox(bbox=[(-2217485.0, 9228907.0),
                                  (-2150692.0, 9284045.0)],
                            crs=CRS.POP_WEB)

        l2a_request = WmsRequest(
            data_source=DataSource.SENTINEL2_L2A,
            layer='TRUE_COLOR',
            bbox=volcano_bbox,
            time='2017-08-30',
            width=512,
            custom_url_params={CustomUrlParam.SHOWLOGO: False},
            config=config)

        l2a_data = l2a_request.get_data()
        plot_image(l2a_data[0])

    # ************** DEM ************** #
    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))

    # ************** Landsat8 ************** #
    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])

    # ************** Sentinel-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])

    # ************** Sentinel-1, ascending orbit direction ************** #
    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])
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
# Get token for the session
token = oauth.fetch_token(token_url='https://services.sentinel-hub.com/oauth/token',
                          client_id=client_id, client_secret=client_secret)

# All requests using this session will have an access token automatically added
resp = oauth.get("https://services.sentinel-hub.com/oauth/tokeninfo")
print(resp.content)

# open boundary shapefile/json file
site = 'Arisaig'
site_shapefile = '/home/dmilodow/DataStore_DTM/STFC/DATA/EDINAAerial/%s_2017/%s_bbox_wgs84.shp' % (site,site)
for feature in fiona.open(site_shapefile): polygon = shape(feature['geometry'])

osm_splitter = OsmSplitter([polygon], CRS.WGS84, zoom_level=8) # Open Street Map Grid
search_bbox = osm_splitter

# define time interval of interest for imagery collection
search_time_interval = ('2019-06-25T00:00:00','2019-07-26T23:59:59')

# for each tile record the desired information
datainfo = pd.DataFrame(columns=['productIdentifier','tilecode','completionDate'])
for t,bbox in enumerate(search_bbox.bbox_list):
    for tile_info in get_area_info(bbox, search_time_interval, maxcc=0.20):
        datainfo = datainfo.append({'productIdentifier': tile_info['properties']['productIdentifier'],
                                    'tilecode' : tile_info['properties']['title'][49:55],
                                    'completionDate': tile_info['properties']['completionDate'][:10],
                                    }, ignore_index=True)

# check for duplicate images and filter these