<jupyter_start><jupyter_text>The goal of this notebook is to demonstrate how to obtain a superpixel segmentation of a raster and then store these as a vector format for visualization and later analyses.A nice example of superpixel segmentation using the module we are using can be found [here](https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_segmentations.html).<jupyter_code>import rasterio
import numpy as np
import matplotlib.pyplot as plt
from skimage.segmentation import felzenszwalb
from pathlib import Path
from skimage.color import label2rgb
import sys
sys.path.append('../../rscube')
from rio_tools import polygonize_array_to_shapefile<jupyter_output><empty_output><jupyter_text>Data Paths<jupyter_code>data_path_name = 'data/tif_datacube/'
data_path = Path(data_path_name)
data_path.exists()
output_path_name = 'out'
out_path = Path(output_path_name)
out_path.mkdir(exist_ok=True, parents=True)
tif_paths = sorted(list(data_path.glob('*.tif')))
tif_paths<jupyter_output><empty_output><jupyter_text>Visualizing the Landsat rasterWe will use the landsat raster for visualization.<jupyter_code>with rasterio.open(tif_paths[2]) as ds:
    landsat_2015_mosaic_gdal = ds.read()
    landsat_2015_mosaic = landsat_2015_mosaic_gdal.transpose([1, 2, 0])
    profile = ds.profile
plt.imshow(landsat_2015_mosaic[..., :3])<jupyter_output><empty_output><jupyter_text>So you may ask what the `transpose` was for. Well, gdal and numpy require arrays of slightly different format. The former reads arrays as Band Interleaved by Pixel (BIP) and the latter, Band Sequential (BSQ) (see [here](http://idlcoyote.com/ip_tips/where3.html)). The landsat has 4 bands (or channels). Rasterio (a gdal wrapper) reads the array with the channels at the front, but numpy requires these channels to be at the back.<jupyter_code>landsat_2015_mosaic_gdal.shape, landsat_2015_mosaic.shape<jupyter_output><empty_output><jupyter_text>The superpixel segmentation takes several parameters that can be read about in the [docs](https://scikit-image.org/docs/dev/api/skimage.segmentation.htmlskimage.segmentation.felzenszwalb). To summarize, the `min_size` specifies the minimum size of all segments in the image, `scale` controls the approximate irregularity of the segments (precisely, a larger `scale` parameter determines if smaller sized segments are merged more easily during the formation of the final segmentation), and `sigma` is set to 0 so there is no smoothing done before segmentation.<jupyter_code>superpixel_labels = felzenszwalb(landsat_2015_mosaic,
                                 min_size=20,
                                 scale=.5,
                                 sigma=0,
                                 # The landsat mosaic has 4 channels
                                 multichannel=True,
                                 )<jupyter_output>/Users/cmarshak/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py:3331: RuntimeWarning: Got image with third dimension of 4. This image will be interpreted as a multichannel 2d image, which may not be intended.
  exec(code_obj, self.user_global_ns, self.user_ns)<jupyter_text>We can visualize the segments assigning random colors to each label.<jupyter_code>superpixel_labels_rgb = label2rgb(superpixel_labels)
plt.imshow(superpixel_labels_rgb)<jupyter_output>/Users/cmarshak/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:1: FutureWarning: The new recommended value for bg_label is 0. Until version 0.19, the default bg_label value is -1. From version 0.19, the bg_label default value will be 0. To avoid this warning, please explicitly set bg_label value.
  """Entry point for launching an IPython kernel.<jupyter_text>Now, we save the labels as polygons with each segment corresponding to a geometry.<jupyter_code>polygonize_array_to_shapefile(superpixel_labels, profile, out_path/'superpixels')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07660878447395301, 'fraction_numerical': 0.016598569969356484, 'mean_word_length': 4.718248175182482, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 27, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '65299', 'license': 'Apache-2.0', 'n_tokens_mistral': 1248, 'n_tokens_neox': 1160, 'n_words': 356, 'path': 'notebooks/supervised_classification/2_Superpixel_Generation.ipynb', 'repo_name': 'simard-landscape-lab/rscube', 'size': '3916'}