Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Sentinel 2 cloud access

This notebook illustrates the use of STAC and pystac-client to access and open Sentinel 2 (cloud-optimized geotiff) datasets.

Notes

  1. You MUST be working within an AWS instance. Otherwise, you will get a permissions error.

  2. Authentication is still more steps than we’d like. We’re working to address this - let us know if you’d like to join the conversation!

For this tutorial, feel free to run the code along with us as we live code by downsizing the zoom window and splitting your screen (or using two screens). Or you can simply watch the zoom walkthrough. Don’t worry if you fall behind on the code. The notebook is standalone and you can easily run the code at your own pace another time to catch anything you missed.

Computing environment

We’ll be using the following open source Python libraries in this notebook:

Search and open (Sentinel 2) raster imagery from the cloud

We will be working with Cloud Optimized GeoTIFF (COG). A COG is a GeoTIFF file with an internal organization that enables more efficient workflows and prevents having to open the entire image (see more at https://www.cogeo.org/).

Here is the User Manual for more information about accessing Sentinel 2 S3.

Search for Sentinel 2 imagery

To explore and access COG’s easily we will use a SpatioTemporal Asset Catalog (STAC). The STAC provides a common metadata format to make it easier to index and querry S3 buckets for geospatial data.

Extract geometry bounds are extracted from the ICESat-2 KML file used above so that we can perform the Sentinel 2 spatial search.

We will search for imagery in STAC catalog using the pystac_client search tool.

19 items

We can include property searches, such as path, row, cloud-cover, as well with the properties flag in the api.search.

We are given a pystac collection of items (images)

Loading...

Load the geojson file into geopandas and inspect the items we want to collect

Loading...
Loading...

Intake all scenes using the intake-STAC library

Intake-STAC facilitates discovering, exploring, and loading spatio-temporal datasets by providing Intake Drivers for STAC catalogs. This provides a simple toolkit for working with STAC catalogs and for loading STAC assets as xarray objects.

['S2B_22WEC_20190422_0_L2A', 'S2B_22WDB_20190422_0_L2A', 'S2B_22WFB_20190422_0_L2A', 'S2B_22WEB_20190422_0_L2A', 'S2B_22WFC_20190422_0_L2A', 'S2B_22WDC_20190422_0_L2A', 'S2A_22WEC_20190421_0_L2A', 'S2A_22WFC_20190421_0_L2A', 'S2A_22WFB_20190421_0_L2A', 'S2A_22WEB_20190421_0_L2A', 'S2A_22WFB_20190420_0_L2A', 'S2A_22WDB_20190420_1_L2A', 'S2A_22WDC_20190420_0_L2A', 'S2A_22WDC_20190420_1_L2A', 'S2A_22WEC_20190420_0_L2A', 'S2A_22WDB_20190420_0_L2A', 'S2A_22WEB_20190420_0_L2A', 'S2A_22WFC_20190420_0_L2A', 'S2A_22WEB_20190420_1_L2A']

Let’s explore the metadata and keys for the first scene

overview
thumbnail
metadata
B11
B01
B12
B02
B03
B04
AOT
B05
B06
B07
B08
B8A
B09
WVP
visual
SCL
info

We can explore the metadata for any of these:

{'href': 'https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/22/W/EB/2019/4/S2A_22WEB_20190420_0_L2A/B02.tif', 'type': 'image/tiff; application=geotiff; profile=cloud-optimized', 'title': 'Band 2 (blue)', 'proj:shape': [10980, 10980], 'proj:transform': [10, 0, 499980, 0, -10, 7700040, 0, 0, 1], 'eo:bands': [{'full_width_half_max': 0.098, 'center_wavelength': 0.4966, 'name': 'B02', 'common_name': 'blue'}], 'gsd': 10, 'roles': ['data'], 'plots': {'geotiff': {'kind': 'image', 'x': 'x', 'y': 'y', 'frame_width': 500, 'data_aspect': 1, 'rasterize': True, 'dynamic': True, 'cmap': 'viridis'}}, 'catalog_dir': ''}
Loading...
'https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/22/W/EB/2019/4/S2B_22WEB_20190422_0_L2A/B02.tif'
https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/22/W/EB/2019/4/S2A_22WEB_20190420_0_L2A/B02.tif
https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/22/W/EB/2019/4/S2B_22WEB_20190422_0_L2A/B02.tif

Open and visualize each image using RasterIO

Loading...

We can open directly into xarray using rasterIO...

Manipulating data in Xarray

Pandas and xarray have very similar structures and ways of manipulating data, but pandas excels with 2-D data and xarray is ideal for higher dimension data. Xarray introduces labels in the form of dimensions, coordinates and attributes on top of Pandas-like DataFrames.

We will only scratch the surface here on what xarray can do. To learn more, there are great xarray tutorials here: https://xarray-contrib.github.io/xarray-tutorial/online-tutorial-series/01_xarray_fundamentals.html

RasterIO and RioXarray

We can use rasterIO to easily open into an xarray DataSet:

Loading...

We can also open using rioxarray, which integrates rasterIO and xarray and is the most efficient way of opening using rasterIO:

Loading...

We can see Attributes have been added to the xarray using the same url.

Beyond what xarray and rasterIO provide, rioxarray has these added benefits (plus others):

  • Supports multidimensional datasets such as netCDF

  • Loads in the CRS, transform, and nodata metadata in standard CF & GDAL locations

  • Supports masking and scaling data

  • Loads raster metadata into the attributes

For more info: https://corteva.github.io/rioxarray/stable/index.html

Dask

Another convenient means for opening a lot of raster data into xarray is using dask. Xarray integrates with Dask to support parallel computations and streaming computation on datasets that don’t fit into memory. So this is perfect when you want to process a lot of data.

Dask divides arrays into many small pieces, called chunks, each of which is presumed to be small enough to fit into memory.

Unlike NumPy, which has eager evaluation, operations on dask arrays are lazy. Operations queue up a series of tasks mapped over blocks, and no computation is performed until you actually ask values to be computed (e.g., to print results to your screen or write to disk). At that point, data is loaded into memory and computation proceeds in a streaming fashion, block-by-block.

To expand our xarray toolbox for working with larger data sets that we don’t necessarily want entirely in memory, we will start by reading in 3 bands of a Sentinel 2 scene to xarray using dask.

S2B_22WDB_20190422_0_L2A
Loading...

Typically, it’s best to align dask chunks with the way image chunks (typically called “tiles”) are stored on disk or cloud storage buckets. The Sentinel 2 data is stored on AWS S3 in a tiled Geotiff format where tiles are 512x512, so we should pick some multiple of that, and typically aim for chunk sizes of ~100Mb (although this is subjective).

In a way that is similar to pandas, we can explore variables easily in xarray. We will first work with coordinates (equivalent to indices in pandas). Here x might often be the longitude (it can be renamed to this actually):

Loading...

We can also keep track of arbitrary metadata (called attributes) in the form of a Python dictionary, including the crs (projection). The crs here is epsg:32622.

We can apply operations over dimensions by name. Here, if we want to slice the data to only have the blue band:

Loading...

instead of loc (from pandas) we are using sel, but they function synonymously. Notice our data is found under band_data in this xarray dataset.

Mathematical operations (e.g., x - y) vectorize across multiple dimensions (array broadcasting) based on dimension names. Let’s determine the mean reflectance for the blue band:

array(4057.1724, dtype=float32)

And you can easily use the split-apply-combine paradigm with groupby, which we won’t show here.

Advanced multi-dimensional read-ins, manipulation and visualization

Now let’s open all the bands and multiple days together into an xarray. This will be a more complex xarray with an extra 'time' dimension. We have two image in the catalog we can include together.

['S2A_22WEC_20190420_0_L2A', 'S2A_22WDB_20190420_0_L2A', 'S2A_22WEB_20190420_0_L2A']

Let’s create the time variable first for the xarray time dimension. This finds the desired scene IDs in the geopandas dataframe we have above and extracts their ‘datetime’ information. These datetimes get recorded into an xarray variable object for ‘time’.

Loading...

Now we will search and collect band names for grabbing each desired band. We will just grab the bands that have 30 m pixels. This provides an example of how you can search data in the STAC catalog.

B11 20
B01 60
B12 20
B02 10
B03 10
B04 10
B05 20
B06 20
B07 20
B08 10
B8A 20
B09 60
['B02', 'B03', 'B04', 'B08']

And now open all of it...

S2A_22WEC_20190420_0_L2A
S2A_22WDB_20190420_0_L2A
S2A_22WEB_20190420_0_L2A
Loading...

We now have three Sentinel 2 scenes with all of the bands we are interested in stored in an xarray, but you can imagine that this exact code can scale to years worth of data and bands.

From here, we easily subset one image at a time or the entire xarray. Choosing to include data_array shifts the Dataset to a DataArray making it easier to plot:

2019-04-20T15:41:57.000000000
Loading...
Loading...

4. Summary

Congratulations! You’ve completed the tutorial. In this tutorial you have gained the skills to:

  • Search for optimized cloud data

  • Open data into xarray arrays, and

  • Manipulate, visualize, and explore the data

Credits
  • notebook by: Tasha Snow