103 raster colormap
In [1]:
Copied!
# %pip install -U "leafmap[raster]"
# %pip install -U "leafmap[raster]"
In [2]:
Copied!
import leafmap
import rioxarray as rxr
from leafmap.common import get_image_colormap
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.
In [3]:
Copied!
url = "https://github.com/opengeos/datasets/releases/download/raster/OPERA_L3_DSWx_WTR.tif"
url = "https://github.com/opengeos/datasets/releases/download/raster/OPERA_L3_DSWx_WTR.tif"
In [4]:
Copied!
filepath = leafmap.download_file(url, quiet=True)
filepath = leafmap.download_file(url, quiet=True)
Load the dataset as an xarray DataArray.
In [5]:
Copied!
da = rxr.open_rasterio(filepath)
# da
da = rxr.open_rasterio(filepath)
# da
The original raster file contains a colormap. We can get the colormap from the raster file as follows:
In [6]:
Copied!
colormap = get_image_colormap(filepath)
colormap = get_image_colormap(filepath)
Alternatively, we can define a custom colormap as follows:
In [7]:
Copied!
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),
}
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.
In [8]:
Copied!
image = leafmap.array_to_image(da, colormap=colormap)
image = leafmap.array_to_image(da, colormap=colormap)
Define a legend dictionary to display the legend.
In [9]:
Copied!
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),
}
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.
In [10]:
Copied!
m = leafmap.Map()
m.add_basemap("HYBRID")
m.add_raster(image, layer_name="Water", nodata=255)
m.add_legend(legend_dict=legend_dict)
m
m = leafmap.Map()
m.add_basemap("HYBRID")
m.add_raster(image, layer_name="Water", nodata=255)
m.add_legend(legend_dict=legend_dict)
m
Out[10]: