### Install sentinelhub manually Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/README.md Install the sentinelhub package manually by cloning the repository and running pip install. ```bash pip install . ``` -------------------------------- ### Install sentinelhub with pip Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/docs/source/install.md Use this command to install the base sentinelhub package using pip. ```bash pip install sentinelhub ``` -------------------------------- ### Install latest development version Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/docs/source/install.md Clone the GitHub repository and install the latest development version of sentinelhub-py in editable mode. ```bash pip install -e . --upgrade ``` -------------------------------- ### Install sentinelhub with AWS extension Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/docs/source/install.md Install sentinelhub with extra dependencies for interacting with Amazon Web Services. ```bash pip install sentinelhub[AWS] ``` -------------------------------- ### Install sentinelhub with pip Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/README.md Install the sentinelhub package using pip. Use the `[AWS]` tag for additional AWS functionalities. ```bash pip install sentinelhub ``` ```bash pip install sentinelhub[AWS] ``` -------------------------------- ### Install sentinelhub with Conda Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/docs/source/install.md Install the sentinelhub package from the conda-forge channel using Conda. ```bash conda install -c conda-forge sentinelhub ``` -------------------------------- ### Start Batch Request Job Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/batch_processing.ipynb Triggers the execution of a batch request job on the server. This starts the actual data processing. ```python client.start_job(batch_request) ``` -------------------------------- ### Start Batch Statistical Job Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/batch_statistical.ipynb Starts the execution of a batch statistical job using the `start_job` method of the Batch Statistical client. This method takes the request object as an argument. ```python client.start_job(request) ``` -------------------------------- ### Import Sentinel Hub and Utility Libraries Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities_cdse.ipynb Imports necessary libraries for Sentinel Hub operations, including data handling, geometry manipulation, and request clients. Ensure these are installed. ```python %matplotlib inline # ruff: noqa: I001 import itertools import tempfile from pathlib import Path import numpy as np from shapely.geometry import MultiLineString, MultiPolygon, Polygon, box, shape from sentinelhub import ( CRS, BBox, BBoxSplitter, CustomGridSplitter, DataCollection, MimeType, MosaickingOrder, OsmSplitter, SentinelHubDownloadClient, SentinelHubRequest, TileSplitter, UtmGridSplitter, UtmZoneSplitter, read_data, ) ``` -------------------------------- ### Initialize SentinelHubCatalog and Get Service Info Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/data_search_cdse.ipynb Initializes the SentinelHubCatalog and retrieves basic service information. This is the first step to interact with the Sentinel Hub STAC catalog. ```python from sentinelhub import SentinelHubCatalog catalog = SentinelHubCatalog(config=config) catalog.get_info() ``` -------------------------------- ### Start Batch Request Analysis Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/batch_processing.ipynb Initiates the analysis phase for a batch request on the server-side. This calculates information about tiles and processing units. ```python client.start_analysis(batch_request) ``` -------------------------------- ### Import necessary libraries for Sentinel Hub and data utilities Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Imports common libraries for data manipulation, plotting, and Sentinel Hub functionalities. Ensure these are installed before running. ```python # Configure plots for inline use in Jupyter Notebook %matplotlib inline import datetime as dt # Utilities import boto3 import dateutil import geopandas as gpd import matplotlib.pyplot as plt import pandas as pd # Sentinel Hub from sentinelhub import ( CRS, BBox, ByocCollection, ByocCollectionAdditionalData, ByocCollectionBand, ByocTile, DataCollection, DownloadFailedException, MimeType, SentinelHubBYOC, SentinelHubRequest, SHConfig, bbox_to_dimensions, ) ``` -------------------------------- ### Initialize WMS Request for Multiple Acquisitions in Time Window Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/ogc_request_cdse.ipynb Request all Sentinel-2 acquisitions within a specified date range by providing a tuple of start and end dates to the 'time' argument. ```python wms_true_color_request = WmsRequest( data_collection=DataCollection.SENTINEL2_L1C.define_from("s2l1c", service_url=config.sh_base_url), layer="TRUE-COLOR-S2-L1C", bbox=betsiboka_bbox, time=("2017-12-01", "2017-12-31"), width=512, height=856, config=config, ) ``` -------------------------------- ### Search Catalog Collections Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/data_search.ipynb Example of a search query for catalog collections, showing results with 'id' and 'properties' including 'datetime' and 'eo:cloud_cover'. ```python search_results = data_collection.search( bbox=BBox( (24.9, 49.9, 25.1, 50.1), crs=CRS.WGS84 ), datetime=TimeInterval( '2020-12-11', '2020-12-12' ), query= { "eo:cloud_cover": { "lt": 10 } } ) for item in search_results: print(item['id'], item['properties']['datetime'], item['properties']['eo:cloud_cover']) # Example output: # S2B_MSIL2A_20201211T073720Z 2020-12-11T07:37:20Z 0.6 # S2B_MSIL2A_20201211T073219_N0214_R049_T39TVL_20201211T090759 2020-12-11T07:37:06Z 0.0 ``` -------------------------------- ### Import necessary libraries Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/statistical_request_cdse.ipynb Imports required Python packages for data manipulation, plotting, and Sentinel Hub functionalities. Ensure 'geopandas', 'matplotlib', and 'seaborn' are installed. ```python %matplotlib inline import geopandas as gpd import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sentinelhub import ( CRS, BBox, DataCollection, Geometry, SentinelHubStatistical, SentinelHubStatisticalDownloadClient, SHConfig, parse_time, ) ``` -------------------------------- ### Create Data Collection from Existing Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/data_collections.ipynb Define a new data collection based on an existing one, modifying parameters such as the `service_url`. This example creates a Sentinel-2 L2A collection pointing to the MUNDI deployment. ```python from sentinelhub import DataCollection s2_l2a_mundi = DataCollection.define_from( DataCollection.SENTINEL2_L2A, "SENTINEL2_L2A_MUNDI", service_url="https://shservices.mundiwebservices.com" ) s2_l2a_mundi ``` -------------------------------- ### Import Visualization and Data Handling Libraries Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities_cdse.ipynb Imports additional libraries required for data visualization and advanced handling, such as GeoPandas, Matplotlib, and Xarray. These might require separate installation. ```python import geopandas as gpd import matplotlib.pyplot as plt import rioxarray # noqa: F401 # Its necesary for xarray.open_mfdataset() with engine `rasterio` import xarray as xr # It may need Dask library https://docs.dask.org/en/stable/install.html from matplotlib.patches import Polygon as PltPolygon from mpl_toolkits.basemap import Basemap # Available here: https://github.com/matplotlib/basemap ``` -------------------------------- ### WMS Request with Custom Evalscript Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/ogc_request.ipynb This example shows how to define a custom evalscript in Python and use it in a WMS request via the CustomUrlParam.EVALSCRIPT parameter. This allows for custom image processing directly on the Sentinel Hub. ```python # by Braaten, Cohen, Yang 2015 my_evalscript = """ 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( data_collection=DataCollection.SENTINEL2_L1C, layer="TRUE-COLOR-S2-L1C", # Layer parameter can be any existing Sentinel-2 L1C layer bbox=betsiboka_bbox, time="2017-12-20", width=512, custom_url_params={CustomUrlParam.EVALSCRIPT: my_evalscript}, config=config, ) evalscript_wms_data = evalscript_wms_request.get_data() plot_image(evalscript_wms_data[0]) ``` -------------------------------- ### Obtain Tile Paths from AWS Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Use the previously defined function to get a list of tile paths from a specific S3 bucket and date range. Ensure the 'config' object is properly initialized. ```python tiles_path = list_objects_path( bucket="sentinel-s2-l2a-mosaic-120", year_count=1, month_count=1, day_count=1, config=config ) ``` -------------------------------- ### WMS Request to Read Data from Disk Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/ogc_request.ipynb Create a new WMS request, pointing to the same `data_folder` where data was previously saved. This setup allows the library to load data from disk instead of re-downloading. ```python wms_bands_request_from_disk = WmsRequest( data_collection=DataCollection.SENTINEL2_L1C, data_folder="test_dir", layer="BANDS-S2-L1C", bbox=betsiboka_bbox, time="2017-12-15", width=512, height=856, image_format=MimeType.TIFF, config=config, ) ``` -------------------------------- ### Get Sentinel-2 Acquisitions in Time Window (True Color) Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/ogc_request.ipynb Retrieves all Sentinel-2 L1C true color images acquired within a specified date range. The `time` argument accepts a tuple of start and end dates. The number of available images and their acquisition dates can be accessed via `get_data()` and `get_dates()` respectively. ```python wms_true_color_request = WmsRequest( data_collection=DataCollection.SENTINEL2_L1C, layer="TRUE-COLOR-S2-L1C", bbox=betsiboka_bbox, time=("2017-12-01", "2017-12-31"), width=512, height=856, config=config, ) ``` ```python wms_true_color_img = wms_true_color_request.get_data() ``` ```python print("There are %d Sentinel-2 images available for December 2017." % len(wms_true_color_img)) ``` ```python plot_image(wms_true_color_img[2]) ``` ```python 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)) ``` -------------------------------- ### Initialize Sentinel Hub Client and Configuration Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/session_sharing.ipynb Initializes the Sentinel Hub client with configuration, asserting the minimum package version. Ensure your OAuth client ID and secret are provided in the SHConfig. ```python from sentinelhub import SentinelHubDownloadClient, SentinelHubSession, SHConfig, __version__ assert __version__ >= "3.6.0", "The minimal required package version for this tutorial is 3.6.0" config = SHConfig() # config.sh_client_id = "" # config.sh_client_secret = "" if not config.sh_client_id or not config.sh_client_secret: print("Please provide the credentials (OAuth client ID and client secret).") # The following endpoint can be accessed only if a user is authenticated: EXAMPLE_URL = "https://services.sentinel-hub.com/oauth/tokeninfo" ``` -------------------------------- ### Initialize WebFeatureService Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/data_search_cdse.ipynb Initializes the `WebFeatureService` client for interacting with WFS services. Requires the `sentinelhub` library. ```python from sentinelhub import WebFeatureService ``` -------------------------------- ### Configure Sentinel Hub Instance Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/ogc_request.ipynb Initializes the Sentinel Hub configuration. A warning is printed if the instance ID is not set, which is required for OGC functionality. ```python from sentinelhub import SHConfig config = SHConfig() if config.instance_id == "": print("Warning! To use OGC functionality of Sentinel Hub, please configure the `instance_id`.") ``` -------------------------------- ### Initialize UtmGridSplitter Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities.ipynb Instantiate `UtmGridSplitter` with a list of areas, a base CRS, and desired bounding box dimensions in meters. This splitter also enforces consistent bounding box sizes in meters. ```python utm_grid_splitter = UtmGridSplitter([hawaii_area], CRS.WGS84, (50000, 50000)) ``` -------------------------------- ### Configure Sentinel Hub Instance Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/data_search_cdse.ipynb Sets up the configuration for Sentinel Hub, allowing for an optional instance ID to be specified. This is a prerequisite for many Sentinel Hub operations. ```python INSTANCE_ID = "" config = SHConfig() if INSTANCE_ID: config.instance_id = INSTANCE_ID ``` -------------------------------- ### Initialize SHConfig Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/docs/source/configure.md Instantiate the SHConfig class to use default configuration values. The output shows the default fields and their initial empty or default values. ```python from sentinelhub import SHConfig config = SHConfig() config ``` -------------------------------- ### View Sentinel Hub Configuration Options Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/docs/source/configure.md This command displays available configuration options for Sentinel Hub. Use it to explore and understand the various settings you can adjust. ```bash $ sentinelhub.config --help ``` -------------------------------- ### Get All Collections and Filter BYOC/Batch Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/data_search_cdse.ipynb Retrieves all available data collections from the catalog and filters out BYOC and batch collections. Use this to get a list of standard satellite data collections. ```python collections = catalog.get_collections() collections = [collection for collection in collections if not collection["id"].startswith(("byoc", "batch"))] collections ``` -------------------------------- ### Configure Sentinel Hub credentials Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Sets up Sentinel Hub configuration, including client ID and secret. It's recommended to store these in a config.toml file, but they can also be provided directly. ```python # Insert your credentials here in case you don't already have them in the config.toml file: SH_CLIENT_ID = "" SH_CLIENT_SECRET = "" config = SHConfig() if SH_CLIENT_ID and SH_CLIENT_SECRET: config.sh_client_id = SH_CLIENT_ID config.sh_client_secret = SH_CLIENT_SECRET if not config.sh_client_id or not config.sh_client_secret: print("Warning! To use Sentinel Hub BYOC API, please provide the credentials (client ID and client secret).") ``` -------------------------------- ### Iterate Over BYOC Collections Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Get an iterator for all BYOC collections. This is efficient for handling a large number of collections. ```python collections_iterator = byoc.iter_collections() ``` -------------------------------- ### Configure Sentinel Hub Configuration Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities.ipynb Loads Sentinel Hub configuration. It's important to configure the `instance_id` for WFS functionality. ```python from sentinelhub import SHConfig config = SHConfig() if config.instance_id == "": print("Warning! To use WFS functionality, please configure the `instance_id`.") ``` -------------------------------- ### Get a BYOC Collection Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Retrieve a specific BYOC collection by its ID. Ensure you have the collection ID available. ```python my_collection = byoc.get_collection(created_collection["id"]) ``` -------------------------------- ### Initialize Batch Statistical Client Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/batch_statistical.ipynb Initializes a Batch Statistical client instance, which is used to manage batch statistical requests. The client requires a configuration object. ```python client = SentinelHubBatchStatistical(config) ``` -------------------------------- ### Plot BYOC tiles on a map Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Visualize the spatial distribution of BYOC tiles using `geopandas.plot`. This requires matplotlib to be installed. ```python fig, ax = plt.subplots(figsize=(17, 8)) tiles_gdf.plot(ax=ax); ``` -------------------------------- ### Initialize and use OsmSplitter Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities_cdse.ipynb Initializes an OsmSplitter with a given area, CRS, and zoom level. It then retrieves and prints the first bounding box and info list. ```python 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]) ``` -------------------------------- ### Create a new BYOC Tile object Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Instantiate a ByocTile object with the path to the tile on an S3 bucket and its sensing time. The path should include a '(BAND)' placeholder if band names vary. ```python new_tile = ByocTile(path="2019/11/27/28V/(BAND).tif", sensing_time=dt.datetime(2019, 11, 27)) ``` -------------------------------- ### Iterate over BYOC tiles Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Use `byoc.iter_tiles` to get an iterator for BYOC tiles within a collection. This is useful for processing tiles in batches. ```python tile_iterator = byoc.iter_tiles(created_collection) ``` -------------------------------- ### Create Shared Session for Multiprocessing Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/session_sharing.ipynb Create a SentinelHubSession that will be shared with all worker processes in a multiprocessing setup. This session is the source for the shared token. ```python # This will create a session that will be shared with all workers session = SentinelHubSession(config) ``` -------------------------------- ### Initialize and Use BBoxSplitter Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities.ipynb Initializes BBoxSplitter with an area, CRS, and grid dimensions. It then retrieves and prints the area's bounding box and a sample of the split bounding boxes with their associated information. ```python bbox_splitter = BBoxSplitter( [hawaii_area], CRS.WGS84, (5, 4) ) # bounding box will be split into grid of 5x4 bounding boxes print("Area bounding box: {}\n".format(bbox_splitter.get_area_bbox().__repr__())) bbox_list = bbox_splitter.get_bbox_list() info_list = bbox_splitter.get_info_list() print( "Each bounding box also has some info how it was created.\nExample:\nbbox: {}\ninfo: {}\n".format( bbox_list[0].__repr__(), info_list[0] ) ) ``` -------------------------------- ### Configure and Create Statistical Requests Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/statistical_request_cdse.ipynb Sets up the aggregation parameters and defines the statistical calculations for the requests. It then iterates through provided geographic shapes to create individual SentinelHubStatistical requests. ```python aggregation = SentinelHubStatistical.aggregation( evalscript=features_evalscript, time_interval=yearly_time_interval, aggregation_interval="P1D", resolution=(10, 10) ) calculations = {"default": {"statistics": {"default": {"percentiles": {"k": [5, 50, 95]}}}}}} features_requests = [] for geo_shape in polygons_gdf.geometry.values: request = SentinelHubStatistical( aggregation=aggregation, input_data=[ SentinelHubStatistical.input_data( DataCollection.SENTINEL2_L2A.define_from("s2l2a", service_url=config.sh_base_url) ) ], geometry=Geometry(geo_shape, crs=CRS(polygons_gdf.crs)), calculations=calculations, config=config, ) features_requests.append(request) ``` -------------------------------- ### Get the Next BYOC Collection from Iterator Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Retrieve the next BYOC collection from an iterator. Useful when you only need to process collections one by one. ```python my_collection_using_next = next(collections_iterator) print("name:", my_collection_using_next["name"]) print("id:", my_collection_using_next["id"]) ``` -------------------------------- ### Get and Print TileSplitter Information Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities.ipynb Retrieves and prints the number of bounding boxes, the first bounding box representation, and the information list for the TileSplitter. ```python tile_bbox_list = tile_splitter.get_bbox_list() print(len(tile_bbox_list)) print(tile_bbox_list[0].__repr__()) print(tile_splitter.get_info_list()[0]) ``` -------------------------------- ### Get Failed Statistical Requests Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/batch_statistical.ipynb Retrieves a list of any failed requests from the batch statistical processing. An empty list indicates all requests were successful. ```python failed_requests = get_failed_statistical_requests(results) failed_requests ``` -------------------------------- ### Configure and Create Statistical Requests Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/statistical_request.ipynb Sets up aggregation parameters and defines calculations for statistical requests. It then iterates through provided polygons to create individual requests. ```python aggregation = SentinelHubStatistical.aggregation( evalscript=features_evalscript, time_interval=yearly_time_interval, aggregation_interval="P1D", resolution=(10, 10) ) calculations = {"default": {"statistics": {"default": {"percentiles": {"k": [5, 50, 95]}}}}}} features_requests = [] for geo_shape in polygons_gdf.geometry.values: request = SentinelHubStatistical( aggregation=aggregation, input_data=[SentinelHubStatistical.input_data(DataCollection.SENTINEL2_L2A)], geometry=Geometry(geo_shape, crs=CRS(polygons_gdf.crs)), calculations=calculations, config=config, ) features_requests.append(request) ``` -------------------------------- ### Configure Sentinel Hub credentials Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/batch_statistical.ipynb Initializes Sentinel Hub configuration. If client ID or secret are not set, a warning is printed, as they are required for using the Batch Statistical API. ```python config = SHConfig() if not config.sh_client_id or not config.sh_client_secret: print("Warning! To use Batch Statistical API, please provide the credentials (OAuth client ID and client secret).") ``` -------------------------------- ### Get Bounding Boxes from UtmZoneSplitter Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities.ipynb Retrieve a list of `BBox` objects representing the split UTM zones. Each `BBox` is in the CRS of its corresponding UTM zone. ```python utm_zone_splitter.get_bbox_list() ``` -------------------------------- ### Get Specific Tiling Grid Definition Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/batch_processing.ipynb Fetches the definition of a specific tiling grid by its ID. Replace `GRID_ID` with the desired grid's identifier. ```python # Specify grid ID here: GRID_ID = 1 client.get_tiling_grid(GRID_ID) ``` -------------------------------- ### Display First Result Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/data_search_cdse.ipynb Prints the first result obtained from the WFS search. This shows the structure and available properties for a single data product. ```python results[0] ``` -------------------------------- ### Initialize UtmZoneSplitter Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities.ipynb Instantiate `UtmZoneSplitter` with a list of areas, a base CRS, and desired bounding box dimensions in meters. The `reduce_bbox_sizes` option is not available for this splitter. ```python utm_zone_splitter = UtmZoneSplitter([hawaii_area], CRS.WGS84, (50000, 50000)) ``` -------------------------------- ### Configure S3 Input and Output Paths Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/batch_statistical.ipynb Defines the S3 bucket paths for input data and output storage. Ensure the IAM user has the necessary permissions to access these locations. ```python INPUT_PATH = "s3:////reprojected-geoms.gpkg" OUTPUT_PATH = "s3:////output/" ``` -------------------------------- ### Create Pandas DataFrame from BYOC Collections Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Convert all BYOC collections into a pandas DataFrame for easier data manipulation and analysis. This requires the pandas library to be installed. ```python my_collections_df = pd.DataFrame(data=list(byoc.iter_collections())) my_collections_df[["id", "name", "created"]].head() ``` -------------------------------- ### Get Shape of a Specific Sentinel-2 Band Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/ogc_request.ipynb Access and print the shape of a specific band (e.g., the 13th band, which is B12) from the downloaded Sentinel-2 image data. ```python wms_bands_img[-1][:, :, 12].shape ``` -------------------------------- ### Configure BYOC Collection with Manual Band Settings Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Use this when you need to explicitly define bands for ingestion, such as for true color TIFFs. Ensure the `ByocCollectionAdditionalData` and `ByocCollectionBand` objects are correctly populated with source, band index, bit depth, and sample format. ```python band_config = ByocCollectionAdditionalData( bands={ # source should be the string inside (BAND) placeholder "R": ByocCollectionBand(source="RGB", band_index=1, bit_depth=8, sample_format="UINT"), "G": ByocCollectionBand(source="RGB", band_index=2, bit_depth=8, sample_format="UINT"), "B": ByocCollectionBand(source="RGB", band_index=3, bit_depth=8, sample_format="UINT"), } ) byoc_manual_config = ByocCollection( name="byoc-manual-config", s3_bucket="byoc-config-demo", additional_data=band_config ) byoc_manual_config_collection = byoc.create_collection(byoc_manual_config) ``` ```python byoc_manual_config_collection["isConfigured"] ``` ```python byoc_manual_config_collection["additionalData"] ``` ```python added_tile = byoc.create_tile(byoc_manual_config_collection, example_tile) added_tile ``` ```python added_tile_info = byoc.get_tile(collection=byoc_manual_config_collection["id"], tile=added_tile["id"]) added_tile_info["status"] ``` -------------------------------- ### Get Tile Sensing Time Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Retrieves the sensing time of a tile, either by parsing a string or directly from a dataclass object. This is often needed for time-interval filtering. ```python tile_time = dateutil.parser.parse(tiles[0]["sensingTime"]) ``` ```python tile_time = tile_dataclass.sensing_time ``` -------------------------------- ### Import Sentinel Hub and Utility Libraries Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities.ipynb Imports necessary libraries for Sentinel Hub operations, including data handling, bounding box splitting, and request management. Also imports auxiliary libraries for visualization and data manipulation. ```python %matplotlib inline # ruff: noqa: I001 import itertools import tempfile from pathlib import Path import numpy as np from shapely.geometry import MultiLineString, MultiPolygon, Polygon, box, shape from sentinelhub import ( CRS, BBox, BBoxSplitter, CustomGridSplitter, DataCollection, MimeType, MosaickingOrder, OsmSplitter, SentinelHubDownloadClient, SentinelHubRequest, TileSplitter, UtmGridSplitter, UtmZoneSplitter, read_data, ) ``` ```python import geopandas as gpd import matplotlib.pyplot as plt import rioxarray # noqa: F401 # Its necesary for xarray.open_mfdataset() with engine `rasterio` import xarray as xr # It may need Dask library https://docs.dask.org/en/stable/install.html from matplotlib.patches import Polygon as PltPolygon from mpl_toolkits.basemap import Basemap # Available here: https://github.com/matplotlib/basemap ``` -------------------------------- ### Get Collection Information Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/data_search_cdse.ipynb Retrieve detailed information about a specific data collection, such as Sentinel-1 GRD. This method is useful for understanding the properties and available parameters of a dataset. ```python catalog.get_collection(DataCollection.SENTINEL1_EW) ``` -------------------------------- ### Execute Raw Dictionary Request Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/process_request.ipynb Create and execute a download request using a raw dictionary. Ensure the 'content-type' header is set to 'application/json' for POST requests. ```python # create request download_request = DownloadRequest( request_type="POST", url="https://services.sentinel-hub.com/api/v1/process", post_values=request_raw_dict, data_type=MimeType.TIFF, headers={"content-type": "application/json"}, use_session=True, ) # execute request client = SentinelHubDownloadClient(config=config) img = client.download(download_request) ``` -------------------------------- ### Get a specific feature by ID Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/data_search.ipynb Use `catalog.get_feature` to retrieve information about a specific satellite tile when you have its ID. This requires the data collection and the feature ID as arguments. ```python catalog.get_feature(DataCollection.SENTINEL2_L2A, "S2A_MSIL2A_20210125T073201_N0214_R049_T39TWK_20210125T105105") ``` -------------------------------- ### Configure Sentinel Hub Catalog API Credentials Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/data_search_cdse.ipynb Configures the Sentinel Hub client with credentials. Prints a warning if client ID or secret are missing, which are required for Catalog API usage. ```python config = SHConfig() if config.sh_client_id == "" or config.sh_client_secret == "": print("Warning! To use Sentinel Hub Catalog API, please provide the credentials (client ID and client secret).") ``` -------------------------------- ### Get Tile Ingestion Status Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Retrieves information about a specific tile within a BYOC collection to check its ingestion status. The status will change from 'WAITING' as the ingestion progresses. ```python added_tile_info = byoc.get_tile(collection=byoc_auto_config_collection["id"], tile=added_tile["id"]) added_tile_info["status"] ``` -------------------------------- ### Configure Sentinel Hub Credentials Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/process_request.ipynb Initializes Sentinel Hub configuration. Ensure your OAuth client ID and client secret are provided for Process API access. ```python from sentinelhub import SHConfig config = SHConfig() if not config.sh_client_id or not config.sh_client_secret: print("Warning! To use Process API, please provide the credentials (OAuth client ID and client secret).") ``` -------------------------------- ### Configure SHConfig with a Profile Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/docs/source/configure.md Load configuration from a specific profile in the TOML file. If no profile is specified, the default profile is used. ```python from sentinelhub import SHConfig config = SHConfig("myprofile") ``` -------------------------------- ### Get the first tile from a BYOC collection iterator Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Use `next()` with `byoc.iter_tiles` to efficiently retrieve only the first tile from a large collection, avoiding loading all tile information. ```python tile = next(byoc.iter_tiles(created_collection)) ``` -------------------------------- ### Get a specific feature by ID Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/data_search_cdse.ipynb Use this method to retrieve information about a specific satellite tile when its ID is known. This requires the data collection and the unique feature ID. ```python catalog.get_feature( DataCollection.SENTINEL2_L2A, "S2A_MSIL2A_20210125T073201_N0500_R049_T39TWK_20230528T024029.SAFE", ) ``` -------------------------------- ### Create BBox Object and Calculate Image Dimensions Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/process_request.ipynb Initializes a BBox object with WGS84 coordinates and calculates the desired output image dimensions in pixels based on a specified resolution in meters. ```python resolution = 60 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") ``` -------------------------------- ### List Available Tiling Grids Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/batch_processing.ipynb Retrieves and lists all available tiling grids supported by the Batch API. This helps in selecting an appropriate grid for batch processing tasks. ```python list(client.iter_tiling_grids()) ``` -------------------------------- ### Get a specific tile from a BYOC collection Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/byoc_request.ipynb Use this method to retrieve a single tile by providing its collection ID and tile ID. This is useful when you know the exact tile you need. ```python tile = byoc.get_tile(collection=created_collection["id"], tile=created_tile["id"]) ``` ```python tile ``` -------------------------------- ### Initialize and use TileSplitter Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities_cdse.ipynb Initializes a TileSplitter with a given area, CRS, time interval, and data collection. It then prints the number of bounding boxes and details of the first bounding box and info. ```python tile_splitter = TileSplitter( [hawaii_area], CRS.WGS84, ("2017-10-01", "2017-11-01"), data_collection=DataCollection.SENTINEL2_L1C.define_from("s2l1c", service_url=config.sh_base_url), config=config, ) tile_bbox_list = tile_splitter.get_bbox_list() print(len(tile_bbox_list)) print(tile_bbox_list[0].__repr__()) print(tile_splitter.get_info_list()[0]) ``` -------------------------------- ### Get Geometries from Split Bounding Boxes Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities.ipynb Retrieves a list of geometries, where each geometry is the intersection of a split bounding box with the original area of interest. This is useful for processing only the relevant parts of each tile. ```python geometry_list = bbox_splitter.get_geometry_list() geometry_list[0] ``` -------------------------------- ### WMS Request with Evalscript URL Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/ogc_request.ipynb This example demonstrates how to use a remote evalscript by providing its URL to the CustomUrlParam.EVALSCRIPTURL parameter in a WMS request. This is useful for utilizing pre-existing, complex processing scripts. ```python my_url = "https://raw.githubusercontent.com/sentinel-hub/custom-scripts/master/sentinel-2/ndmi_special/script.js" evalscripturl_wms_request = WmsRequest( data_collection=DataCollection.SENTINEL2_L1C, layer="TRUE-COLOR-S2-L1C", # Layer parameter can be any existing Sentinel-2 L1C layer bbox=betsiboka_bbox, time="2017-12-20", width=512, custom_url_params={CustomUrlParam.EVALSCRIPTURL: my_url}, config=config, ) evalscripturl_wms_data = evalscripturl_wms_request.get_data() plot_image(evalscripturl_wms_data[0]) ``` -------------------------------- ### Configure S3 Bucket for Batch Output Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/batch_processing.ipynb Sets up the S3 bucket path and IAM role ARN for the Batch Process to write output data. Follow the provided instructions for setting up AWS IAM Assume Role Workflow. ```python BUCKET_PATH = "???" ROLE_ARN = "???” ``` -------------------------------- ### Configure Sentinel Hub credentials Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/batch_processing.ipynb Initializes Sentinel Hub configuration. It includes a check to ensure that client ID and client secret are provided, which are necessary for using the Sentinel Hub Process API. ```python config = SHConfig() if config.sh_client_id == "" or config.sh_client_secret == "": print("Warning! To use Sentinel Hub Process API, please provide the credentials (client ID and client secret).") ``` -------------------------------- ### NDVI Evalscript Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities.ipynb An example evalscript for calculating the Normalized Difference Vegetation Index (NDVI) using Sentinel-2 Level 2A data. It requires B04 (Red) and B08 (NIR) bands. ```javascript //VERSION=3 function evaluatePixel(samples) { let val = index(samples.B08, samples.B04); return [val]; } function setup() { return { input: [{ bands: [ "B04", "B08", "dataMask" ] }], output: { bands: 1 } } } ``` -------------------------------- ### Initialize SentinelHubSession from Token Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/session_sharing.ipynb Create a SentinelHubSession object from an existing token. By default, sessions created this way are non-refreshing. ```python session = SentinelHubSession.from_token(token) session ``` -------------------------------- ### Import Sentinel Hub and Utilities Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/process_request.ipynb Imports necessary libraries for Sentinel Hub requests, including data handling, CRS, bounding boxes, and plotting utilities. ```python import datetime import os import matplotlib.pyplot as plt import numpy as np from sentinelhub import ( CRS, BBox, DataCollection, DownloadRequest, MimeType, MosaickingOrder, SentinelHubDownloadClient, SentinelHubRequest, bbox_to_dimensions, ) # The following is not a package. It is a file utils.py which should be in the same folder as this notebook. from utils import plot_image ``` -------------------------------- ### Plotting Data by Identifier Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/batch_statistical.ipynb Initializes a matplotlib figure and axes for plotting. It then iterates through groups of data, where each group is defined by a unique 'identifier'. This setup is typically followed by plotting logic within the loop. ```python fig, ax = plt.subplots(figsize=(15, 8)) for _, group in dataframe.groupby("identifier"): ``` -------------------------------- ### NDVI Evalscript for Sentinel Hub Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities_cdse.ipynb An example evalscript for Sentinel Hub to calculate NDVI using Sentinel-2 L2A bands B04 and B08. It specifies input bands and output band count. ```python ndvi_eval = """ //VERSION=3 function evaluatePixel(samples) { let val = index(samples.B08, samples.B04); return [val]; } function setup() { return { input: [{ bands: [ "B04", "B08", "dataMask" ] }], output: { bands: 1 } } } """ ``` -------------------------------- ### Set up IPython Environment Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/process_request.ipynb Configures the IPython environment for automatic reloading of modules and inline display of matplotlib plots. ```python %reload_ext autoreload %autoreload 2 %matplotlib inline ``` -------------------------------- ### Define bounding box and dimensions Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/reading_pu_from_headers.ipynb Sets up the geographical bounding box and desired output dimensions for the Sentinel Hub request using WGS84 coordinates. ```python betsiboka_coords_wgs84 = (46.16, -16.15, 46.51, -15.58) resolution = 60 betsiboka_bbox = BBox(bbox=betsiboka_coords_wgs84, crs=CRS.WGS84) betsiboka_size = bbox_to_dimensions(betsiboka_bbox, resolution=resolution) ``` -------------------------------- ### Search Sentinel-2 L2A with WFS Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/data_search.ipynb Searches for Sentinel-2 L2A data using the Web Feature Service (WFS) with specified bounding box, time interval, and maximum cloud cover. Requires SHConfig setup. ```python from sentinelhub import BBox, CRS, DataCollection, SHConfig, WebFeatureService caspian_sea_bbox = BBox((49.9604, 44.7176, 51.0481, 45.2324), crs=CRS.WGS84) time_interval = "2020-12-10", "2021-02-01" wfs_iterator = WebFeatureService( caspian_sea_bbox, time_interval, data_collection=DataCollection.SENTINEL2_L2A, maxcc=0.05, config=config ) results = list(wfs_iterator) print("Total number of results:", len(results)) results[0] ``` -------------------------------- ### Initialize Batch Process Client Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/batch_processing.ipynb Initializes the BatchProcessClient for interacting with the Sentinel Hub Batch API (Version 2). Ensure your configuration object contains valid credentials and service URLs. ```python client = BatchProcessClient(config=config) ``` -------------------------------- ### WCS Request with Specified Resolution Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/ogc_request.ipynb Use `WcsRequest` to specify spatial resolution in meters using `resx` and `resy` arguments, instead of image dimensions. This example requests a true color image with a resolution of 60m x 60m. ```python wcs_true_color_request = WcsRequest( data_collection=DataCollection.SENTINEL2_L1C, layer="TRUE-COLOR-S2-L1C", bbox=betsiboka_bbox, time="2017-12-15", resx="60m", resy="60m", config=config, ) wcs_true_color_img = wcs_true_color_request.get_data() ``` ```python 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 ) ) ``` ```python plot_image(wcs_true_color_img[-1]) ``` -------------------------------- ### Initialize TileSplitter Source: https://github.com/sentinel-hub/sentinelhub-py/blob/master/examples/large_area_utilities.ipynb Initializes a TileSplitter for splitting areas into satellite tiles. Requires area, CRS, time interval, data collection, and configuration. ```python tile_splitter = TileSplitter( [hawaii_area], CRS.WGS84, ("2017-10-01", "2017-11-01"), data_collection=DataCollection.SENTINEL2_L1C, config=config ) ```