Skip to content

103 raster colormap

image image image

Applying a custom colormap to a raster dataset

Uncomment the following line to install the leafmap package.

1
# %pip install -U "leafmap[raster]"
1
2
3
import leafmap
import rioxarray as rxr
from leafmap.common import get_image_colormap

Download a sample dataset from GitHub. This dataset is a GeoTIFF file containing the surface water extent in Las Vegas. This dataset is a NASA OPERA DSWx product.

1
url = "https://github.com/opengeos/datasets/releases/download/raster/OPERA_L3_DSWx_WTR.tif"
1
filepath = leafmap.download_file(url, quiet=True)

Load the dataset as an xarray DataArray.

1
2
da = rxr.open_rasterio(filepath)
# da

The original raster file contains a colormap. We can get the colormap from the raster file as follows:

1
colormap = get_image_colormap(filepath)

Alternatively, we can define a custom colormap as follows:

1
2
3
4
5
6
7
8
9
colormap = {
    0: (255, 255, 255),
    1: (0, 0, 255),
    2: (180, 213, 244),
    252: (0, 255, 255),
    253: (175, 175, 175),
    254: (0, 0, 127),
    255: (0, 0, 0),
}

You can apply any data processing types to the xarray DataArray. After that, convert the xarray DataArray to an image in the memory and apply the custom colormap.

1
image = leafmap.array_to_image(da, colormap=colormap)

Define a legend dictionary to display the legend.

1
2
3
4
5
6
7
8
9
legend_dict = {
    "0: Not water": (255, 255, 255),
    "1: Open water": (0, 0, 255),
    "2: Partial surface water": (180, 213, 244),
    "252: Snow/ice": (0, 255, 255),
    "253: Cloud/cloud shadow": (175, 175, 175),
    "254: Ocean masked": (0, 0, 127),
    "255: Fill value (no data)": (0, 0, 0),
}

Visualize the raster dataset with the custom colormap and the legend.

1
2
3
4
5
m = leafmap.Map()
m.add_basemap("HYBRID")
m.add_raster(image, layer_name="Water", nodata=255)
m.add_legend(legend_dict=legend_dict)
m

image