# Calculating band indices¶

Keywords data used; sentinel-2, band index; NDVI, band index; NDWI, band index; MNDWI

## Background¶

Remote sensing indices are combinations of spectral bands used to highlight features in the data and the underlying landscape. For example, one of the most commonly used indices is the Normalised Difference Vegetation Index (NDVI), which uses the ratio of the red and near-infrared (NIR) band to highlight healthy vegetation (see here for a deeper explanation). Using Digital Earth Africa’s archive of analysis-ready satellite data, we can easily calculate a wide range of remote sensing indices that can be used to assist in mapping and monitoring features like vegetation and water consistently through time, or as inputs to machine learning or classification algorithms.

## Description¶

This notebook demonstrates how to:

• Calculate an index manually using xarray

• Calculate one or multiple indices using the function calculate_indices from deafrica_bandindices.py

## Getting started¶

To run this analysis, run all the cells in the notebook, starting with the “Load packages” cell.

[1]:

%matplotlib inline

import datacube
import matplotlib.pyplot as plt
import xarray as xr

from deafrica_tools.plotting import rgb
from deafrica_tools.bandindices import calculate_indices

/env/lib/python3.6/site-packages/geopandas/_compat.py:88: UserWarning: The Shapely GEOS version (3.7.2-CAPI-1.11.0 ) is incompatible with the GEOS version PyGEOS was compiled with (3.9.0-CAPI-1.16.2). Conversions between both will be slow.
shapely_geos_version, geos_capi_version_string


### Connect to the datacube¶

[2]:

dc = datacube.Datacube(app='Calculating_band_indices')


## Create a query and load satellite data¶

To demonstrate how to compute a remote sensing index, we first need to load in a time series of satellite data for an area. We will use data from the Sentinel-2 satellite:

[3]:

lat, lon = 13.94, -16.54
buffer = 0.125

# Create a reusable query
query = {
'x': (lon-buffer, lon+buffer),
'y': (lat+buffer, lat-buffer),
'time': ('2019-06', '2020-06'),
'resolution': (-30, 30)
}

# Identify the most common projection system in the input query
output_crs = mostcommon_crs(dc=dc, product='s2_l2a', query=query)

# Load available data from Sentinel-2 and filter to retain only times
# with at least 99% good data
products=['s2_l2a'],
min_gooddata=0.99,
measurements=['red', 'green', 'blue', 'swir_1', 'swir_2', 'nir', 'nir_2'],
output_crs=output_crs,
**query)


Using pixel quality parameters for Sentinel 2
Finding datasets
s2_l2a
Counting good quality pixels for each time step
Filtering to 4 out of 78 time steps with at least 99.0% good quality pixels

[4]:

ds

[4]:

<xarray.Dataset>
Dimensions:      (time: 4, x: 907, y: 928)
Coordinates:
* time         (time) datetime64[ns] 2019-10-20T11:47:38 ... 2020-03-18T11:...
* y            (y) float64 1.556e+06 1.556e+06 ... 1.528e+06 1.528e+06
* x            (x) float64 3.2e+05 3.201e+05 3.201e+05 ... 3.472e+05 3.472e+05
spatial_ref  int32 32628
Data variables:
red          (time, y, x) float32 2067.0 1000.0 1000.0 ... 1899.0 1930.0
green        (time, y, x) float32 1707.0 1065.0 1143.0 ... 1332.0 1337.0
blue         (time, y, x) float32 896.0 452.0 520.0 ... 1030.0 1009.0 993.0
swir_1       (time, y, x) float32 4049.0 3072.0 3083.0 ... 4802.0 4834.0
swir_2       (time, y, x) float32 3372.0 2174.0 2119.0 ... 4011.0 4112.0
nir          (time, y, x) float32 4196.0 4068.0 4026.0 ... 3014.0 2842.0
nir_2        (time, y, x) float32 4361.0 4318.0 4312.0 ... 3163.0 3050.0
Attributes:
crs:           epsg:32628
grid_mapping:  spatial_ref

### Plot the first image to see what our area looks like¶

We can use the rgb function to plot the timesteps in our dataset as true colour RGB images:

[5]:

# Plot as an RGB image

rgb(ds, col='time')


## Manually calculate an index¶

One of the most commonly used remote sensing indices is the Normalised Difference Vegetation Index or NDVI. This index uses the ratio of the red and near-infrared (NIR) bands to identify live green vegetation. The formula for NDVI is:

\begin{split}\begin{aligned} \text{NDVI} & = \frac{(\text{NIR} - \text{Red})}{(\text{NIR} + \text{Red})} \\ \end{aligned}\end{split}

When interpreting this index, high values indicate vegetation, and low values indicate soil or water.

[6]:

# Calculate NDVI using the formula above
ds['NDVI_manual'] = (ds.nir - ds.red) / (ds.nir + ds.red)

# Plot the results for one time step to see what they look like:
ds.NDVI_manual.plot(col='time', vmin=-0.50, vmax=0.8, cmap='RdYlGn')


[6]:

<xarray.plot.facetgrid.FacetGrid at 0x7fa9148b6d68>


In the image above, vegetation shows up as green (NDVI > 0). Sand shows up as yellow (NDVI ~ 0) and water shows up as red (NDVI < 0).

## Use the calculate_indices function to calculate an index¶

The calculate_indices function provides an easier way to calculate a wide range of remote sensing indices, including:

• AWEI_ns (Automated Water Extraction Index,no shadows, Feyisa 2014)

• AWEI_sh (Automated Water Extraction Index,shadows, Feyisa 2014)

• BAEI (Built-Up Area Extraction Index, Bouzekri et al. 2015)

• BAI (Burn Area Index, Martin 1998)

• BSI (Bare Soil Index, Rikimaru et al. 2002)

• BUI (Built-Up Index, He et al. 2010)

• CMR (Clay Minerals Ratio, Drury 1987)

• EVI (Enhanced Vegetation Index, Huete 2002)

• FMR (Ferrous Minerals Ratio, Segal 1982)

• IOR (Iron Oxide Ratio, Segal 1982)

• LAI (Leaf Area Index, Boegh 2002)

• MNDWI (Modified Normalised Difference Water Index, Xu 1996)

• MSAVI (Modified Soil Adjusted Vegetation Index, Qi et al. 1994)

• NBI (New Built-Up Index, Jieli et al. 2010)

• NBR (Normalised Burn Ratio, Lopez Garcia 1991)

• NDBI (Normalised Difference Built-Up Index, Zha 2003)

• NDCI (Normalised Difference Chlorophyll Index, Mishra & Mishra, 2012)

• NDMI (Normalised Difference Moisture Index, Gao 1996)

• NDSI (Normalised Difference Snow Index, Hall 1995)

• NDVI (Normalised Difference Vegetation Index, Rouse 1973)

• NDWI (Normalised Difference Water Index, McFeeters 1996)

• SAVI (Soil Adjusted Vegetation Index, Huete 1988)

• TCB (Tasseled Cap Brightness, Crist 1985)

• TCG (Tasseled Cap Greeness, Crist 1985)

• TCW (Tasseled Cap Wetness, Crist 1985)

• WI (Water Index, Fisher 2016)

The calculate_indices function can be found in the deafrica_tools.bandindices script. This script provides all required band math involved in creating each index and is worth a look.

### Using calculate_indices to get the same result¶

The function provides a simple way to calculate band indices without needing to explicitly write code for the band math.

[7]:

calculate_indices(ds, index=['NDVI'], collection='s2')

[7]:

<xarray.Dataset>
Dimensions:      (time: 4, x: 907, y: 928)
Coordinates:
* time         (time) datetime64[ns] 2019-10-20T11:47:38 ... 2020-03-18T11:...
* y            (y) float64 1.556e+06 1.556e+06 ... 1.528e+06 1.528e+06
* x            (x) float64 3.2e+05 3.201e+05 3.201e+05 ... 3.472e+05 3.472e+05
spatial_ref  int32 32628
Data variables:
red          (time, y, x) float32 2067.0 1000.0 1000.0 ... 1899.0 1930.0
green        (time, y, x) float32 1707.0 1065.0 1143.0 ... 1332.0 1337.0
blue         (time, y, x) float32 896.0 452.0 520.0 ... 1030.0 1009.0 993.0
swir_1       (time, y, x) float32 4049.0 3072.0 3083.0 ... 4802.0 4834.0
swir_2       (time, y, x) float32 3372.0 2174.0 2119.0 ... 4011.0 4112.0
nir          (time, y, x) float32 4196.0 4068.0 4026.0 ... 3014.0 2842.0
nir_2        (time, y, x) float32 4361.0 4318.0 4312.0 ... 3163.0 3050.0
NDVI_manual  (time, y, x) float32 0.33993295 0.605367 ... 0.19111484
NDVI         (time, y, x) float32 0.33993298 0.605367 ... 0.19111484
Attributes:
crs:           epsg:32628
grid_mapping:  spatial_ref
[8]:

# Calculate NDVI using calculate indices
ds_ndvi = calculate_indices(ds, index='NDVI', collection='s2')

# Plot the results
ds_ndvi.NDVI.plot(col='time', vmin=-0.50, vmax=0.8, cmap='RdYlGn')


[8]:

<xarray.plot.facetgrid.FacetGrid at 0x7fa9146b99b0>


Note: when using the calculate_indices function, it is important to set the collection parameter correctly. This is because different satellite collections use different names for the same bands, which can lead to invalid results if not accounted for. For Sentinel-2 , specify collection='s2'. For Landsat Collection 2, specify collection='c2'.

### Using calculate_indices to calculate multiple indices at once¶

The calculate_indices function makes it straightforward to calculate multiple remote sensing indices in one line of code.

In the example below, we will calculate NDVI as well as two common water indices: the Normalised Difference Water Index (NDWI), and the Modified Normalised Difference Index (MNDWI). The new indices will appear in the list of data_variables below:

[9]:

# Calculate multiple indices
ds_multi = calculate_indices(ds, index=['NDVI', 'NDWI', 'MNDWI'], collection='s2')

print(ds_multi)

<xarray.Dataset>
Dimensions:      (time: 4, x: 907, y: 928)
Coordinates:
* time         (time) datetime64[ns] 2019-10-20T11:47:38 ... 2020-03-18T11:...
* y            (y) float64 1.556e+06 1.556e+06 ... 1.528e+06 1.528e+06
* x            (x) float64 3.2e+05 3.201e+05 3.201e+05 ... 3.472e+05 3.472e+05
spatial_ref  int32 32628
Data variables:
red          (time, y, x) float32 2067.0 1000.0 1000.0 ... 1899.0 1930.0
green        (time, y, x) float32 1707.0 1065.0 1143.0 ... 1332.0 1337.0
blue         (time, y, x) float32 896.0 452.0 520.0 ... 1030.0 1009.0 993.0
swir_1       (time, y, x) float32 4049.0 3072.0 3083.0 ... 4802.0 4834.0
swir_2       (time, y, x) float32 3372.0 2174.0 2119.0 ... 4011.0 4112.0
nir          (time, y, x) float32 4196.0 4068.0 4026.0 ... 3014.0 2842.0
nir_2        (time, y, x) float32 4361.0 4318.0 4312.0 ... 3163.0 3050.0
NDVI_manual  (time, y, x) float32 0.33993295 0.605367 ... 0.19111484
NDVI         (time, y, x) float32 0.33993298 0.605367 ... 0.19111484
NDWI         (time, y, x) float32 -0.42165002 -0.585038 ... -0.360134
MNDWI        (time, y, x) float32 -0.40687978 -0.48513418 ... -0.5666828
Attributes:
crs:           epsg:32628
grid_mapping:  spatial_ref

[10]:

# Plot the NDWI results
ds_multi.NDWI.plot(col='time', robust=True, cmap='PuBu')

[10]:

<xarray.plot.facetgrid.FacetGrid at 0x7fa914705518>

[11]:

# Plot the MNDWI results
ds_multi.MNDWI.plot(col='time', robust=True, cmap='PuBu')

[11]:

<xarray.plot.facetgrid.FacetGrid at 0x7fa9143d2cc0>


We can also drop the original satellite bands from the dataset using drop=True. The dataset produced below should now only include the new 'NDVI', 'NDWI', 'MNDWI' bands under data_variables:

[12]:

# Calculate multiple indices and drop original bands
ds_drop = calculate_indices(ds, index=['NDVI', 'NDWI', 'MNDWI'], drop=True, collection='s2')
print(ds_drop)

Dropping bands ['red', 'green', 'blue', 'swir_1', 'swir_2', 'nir', 'nir_2', 'NDVI_manual']
<xarray.Dataset>
Dimensions:      (time: 4, x: 907, y: 928)
Coordinates:
* time         (time) datetime64[ns] 2019-10-20T11:47:38 ... 2020-03-18T11:...
* y            (y) float64 1.556e+06 1.556e+06 ... 1.528e+06 1.528e+06
* x            (x) float64 3.2e+05 3.201e+05 3.201e+05 ... 3.472e+05 3.472e+05
spatial_ref  int32 32628
Data variables:
NDVI         (time, y, x) float32 0.33993298 0.605367 ... 0.19111484
NDWI         (time, y, x) float32 -0.42165002 -0.585038 ... -0.360134
MNDWI        (time, y, x) float32 -0.40687978 -0.48513418 ... -0.5666828
Attributes:
crs:           epsg:32628
grid_mapping:  spatial_ref


Contact: If you need assistance, please post a question on the Open Data Cube Slack channel or on the GIS Stack Exchange using the open-data-cube tag (you can view previously asked questions here). If you would like to report an issue with this notebook, you can file one on Github.

Compatible datacube version:

[13]:

print(datacube.__version__)

1.8.4.dev52+g07bc51a5


Last Tested:

[14]:

from datetime import date
print(date.today())

2021-04-15