Applying WOfS Bitmasking

Keywords data used; WOfS, data methods; wofs_fuser, analysis; masking

Background

The Water Observations from Space (WOfS) product shows water observed by Landsat satellites over Africa.

Individual water classified images are called Water Observation Feature Layers (WOFLs), and are created in a 1-to-1 relationship with the input satellite data. Hence there is one WOFL for each satellite dataset processed for the occurrence of water.

Description

This notebook explains both the structure of the WOFLs, and how you can use this for powerful and flexible image masking.

The data in a WOFL is stored as a bit field. This is a binary number, where each digit of the number is independantly set or not based on the presence (1) or absence (0) of a particular attribute (water, cloud, cloud shadow etc). In this way, the single decimal value associated to each pixel can provide information on a variety of features of that pixel.

The notebook demonstrates how to:

  1. Load WOFL data for a given location and time period

  2. Inspect the WOLF bit flag information

  3. Use the WOFL bit flags to create a binary mask


Getting started

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

After finishing the analysis, you can modify some values in the “Analysis parameters” cell and re-run the analysis to load WOFLs for a different location or time period.

Load packages

[1]:
%matplotlib inline

import datacube
from datacube.storage import masking
import matplotlib.pyplot as plt
import numpy as np

from deafrica_tools.plotting import display_map
from deafrica_tools.datahandling import wofs_fuser, mostcommon_crs
/env/lib/python3.6/site-packages/datacube/storage/masking.py:8: DeprecationWarning: datacube.storage.masking has moved to datacube.utils.masking
  category=DeprecationWarning)
/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="Applying_WOfS_bitmasking")

Analysis parameters

To load WOFL data, we can first create a re-usable query that will define the spatial extent and time period we are interested in, as well as other important parameters that are used to correctly load the data.

[3]:
lat, lon =  -4.9, 39.2
buffer = 0.125

x = (lon-buffer, lon+buffer)
y =  (lat+buffer, lat-buffer)

# Create a reusable query
query = {
    'x': x,
    'y': y,
    'time': ('2018-10-01', '2018-12-01'),
    'resolution': (-30, 30)
}

output_crs = mostcommon_crs(dc=dc, product='ga_ls8c_wofs_2', query=query)

View the selected location

[4]:
display_map(x=x, y=y)
[4]:

Load WOFL data

As WOFLs are created scene-by-scene, and some scenes overlap, it’s important when loading data to group_by solar day, and ensure that the data between scenes is combined correctly by using the WOfS fuse_func. This will merge observations taken on the same day, and ensure that important data isn’t lost when overlapping datasets are combined.

[5]:
# Load the data from the datacube
wofls = dc.load(product="ga_ls8c_wofs_2", output_crs=output_crs, group_by="solar_day",
                            fuse_func=wofs_fuser, **query)
[6]:
# Plot the loaded WOFLs
wofls.water.plot(col="time", col_wrap=3)
plt.show()
../../../_images/sandbox_notebooks_Frequently_used_code_Applying_WOfS_bitmasking_16_0.png
[7]:
# Select one image of interest (`time=2` selects the third observation)
wofl = wofls.isel(time=2)

Understanding the WOFLs

As mentioned above, WOFLs are stored as a binary number, where each digit of the number is independantly set or not based on the presence (1) or absence (0) of a particular feature. Below is a breakdown of which bits represent which features, along with the decimal value associated with that bit being set to true.

Attribute

Bit / position

Decimal value

No data

0: 0------- or 1-------

1

Non contiguous

1: -0------ or -1------

2

Sea (not used)

2: --0----- or --1-----

4

Terrain or low solar angle

3: ---0---- or ---1----

8

High slope

4: ----0--- or ----1---

16

Cloud shadow

5: -----0-- or -----1--

32

Cloud

6: ------0- or ------1-

64

Water

7: -------0 or -------1

128

The values in the above plots are the decimal representation of the combination of set flags. For example a value of 136 indicates water (128) AND terrain shadow / low solar angle (8) were observed for the pixel, whereas a value of 144 would indicate water (128) AND high slope (16).

This flag information is available inside the loaded data and can be visualised as below

[8]:
# Display details of available flags
flags = masking.describe_variable_flags(wofls)
flags["bits"] = flags["bits"].astype(str)
flags.sort_values(by="bits")
[8]:
bits values description
nodata 0 {'0': False, '1': True} No data
contiguous 1 {'0': True, '1': False} Contiguity
sea 2 {'0': False, '1': True} Sea
cloud_shadow 5 {'0': False, '1': True} Cloud shadow
cloud 6 {'0': False, '1': True} Cloudy
water_observed 7 {'0': False, '1': True} Classified as water by the decision tree
dry [7, 6, 5, 4, 3, 1, 0] {'0': True} Clear and dry
wet [7, 6, 5, 4, 3, 1, 0] {'128': True} Clear and Wet
[9]:
# Show areas flagged as water only (with no other flags set)
(wofl.water == 128).plot.imshow()
plt.show()
../../../_images/sandbox_notebooks_Frequently_used_code_Applying_WOfS_bitmasking_23_0.png

Masking

We can convert the WOFL bit field into a binary array containing True and False values. This allows us to use the WOFL data as a mask that can be applied to other datasets.

The make_mask function allows us to create a mask using the flag labels (e.g. “wet” or “dry”) rather than the binary numbers we used above.

[10]:
# Create a mask based on all 'wet' pixels
wetwofl = masking.make_mask(wofl, wet=True)
wetwofl.water.plot();
../../../_images/sandbox_notebooks_Frequently_used_code_Applying_WOfS_bitmasking_25_0.png

Create custom masks by combining flags

Flags can be combined. When chaining flags together, they will be combined in a logical AND fashion. This process works by passing a dictionary with true/false values to the make_mask function. This allows you to chose whether you want to remove clouds and/or cloud shadows from imagery.

[11]:
# Clear (no clouds and shadow)
clear = {"cloud_shadow": False, "cloud": False}

cloudfree = masking.make_mask(wofl, **clear)
cloudfree.water.plot();
../../../_images/sandbox_notebooks_Frequently_used_code_Applying_WOfS_bitmasking_27_0.png

Or, to look at only the clear areas which are good quality data and not wet, we can use the ‘dry’ flag.

[12]:
# clear and dry mask
good_data_mask = masking.make_mask(wofl, dry=True)
good_data_mask.water.plot();
../../../_images/sandbox_notebooks_Frequently_used_code_Applying_WOfS_bitmasking_29_0.png

Additional information

License: The code in this notebook is licensed under the Apache License, Version 2.0. Digital Earth Africa data is licensed under the Creative Commons by Attribution 4.0 license.

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 datetime
datetime.today().strftime('%Y-%m-%d')
[14]:
'2021-04-20'