You can run this notebook in a live session Binder or view it on Github.

# To start, we install Rasterio, a Python module for interacting with gridded spatial data
!pip install rasterio
Collecting rasterio
  Downloading (19.7MB)

Collecting click-plugins (from rasterio)
Collecting affine (from rasterio)
Requirement already satisfied: attrs in /home/travis/miniconda/envs/test/lib/python3.6/site-packages (from rasterio) (19.1.0)
Requirement already satisfied: click<8,>=4.0 in /home/travis/miniconda/envs/test/lib/python3.6/site-packages (from rasterio) (7.0)
Collecting cligj>=0.5 (from rasterio)
Collecting snuggs>=1.4.1 (from rasterio)
Requirement already satisfied: numpy in /home/travis/miniconda/envs/test/lib/python3.6/site-packages (from rasterio) (1.16.3)
Requirement already satisfied: pyparsing in /home/travis/miniconda/envs/test/lib/python3.6/site-packages (from snuggs>=1.4.1->rasterio) (2.4.0)
Installing collected packages: click-plugins, affine, cligj, snuggs, rasterio
Successfully installed affine-2.2.2 click-plugins-1.1.1 cligj-0.5.0 rasterio-1.0.22 snuggs-1.4.3

Reading and manipulating tiled GeoTIFF datasets

This notebook shows how to perform simple calculations with a GeoTIFF dataset using XArray and Dask. We load and rescale a Landsat 8 image and compute NDVI (Normalized difference vegetation index). This can be used to distinguish green vegetation from areas of bare land or water.

We’ll use an image of the Denver, USA area taken in July 2018.

RGB image

Download data

First, we download the dataset. We are using an image from the cloud-hosted Landsat 8 public dataset and each band is available as a separate GeoTIFF file.

import os
import json
import rasterio
import requests

import matplotlib.pyplot as plt
%matplotlib inline
nir_filename = ''
red_filename = ''
mtl_filename = ''
def download_file(in_filename, out_filename):
    if not os.path.exists(out_filename):
        print("Downloading", in_filename)
        response = requests.get(in_filename)
        with open(out_filename, 'wb') as f:
download_file(nir_filename, 'nir.tif')
download_file(red_filename, 'red.tif')
download_file(mtl_filename, 'meta.json')

Check image metadata

Let’s see if the image is tiled so we can select a chunk size.

img ='red.tif')
[(512, 512)]

The image has separate blocks for each band with block size 512 x 512.

Create XArray datasets

import xarray as xr
red = xr.open_rasterio('red.tif', chunks={'band': 1, 'x': 1024, 'y': 1024})
nir = xr.open_rasterio('nir.tif', chunks={'band': 1, 'x': 1024, 'y': 1024})
<xarray.DataArray (band: 1, y: 7841, x: 7721)>
dask.array<shape=(1, 7841, 7721), dtype=uint16, chunksize=(1, 1024, 1024)>
  * band     (band) int64 1
  * y        (y) float64 4.423e+06 4.423e+06 4.423e+06 ... 4.188e+06 4.188e+06
  * x        (x) float64 4.134e+05 4.134e+05 4.135e+05 ... 6.45e+05 6.45e+05
    transform:   (30.0, 0.0, 413385.0, 0.0, -30.0, 4423215.0)
    crs:         +init=epsg:32613
    res:         (30.0, 30.0)
    is_tiled:    1
    nodatavals:  (nan,)

Each dataset’s data is a Dask array.

dask.array<open_rasterio-33289c035acf68a2306c3dde206f7096<this-array>, shape=(1, 7841, 7721), dtype=uint16, chunksize=(1, 1024, 1024)>

Optional: create a Dask client

You can start a Dask client to monitor execution with the dashboard.

import dask
from dask.distributed import Client
client = Client(processes=False)



  • Workers: 1
  • Cores: 2
  • Memory: 7.84 GB

Rescale bands using Landsat metadata

The Landsat Level 1 images are delivered in a quantized format. This has to be converted to top-of-atmosphere reflectance using the provided metadata.

First we define convenience functions to load the rescaling factors and transform a dataset. The red band is band 4 and near infrared is band 5.

def load_scale_factors(filename, band_number):
    with open(filename) as f:
        metadata = json.load(f)
    M_p = metadata['L1_METADATA_FILE'] \
                  ['RADIOMETRIC_RESCALING'] \
    A_p = metadata['L1_METADATA_FILE'] \
                  ['RADIOMETRIC_RESCALING'] \
    return M_p, A_p
def calculate_reflectance(ds, band_number, metafile='meta.json'):
    M_p, A_p = load_scale_factors(metafile, band_number)
    toa = M_p * ds + A_p
    return toa
red_toa = calculate_reflectance(red, band_number=4)
nir_toa = calculate_reflectance(nir, band_number=5)

Because the transformation is composed of arithmetic operations, execution is delayed and the operations are parallelized automatically.

dask.array<add, shape=(1, 7841, 7721), dtype=float64, chunksize=(1, 1024, 1024)>

The resulting image has floating point data with magnitudes appropriate to reflectance. This can be checked by computing the range of values in an image:

red_max, red_min, red_mean = dask.compute(
    red_toa.max(dim=['x', 'y']),
    red_toa.min(dim=['x', 'y']),
    red_toa.mean(dim=['x', 'y'])

Calculate and display NDVI

Now that we have the image as reflectance values, we are ready to compute NDVI.

\[NDVI = \frac{NIR - Red}{NIR + Red}\]

This highlights areas of healthy vegetation with high NDVI values, which appear as green in the image below.

ndvi = (nir_toa - red_toa) / (nir_toa + red_toa)
ndvi2d = ndvi.squeeze()
im = ndvi2d.compute().plot.imshow(cmap='BrBG', vmin=-0.5, vmax=1)