Supervised Wishart classification¶
This notebook shows how to apply the Wishart unsupervised classification to a PolSARpro NetCDF dataset.
Import packages and set directories¶
import os
from pathlib import Path
import xarray as xr
from polsarpro.io import open_netcdf_beam
from polsarpro.classification import wishart_supervised
# optional import for progress bar
from dask.diagnostics import ProgressBar
# change to your data paths
# original dataset
input_alos_data = Path("/data/psp/test_files/SAN_FRANCISCO_ALOS1_slc.nc")
output_dir = Path("/data/psp/res")
# Hand drawn regions
label_path = Path("../data/sample_labels_sf_alos1.nc")
Load data¶
We load the SNAP NetCDF-BEAM dataset using the open_netcdf_beam function.
To obtain such a dataset, please refer to the "Getting Started" tutorial or the quickstart-tutorial.ipynb notebook.
# uncomment to test on S matrix made with SNAP
S = open_netcdf_beam(input_alos_data)
# initial regions labeled as {1...N}, 0 for unlabelled
labels = xr.open_dataarray(label_path)
Apply the classification¶
Let's apply the algorithm and write the result to a NetCDF file. Optionally we can use a progress bar to monitor the progress of the computation.
Note: Unlike the C implementation, this version does not require precomputed H/A/Alpha parameters. However, for backward compatibility, you may provide existing parameters via the h_a_alpha_result argument. In that case, the H/A/Alpha parameters may have been computed using a different boxcar window size than the one used in this function.
# change to the name of your liking
file_out = output_dir / "psp_wishart_super.nc"
# netcdf writer cannot overwrite
if os.path.isfile(file_out):
os.remove(file_out)
with ProgressBar():
wishart_supervised(S, training_labels=labels, boxcar_size=[7, 7]).to_netcdf(file_out)
[########################################] | 100% Completed | 11.84 s [########################################] | 100% Completed | 19.13 s
Display outputs¶
We open the previously saved dataset:
res = xr.open_dataset(file_out)
Then we may plot the individual outputs:
from matplotlib.colors import ListedColormap
# Blue: sea, green: vegetation, orange: built-up
colors = ["#387EB9", "#4EAF49", "#FF7F00"]
# Create the discrete colormap
my_cmap = ListedColormap(colors)
res.wishart_supervised_class.plot.imshow(cmap=my_cmap)
<matplotlib.image.AxesImage at 0x7d57c4e513d0>