Exemple #1
0
    def _get_timestamp(self, time_interval, bbox):
        """ Get the timestamp array needed as a parameter for downloading the images
        """
        if self.single_scene:
            return [time_interval[0]]

        wfs = WebFeatureService(bbox=bbox,
                                time_interval=time_interval,
                                data_source=self.data_source,
                                maxcc=self.maxcc,
                                config=self.config)

        dates = wfs.get_dates()

        if len(dates) == 0:
            raise ValueError(
                "No available images for requested time range: {}".format(
                    time_interval))

        dates = sorted(dates)

        return [dates[0]] + [
            d2 for d1, d2 in zip(dates[:-1], dates[1:])
            if d2 - d1 > self.time_difference
        ]
Exemple #2
0
def get_available_timestamps(bbox, config, data_source, maxcc, time_difference,
                             time_interval):
    """Helper function to search for all available timestamps, based on query parameters

    :param bbox: Bounding box
    :type bbox: BBox
    :param time_interval: Time interval to query available satellite data from
    type time_interval: different input formats available (e.g. (str, str), or (datetime, datetime)
    :param data_source: Source of requested satellite data.
    :type data_source: DataSource
    :param maxcc: Maximum cloud coverage.
    :type maxcc: float
    :param time_difference: Minimum allowed time difference, used when filtering dates, None by default.
    :type time_difference: datetime.timedelta
    :param config: Sentinel Hub Config
    :type config: SHConfig
    :return: list of datetimes with available observations
    """
    wfs = WebFeatureService(bbox=bbox,
                            time_interval=time_interval,
                            data_source=data_source,
                            maxcc=maxcc,
                            config=config)
    dates = wfs.get_dates()

    if len(dates) == 0:
        raise ValueError(
            "No available images for requested time range: {}".format(
                time_interval))

    dates = sorted(dates)
    return [dates[0]] + [
        d2
        for d1, d2 in zip(dates[:-1], dates[1:]) if d2 - d1 > time_difference
    ]
Exemple #3
0
    def setUpClass(cls):
        super().setUpClass()

        wgs84_bbox = BBox(bbox=(-5.23, 48.0, -5.03, 48.17), crs=CRS.WGS84)
        time_interval = (datetime.date(year=2017, month=1, day=5), datetime.date(year=2017, month=12, day=16))

        cls.test_cases = [
            TestCaseContainer('General test',
                              WebFeatureService(wgs84_bbox, time_interval, data_source=DataSource.SENTINEL2_L1C,
                                                maxcc=0.1),
                              result_len=13),
            TestCaseContainer('Latest date only',
                              WebFeatureService(wgs84_bbox, 'latest', data_source=DataSource.SENTINEL2_L2A),
                              result_len=1),
        ]
def get_area_id(bbox, crs=CRS.WGS84):
    today = datetime.today()
    monthago = today - timedelta(days=7)
    time_interval = (monthago.strftime("%Y-%m-%dT%H:%M:%S"),
                     today.strftime("%Y-%m-%dT%H:%M:%S"))

    search_bbox = BBox(bbox=bbox, crs=crs)
    wfs_iterator = WebFeatureService(search_bbox,
                                     time_interval,
                                     instance_id=config.get(
                                         'config', 'sentinel_id'))
    aoi = search_bbox.get_geometry()
    instances = list(wfs_iterator)

    tiles = {}
    for i, tile_info in enumerate(wfs_iterator.get_tiles()):
        poly = shape(instances[i]['geometry'])
        tiles[tile_info[0]] = round(
            poly.intersection(aoi).area / poly.union(aoi).area * 100, 3)

    return sorted(tiles.items(), key=lambda x: -x[1])
    def get_random_tile(self):
        """Get a random tile over AOI and time interval"""
        random_point = random_sample_point(self.area_of_interest.geometry,
                                           triangles=self.aoi_triangulation,
                                           use_int_coords=False)
        small_bbox = self._get_small_bbox(random_point)

        for time_interval in self._get_shuffled_time_intervals():
            tiles = list(
                WebFeatureService(bbox=small_bbox,
                                  time_interval=time_interval,
                                  data_source=self.data_source,
                                  maxcc=self.maxcc))
            if tiles:
                return random.choice(tiles)

        raise ValueError(
            'Could not sample a random point from given areas of interest, maybe no data is available'
        )

INSTANCE_ID = '2d26c335-1184-42e3-8190-5de92f6c6aac'
if INSTANCE_ID:
    config = SHConfig()
    config.instance_id = INSTANCE_ID
else:
    config = None

search_bbox = BBox(bbox=[46.16, -16.15, 46.51, -15.58], crs=CRS.WGS84)
search_time_interval = ('2017-12-01T00:00:00', '2017-12-15T23:59:59')

wfs_iterator = WebFeatureService(
    search_bbox,
    search_time_interval,
    data_collection=DataCollection.SENTINEL2_L1C,
    maxcc=1.0,
    config=config
)

for tile_info in wfs_iterator:
    print(tile_info)

# extract info which uniquely defines each tile
print(wfs_iterator.get_tiles())

# automatic search with functions from sentinelhub.opensearch, which does not require authentication
for tile_info in get_area_info(search_bbox, search_time_interval, maxcc=0.5):
    print(tile_info)

"""
def get_dates_by_orbit(bbox, start_date, end_date, max_cc, target_orbit,
                       config):
    '''
    For a given bounding box, query Sentinel 2 imagery collection dates between
    two dates (start/end_date) that match a specified list of relative orbits
    and have a maximum cloud cover proportion.

    * bbox is a WGS84 bounding box created by sentinelhub.Geometry.BBox
    * start_date and end_date are date strings formatted as yyyy-mm-dd
    * max_cc is the maximum allowed cloud cover (0-1 scale)
    * target_orbit is a list containing relative orbit numbers to be included
    * config is the Sentinel Hub config object created by sentinelhub.SHConfig()
    '''
    assert target_orbit is not None, "target_orbit must be specified"

    # convert target_orbit to list if just a single orbit
    if type(target_orbit) is int:
        target_orbit = [target_orbit]

    # define time window
    search_time_interval = (f'{start_date}T00:00:00', f'{end_date}T23:59:59')

    # query scenes
    wfs_iterator = WebFeatureService(
        bbox,
        search_time_interval,
        data_collection=DataCollection.SENTINEL2_L2A,
        maxcc=max_cc,
        config=config)

    # filter down to dates from specified orbit(s)
    dates = []
    for tile_info in wfs_iterator:
        # raw product ID
        product_id = tile_info['properties']['id']

        # parse the product ID
        product_vals = parse.parse(S2_GRANULE_ID_FMT, product_id)

        # acquisition date
        date = tile_info['properties']['date']

        # absolute orbit is buried in ID after _A string
        absolute_orbit = int(product_vals['absolute_orbit'])

        # which satellite? 2A or 2B
        sat = product_vals['sat']
        assert sat in ('2A', '2B')

        # convert to relative orbit
        relative_orbit = absolute_to_relative_orbit(absolute_orbit, sat)

        if relative_orbit not in target_orbit:
            continue

        # add date if not already added to list
        if date not in dates:
            dates.append(date)

    assert len(dates) > 0, \
        f'No dates available for this bounding box and relative orbit {target_orbit}'

    return dates
Exemple #8
0
from sentinelhub import WebFeatureService, BBox, CRS, DataSource
from sentinelhub import AwsTileRequest, WmsRequest, AwsProductRequest
import config_file, time

INSTANCE_ID = '97b3c965-e57f-4a06-9ddc-e1ec478d930a'  # In case you put instance ID into cofniguration file you can leave this unchanged

search_bbox = BBox(bbox=[46.16, -16.15, 46.51, -15.58], crs=CRS.WGS84)
search_time_interval = ('2017-12-01T00:00:00', '2017-12-15T23:59:59')

wfs_iterator = WebFeatureService(
    search_bbox,
    search_time_interval,
    data_source=DataSource.LANDSAT8,
    instance_id='f438079a-b072-4285-b154-037b0627d223')
request = AwsProductRequest(product_id=x[0]['properties']['id'],
                            data_folder='')
tt = time.time()
metafiles = []
for (tile_name, t_time, aws_index) in wfs_iterator.get_tiles():
    tile_request = AwsTileRequest(
        tile=tile_name,
        time=t_time,
        aws_index=aws_index,
        data_folder=data_folder)  #metafiles=metafiles
    tile_request.save_data()

print(tt - time.time())
request = AwsProductRequest(product_id=product_id, data_folder=data_folder)

tile_id = 'S2A_OPER_MSI_L1C_TL_MTI__20151219T100121_A002563_T38TML_N02.01'
tile_name, time, aws_index = sentinelhub.AwsTile.tile_id_to_tile(tile_id)
Exemple #9
0
    to_images_path = join(to_path, 'images')
    if (not isdir(to_path)):
        os.makedirs(to_path)

    if (not isdir(to_images_path)):
        os.makedirs(to_images_path)

    np.savez_compressed(join(to_path, 'metadata.npz'), shape=shape, bb=bb)

    search_bbox = BBox(bbox=[(bb[0, 0], bb[0, 1]), (bb[1, 0], bb[1, 1])],
                       crs=CRS.WGS84)

    search_time_interval = (args.from_datetime, args.to_datetime)
    wfs_iterator = WebFeatureService(search_bbox,
                                     search_time_interval,
                                     data_source=DataSource.SENTINEL1_IW,
                                     maxcc=1.0,
                                     instance_id=INSTANCE_ID)

    additional_data = []
    for el in wfs_iterator:
        additional_data.append([
            el['properties']['id'].split('_')[0],
            el['properties']['orbitDirection'],
            get_orbit_id(el['properties']['id'])
        ])

    dates = wfs_iterator.get_dates()

    last_date = None
    for i in range(len(dates)):
Exemple #10
0
def get_available_dates(bounding_box, time_interval):
    wfs = WebFeatureService(bbox=bounding_box,
                            time_interval=time_interval,
                            config=config)

    return [date_time.strftime('%Y-%m-%d') for date_time in wfs.get_dates()]