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.

Notebook examples

Exploring Inland Water Bodies with Sentinel-2 data in EDC

Loading...
Loading...
Loading...

author: Anca Anghelea, based on a notebook by: William Ray

Several lakes and other inland water bodies are featured on EO Dashboard. The datasets supporting the various geo-stories are accessible by means similar to what you will learn in this notebook.

Explore EO Dashboard Stories on Oceans and Inland Water.

In this notebook

In this demonstration Jupyter Notebook, we will be visualising and analysing inland water bodies using Sentinel data, demonstrating the use of EDC.

We are going to use the EDC and its associated libaries and APIs to do this. In this notebook we will learn how to:

  • Build a cube

  • Visualise a variable in your data cube

  • Create a new variable

  • Create a new variable using a threshold

  • Visualise a spatial subset of a variable over time

  • Create a new variable based upon space and time.

Configuration

Before acccessing the data, we will start by importing the necessary Python libraries (already configured in your EDC workspace), and generate credentials automatically to access the services.

Loading...

Define an AOI

Next, we will define our area of interest using a bounding box. This must be provided in WGS84 coordinates to build the cube.

We have chosen an AOI covering the natural park “Valli di Comacchio” in Italy.

Loading...

How to build a data cube

Firstly, we will go through how to build a data cube.

We are going to visualise the floods using Sentinel-2 imagery. Sentinel-2 is part of the Copernicus programme and collects multispectral data globally with a revisit time of 5 days. The satellite’s multispectral imager provides collects data in 13 spectral bands spanning from the visible and near infrared to the shortwave infrared. The visible and near infrared data we will use in this example is collected at 10m resolution.

Check Sentinel-2 L2A available bands

Using EDC inbuilt functions that query Sentinel Hub services, we can easily list the available bands for a given dataset to help us build the cube!

['B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B09', 'B11', 'B12', 'SCL', 'SNW', 'CLD', 'viewZenithMean', 'viewAzimuthMean', 'sunZenithAngles', 'sunAzimuthAngles', 'AOT', 'CLM', 'CLP']

Build an xcube

In the following cell we will specify the input parameters needed to build an xcube array. The following parameters are specified:

  • dataset_name: the Sentinel Hub identification of the dataset. Here we will call S2L2A for Sentinel-2 L2A. All available datasets can be listed with SH.dataset_names

  • band_names: the band names to be used in the xcube array (see previous code cell). Here, we will call the B02, B03, B04, B08, CLM (Blue, Green, Red, NIR, Cloud Mask) bands.

  • bbox: the bounding box that sets the extent of the AOI. Because we are using the default WGS84 coordinate system here, the CRS parameter doesn’t need to be set.

  • spatial_res: the spatial resolution of the rasters contained in the xcube array. The spatial resolution is expressed in the units of the coordinate system used. Therefore, in this example, the spatial resolution is set in degrees. For an approximate pixel size of 10 meters, we set the resolution to 0.000089 degrees.

  • time_range: a list of two dates [start_date, end_date] forming a time period for which all acquisitions will be returned. Sentinel-2 L2A data is available from October 2016 onwards. In this example, we will fetch data for June 2023 - mid July 2023.

  • time_tolerance: The tolerance used to identify whether a dataset should still be included within a time period. Here, 30m corresponds to 30 minutes, thus avoiding duplicate datasets.

Open the xcube

In the following cell we open the cube and display its contents. The automatically generated credentials obtained earlier in this Jupyter Notebook are specified as a parameter when opening the cube. It’s important to note that at this stage, we’re not processing anything, just generating a cube on the fly with data ready to be called when needed for analysis.

Once you open the cube, you can visualise the contents. You can view the number of timestamps and a list of them all too in the Coordinates tab. You can also visualise the seperate variables, with information on the size of the variables and their data type too.

/home/conda/users/52c397debe78d7686aa36bd394f6f113e95009637029c5b71995fe48a567dcd4-20230418-061740-771350-145-edc-2023.03-02/lib/python3.9/site-packages/xcube_sh/sentinelhub.py:243: UserWarning: The argument 'infer_datetime_format' is deprecated and will be removed in a future version. A strict version of it is now the default, see https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. You can safely remove this argument.
  dt = pd.to_datetime(dt,
/home/conda/users/52c397debe78d7686aa36bd394f6f113e95009637029c5b71995fe48a567dcd4-20230418-061740-771350-145-edc-2023.03-02/lib/python3.9/site-packages/xcube_sh/sentinelhub.py:243: UserWarning: The argument 'infer_datetime_format' is deprecated and will be removed in a future version. A strict version of it is now the default, see https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. You can safely remove this argument.
  dt = pd.to_datetime(dt,
Loading...

How to visualise your datacube

Now we have built our cube, let’s visualise the data! We are going to visualise a True Color image and an NDWI image in the same plot. In the below cell you can see we are selecting each band for 10:00:00 16th June 2023, and selecting the nearest acquisition to this date and time. We then stack the three bands and plot this using Matplotlib. We will call the three bands in the visible spectrum. In addition we will multiply the reflectance values by 5 to brighten the image.

Another way to visualise the extent of surface water is to use the Normalised Difference Water Index (NDWI). This is an index that can be used to extract surface water using multispectral imagery such as Sentinel-2. We can calculate the index with the Green and NIR bands as stated below, and add it into the data cube as a new variable.

NDWI = Green - NIR / Green + NIR

For this we are going to create a new variable in the next cell. To create the new variable we are using two existing variables defined as s2_cube.B03 and s2_cube.B08. We then insert these variables into an index formula to create NDWI. Once ndwi has been calculated it’s attributed a long_name and units before being defined as ndwi so that we can call it as a definition later in the notebook.

Next we want to plot both the True Color image and the NDWI in the same plot. We will use Matplotlib to achieve this.

Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
<Figure size 1000x1500 with 2 Axes>

This looks good, and the extent of the flood waters is visualised really nicely here. The 10m resolution also enables us to see individual fields around the lake with the linear boundaries of the fields highlighted nicely in the high resolution image provided by the 10m Sentinel 2 bands.

Let’s try and visualise some more dates in the time period that we are examining;

/tmp/ipykernel_490/1879529373.py:32: UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect.
  plt.tight_layout()
<Figure size 1500x1100 with 7 Axes>

We could use the NDWI to estimate the surface water extent. The more images we have available, the more reliable the estimate can be. Examining the satellite images above we observe that not all of the images would be useful, as some of the lake area is covered with clouds. To overcome this limitation and have a denser time series we could rely on synthetic aperture radar observations, for example from the Copernicus Sentinel-1 platform.

Sentinel-1 description

Like Sentinel-2, Sentinel-1 is also part of the Copernicus programme and collects data globally with a revisit time of 5 days. In contrast to Sentinel-2, Sentinel-1 SAR is an active sensor using SAR signals recording the backscatter. Due to the wavelengths used, SAR is not hindered by clouds and can be operated day and night.

Check Sentinel-1 GRD available bands

Using EDC inbuilt functions that query Sentinel Hub services, we can easily list the available bands for a given dataset.

['VV', 'HH', 'VH', 'localIncidenceAngle', 'scatteringArea', 'shadowMask', 'HV']

Build an xcube

In the following cell we will specify the input parameters needed to build an xcube array. The following parameters are specified:

  • dataset_name: the Sentinel Hub identification of the dataset. Here we will call S1GRD for Sentinel-1 GRD. All available datasets can be listed with SH.dataset_names

  • band_names: the band names to be used in the xcube array (see previous code cell). Here, we will call just the VV polarisation band.

  • bbox: the bounding box that sets the extent of the AOI. Because we are using the default WGS84 coordinate system here, the CRS parameter doesn’t need to be set.

  • spatial_res: the spatial resolution of the rasters contained in the xcube array. The spatial resolution is expressed in the units of the coordinate system used. Therefore, in this example, the spatial resolution is set in degrees. For an approximate pixel size of 10 meters, we set the resolution to 0.000089 degrees.

  • time_range: a list of two dates [start_date, end_date] forming a time period for which all acquisitions will be returned. Sentinel-1 GRD data is available from February 2015 onwards. In this example, we will fetch data for June 2023 - mid July 2023.

  • time_tolerance: The tolerance used to identify whether a dataset should still be included within a time period. Here, 30m corresponds to 30 minutes, thus avoiding duplicate datasets.

Open the xcube

In the following cell we open the cube and display its contents. The automatically generated credentials obtained earlier in this Jupyter Notebook are specified as a parameter when opening the cube.

/home/conda/users/52c397debe78d7686aa36bd394f6f113e95009637029c5b71995fe48a567dcd4-20230418-061740-771350-145-edc-2023.03-02/lib/python3.9/site-packages/xcube_sh/sentinelhub.py:243: UserWarning: The argument 'infer_datetime_format' is deprecated and will be removed in a future version. A strict version of it is now the default, see https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. You can safely remove this argument.
  dt = pd.to_datetime(dt,
/home/conda/users/52c397debe78d7686aa36bd394f6f113e95009637029c5b71995fe48a567dcd4-20230418-061740-771350-145-edc-2023.03-02/lib/python3.9/site-packages/xcube_sh/sentinelhub.py:243: UserWarning: The argument 'infer_datetime_format' is deprecated and will be removed in a future version. A strict version of it is now the default, see https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. You can safely remove this argument.
  dt = pd.to_datetime(dt,
Loading...

Visualising the water areas using SAR

We are going to use the VV band to visualise the flooding. From our earlier visualisation, we know that the area had some cloud coverage around the date 2023-07-04. We will search for Sentinel-1 acquisitions around that date in order to obtain a denser time series.

Radar data has very large dynamic range a very imbalanced histogram (>95% of all values are smaller than 1, but the remaining 5 % can be impractically large). Thus, to obtain a visualisation with a better contrast in which the water bodies would be darker and the land pixels would be brighter, it is recommended to convert the data to log-scale. To convert the pixel values from Digital Number to decibels we can mutiply the log10 of each DN pixel by 10. Secondly, as there will be pixels with a value of -inf after this operation, we need to account for this with the second function which will automatically assign 0 to these pixels.

Like previously, we are going to visualise the VV_dB variable we have just generated for our AOI.

/home/conda/users/52c397debe78d7686aa36bd394f6f113e95009637029c5b71995fe48a567dcd4-20230418-061740-771350-145-edc-2023.03-02/lib/python3.9/site-packages/dask/core.py:119: RuntimeWarning: divide by zero encountered in log10
  return func(*(_execute_task(a, cache) for a in args))
<Figure size 1000x1000 with 2 Axes>

This looks very similar to the NDWI we derived earlier showing the water extent fairly clearly (the blue areas). Let’s visualise it over several timestamps to confirm that this is a good variable to use to generate a lake mask.

<Figure size 1600x1100 with 7 Axes>

Depending on the local conditions (e.g. terrain orientation, slope) and weather conditions, optical or radar imagery may be more useful. In this case both types of observations seem to provide a good view of the water surface area extent.

Next we will generate a flood mask using a threshold.

  • for SAR images, generally, as a good rule of thumb, in the VV band, values below -20 dB are usually surface water. We will try this value first, but we will also look to visualise how the flood mask changes if we adjust the threshold value.

  • observing the NDWI range of values, we can chose values above 0.25 to correspond to the water class.

First, let’s generate the new variable using the .where function in xarray.

At first glance, the below cell may not make much sense. It may read that the step 1 function as assigning a value of 1 to pixels in VV_dB that are equal or more than -20. However, what is actually happening is that the .where function preserves all the pixel values in the variable that are below -20 and assigns everything else a value of 1. More can be found in the xarray documentation http://xarray.pydata.org/en/stable/generated/xarray.DataArray.where.html

Next let’s see what happens to the mask extent if we change the threshold to -15 dB and -25dB:

Next we will plot the new thresholds we want to test:

/home/conda/users/52c397debe78d7686aa36bd394f6f113e95009637029c5b71995fe48a567dcd4-20230418-061740-771350-145-edc-2023.03-02/lib/python3.9/site-packages/dask/core.py:119: RuntimeWarning: divide by zero encountered in log10
  return func(*(_execute_task(a, cache) for a in args))
<Figure size 2000x1200 with 3 Axes>
<Figure size 2000x1200 with 3 Axes>

Observe the differences in the water mask due to the threshold.

Estimating the surface water area extent

Let’s estimate the area covered by water during the time period we are examining.

We can also estimate which is the area that is most covered by water by dividing the sum of the water pixels by the number of timesteps in the data cube (the count).

Now let’s plot the water_average into a plot:

<Figure size 1000x1000 with 2 Axes>

This looks great, we have identified the lake area very clearly here and can also observe how the lake may change in size over time.

Access environmental variables and other datasets

This Notebook demonstrates how to:

request data from selected Copernicus Services, request data from Copernicus Climate Data Store, request data from ESA Climate Change Initiative.