from typing import Any
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import xarray as xr
from envrs.download_path import make_url
18.1 A machine Learning Approach
In this notebook, we will focus on the classification of deforestation in Mozambique. We will be useing a Machine Learning
approach to classify the forest cover (as explained in the previous notebook) and will be covering the deforestation here, where we will specifically have a look at the changes in forest cover over time.
It is assumed here that you are already familiar with the previous notebook, since we will be useing the forest cover classification as a basis for the deforestation analysis.
dict[str, Any] = {
common_url_params: "is_zip": True,
}
= make_url(
url_before "forest_classification_2018.zarr.zip",
**common_url_params,
)= make_url(
url_after "forest_classification_2024.zarr.zip",
**common_url_params,
)= make_url(
url_dc "HLS_T36KXE_2024_b30_v2.zarr.zip",
**common_url_params,
)
https://git.geo.tuwien.ac.at/api/v4/projects/1266/repository/files/forest_classification_2018.zarr.zip/raw?ref=main&lfs=true
https://git.geo.tuwien.ac.at/api/v4/projects/1266/repository/files/forest_classification_2024.zarr.zip/raw?ref=main&lfs=true
https://git.geo.tuwien.ac.at/api/v4/projects/1266/repository/files/HLS_T36KXE_2024_b30_v2.zarr.zip/raw?ref=main&lfs=true
dict[str, Any] = {
common_params: "engine": "zarr",
"consolidated": False,
}= xr.open_dataarray(url_before, **common_params)
forest_before = xr.open_dataarray(url_after, **common_params)
forest_after = xr.open_dataset(url_dc, **common_params) img
= 1 << 0 # 0b01
bit_zero = 1 << 1 # 0b10
bit_one = 1
forest_label_value # fmt: off
= (
deforestation == forest_label_value) * bit_zero
(forest_before + (forest_after == forest_label_value) * bit_one
)# fmt: on
= int("0b01", 2) # before=1 and after=0 -> was forest but not now
deforestation_value = deforestation.where(deforestation == deforestation_value) deforestation
= mcolors.ListedColormap(["#FF2600"])
cmap_red = mcolors.ListedColormap(["#00FF20"])
cmap_green = plt.subplots()
fig, ax "Red", "Green", "Blue"]].sel(quantile=0.5).to_dataarray().plot.imshow(
img[[=True,
robust=ax,
ax
)=ax, alpha=1, cmap=cmap_red, add_colorbar=False)
deforestation.squeeze().plot.imshow(ax== forest_label_value).squeeze().plot.imshow(
forest_after.where(forest_after =ax,
ax=0.3,
alpha=cmap_green,
cmap=False,
add_colorbar
) plt.show()