Sitemap
Spatially Saying

Spatially Saying

raster2ML

Streamlining the Creation of Training Datasets for ML Object Segmentation from Geospatial Inputs

8 min readFeb 11, 2024

--

Press enter or click to view image in full size

Introduction

The intersection of Geographic Information Systems (GIS) and Machine Learning (ML) has opened up vast opportunities for innovation across numerous fields. However, one of the longstanding challenges has been the creation of suitable training datasets for ML models from complex geospatial data. This is where raster2ML comes in — a Python library that effortlessly turns raster and vector data into training datasets ready for ML object segmentation. This tool democratizes access to high-quality datasets, enabling researchers and professionals alike to unlock the full potential of their geospatial data in ML-driven projects.

Purpose of raster2ML

raster2ML serves a critical function by facilitating geospatial data conversion into formats amenable to ML processing. By leveraging advanced algorithms to process raster images and vector shapefiles, it generates training datasets that are precise and tailored for ML object segmentation tasks. This capability is pivotal for various applications, from environmental analysis to urban development planning. raster2ML is designed to ensure that the preparation of specialized training datasets is straightforward, efficient, and scalable, effectively removing a significant barrier to innovation in integrating ML with geospatial analysis.

Main Features of raster2ML

  • raster2png: Converts raster images into 8-bit PNG files, simplifying the process of preparing data for further analysis or machine learning models.
  • shp2labelme: Leverages both raster and shapefile data to generate a LabelMe-compatible JSON structure, further bridging the gap between geospatial analysis and machine learning datasets.
  • labelme2mask: Transforms LabelMe JSON files into labeled image masks, facilitating the application of machine learning algorithms for classification and pattern recognition.

Each feature is designed with user-friendliness in mind, requiring minimal commands to execute complex processes. This ease of use, combined with the tool’s powerful capabilities, makes raster2ML an indispensable resource for researchers, data scientists, and geospatial analysts alike.

Step-by-Step Guide to Using raster2ML

raster2ML offers an intuitive and efficient pathway for transforming geospatial data into training datasets for machine learning object segmentation. This guide demonstrates the utility’s capabilities through a comprehensive tutorial. Example usage is available as a Colab notebook at

Installation

Begin by installing raster2ML and cloning the repository to access example files and scripts:

!pip install raster2ML
!git clone https://github.com/spatiallysaying/raster2ML.git

Display Input Raster and Vector

Visualize the relationship between your raster (e.g., satellite imagery) and vector data (e.g., shapefiles for roads or boundaries) using raster2ML. This step enhances understanding of how these datasets interact spatially.

  • Linear Contrast Stretch: Apply a linear contrast stretch to improve image visibility without altering relative brightness values.
import rasterio
import rasterio.plot
import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np

# Function definitions for linear stretch and displaying the raster with shapefile
def linear_stretch(input_band, min_val=None, max_val=None):
# Your linear stretch code here

def display_raster_with_shapefile(raster_path, shapefile_path):
# Your display function code here
# Example usage
display_raster_with_shapefile("/path/to/raster.tif", "/path/to/vector.shp")
Press enter or click to view image in full size
Raster overlaid with vector.

The first image showcases the original geospatial data — satellite imagery (raster) overlaid with a shapefile (vector). The shapefile outlines are delineated clearly on the raster image, indicating the areas of interest for segmentation.

This visualization is crucial as it confirms that the geospatial data is accurately aligned, ensuring that the output from raster2ML will be correctly mapped.

Step 1: Convert an Input Raster to an 8-bit PNG Image

Convert your raster data into an 8-bit PNG format, making it compatible for further ML processing:

!python /path/to/raster2ML/test_raster2png.py /path/to/input_raster.tif /path/to/output_folder

Step 2: Generate a LabelMe JSON Structure

Utilize both the raster (now in PNG format) and shapefile data to create a LabelMe-compatible JSON structure. This format facilitates the annotation and preparation of data for machine learning:

!python /path/to/raster2ML/test_shp2labelme.py /path/to/png_raster /path/to/shapefile /label_field

Following the conversion process using raster2ML, we obtain a mask image. Each color in the mask represents a different class, as defined by the shapefile. The classes are easily distinguishable, which is essential for training machine learning models for object segmentation tasks.

Get Spatially Saying’s stories in your inbox

Join Medium for free to get updates from this writer.

Displaying LabelMe Overlay: Visualize the overlay of LabelMe annotations on your image to ensure the accuracy and completeness of the dataset preparation.

Image overlaid with labelme JSON
# Function definitions for displaying LabelMe overlay
def display_labelme_overlay(image_path, json_path):
# Your display function code here

# Example usage
display_labelme_overlay("/path/to/png_image", "/path/to/json_annotation")

Step 3: Transform a LabelMe JSON File into a Labeled Image (Mask)

Convert the LabelMe JSON structure into a labeled image mask, ready for use as a training dataset in machine learning models:

!python /path/to/raster2ML/test_labelme2mask.py /path/to/json_file /path/to/output_folder

To appreciate the transformation from the original data to the ML-ready format, here’s a side-by-side comparison that illustrates the accuracy and clarity of the mask of the original image. This step is critical for verifying that the conversion has succeeded and that the data is now suitable for ML segmentation models.

Visual Comparison: Display the original image alongside its corresponding mask to verify the successful creation of your training dataset.

Press enter or click to view image in full size
Original Image alongside the generated Mask.
# Function definitions for displaying raster images side by side
def display_raster_with_raster(raster_path1, raster_path2, title1=None, title2=None):
# Your comparison function code here

# Example usage for visual comparison
display_raster_with_raster("/path/to/original_image.png", "/path/to/generated_mask.png", "Original Image", "Generated Mask")

All-in-One Command

For convenience, raster2ML provides a streamlined command that encompasses the entire process, accepting georeferenced raster and vector files to generate a mask in raster format:

!python /path/to/raster2ML/raster_and_shape_to_mask.py /path/to/raster.tif /path/to/vector.shp /label_field /path/to/output_folder

This usage guide, part of our article, showcases the practical steps to harness the power of raster2ML for creating machine learning datasets from geospatial inputs. It emphasizes the utility's ease of use and the seamless workflow it offers, from data preparation to the generation of ML-ready formats, ensuring that researchers and developers can focus on their analytical tasks rather than data preprocessing complexities.

Feel free to adjust the paths and parameters according to your specific project needs. This guide is designed to be flexible, accommodating a wide range of geospatial data processing requirements.

These visual examples not only affirm the successful execution of the raster2ML processing steps but also provide a clear, tangible reference for what users can expect when they apply raster2ML to their own geospatial data sets. Including these images in the article will help readers understand the practical outcomes of using raster2ML and the quality of results it can produce.

Key Advantages of Using raster2ML

raster2ML revolutionizes the preparation of geospatial data for machine learning applications by offering a suite of unique advantages:

  1. Seamless Integration with GIS Tools: With raster2ML, users can directly leverage the full power of GIS tools and libraries, eliminating the need to navigate through external annotation tools such as LabelMe, VGG Annotator, CVAT, or SageMaker. This direct integration simplifies the workflow, allowing for a more efficient and streamlined data preparation process that taps directly into the rich functionalities of GIS platforms.
  2. Native Spatial Format Operation: One of the standout features of raster2ML is its ability to operate within native spatial formats, seamlessly bridging the gap to ML-compatible formats. This ensures that the spatial integrity and richness of the original data are maintained while making them readily accessible for ML applications. By handling data in its native spatial format raster2ML not only preserves the quality of the data but also enhances its compatibility with machine learning models.
  3. Streamlined Pipeline for Dataset Generation: raster2ML introduces a streamlined pipeline that significantly reduces the complexity and time in generating ML object segmentation datasets. With a single click, users can transform their geospatial data into ML-ready formats, bypassing the cumbersome silos of intermediate tasks typically associated with this process. This efficiency boost accelerates the dataset preparation phase and enables users to focus more on analysis and model training, speeding up the overall project timeline.
  4. Efficient Handling of Large-Scale Geospatial Imagery: Traditional ML-specific annotation tools often struggle with the immense size of satellite and aerial images, which can hinder their processing and analysis capabilities. raster2ML, however, is engineered to efficiently handle these large-scale images, enabling the processing and analysis of extensive geospatial datasets without compromising performance. This robust handling is particularly vital for applications that require the manipulation of high-resolution satellite imagery, where every pixel counts for accurate object segmentation and analysis.

Extended Capabilities After Mask Generation

Note on Post-Processing with GDAL:

After generating a mask with raster2ML, users have the flexibility to process the data further to fit their specific machine-learning model requirements. Utilizing gdal_retile.py of the GDAL library effectively tile the 8-bit image and the corresponding mask into smaller, more manageable chips. These chips can be sized at 512x512, 256x256, or any other dimensions that are most suitable for the chosen model.

This tiling process is particularly beneficial when dealing with large images, as it allows for easier handling and processing within the ML models without losing the georeferencing information, which is crucial for spatial analyses.

Direct Use with Pre-Tiled Geospatial Data:

Additionally, if users begin with a large input image that is already tiled and includes georeference information for each tile, raster2ML can be directly applied to these smaller segments. This capability is especially useful for efficiently processing large datasets and immediately integrating them into the ML workflow.

By providing these versatile post-processing options, raster2ML ensures that users can tailor their dataset preparation to the requirements of their specific projects and machine learning models, streamlining the path from raw geospatial data to actionable insights.

Upcoming Functionality in the Next Version of raster2ML:

We are continuously striving to enhance raster2ML and make it even more powerful and user-friendly. In the next version of the library, we plan to introduce an integrated functionality that will allow users to directly tile the 8-bit image and the corresponding mask into smaller chips right within raster2ML. This feature will support various chip sizes, such as 512x512 or 256x256 pixels, to accommodate different machine-learning model requirements.

This upcoming capability is designed for both scenarios where users start with large, untiled images or pre-tiled geospatial data that retains georeference information. It will simplify the workflow even further, making raster2ML a one-stop solution for preparing geospatial data for machine-learning object segmentation tasks.

Stay tuned for this update, as it will open up new levels of efficiency and convenience for your geospatial machine learning projects.

Citation

For those interested in citing raster2ML:

@misc{spatiallysaying_2023_raster2ML,
title={raster2ML: Utility designed to process a Raster file and its corresponding shapefile to produce a raster mask file},
author={Durga Prasad, Dhulipudi},
year={2023},
url={https://github.com/spatiallysaying/raster2ML}
}Conclusion

raster2ML It is a tool and a catalyst for innovation in the GIS+ML domain. Its ease of use and powerful functionality make it an indispensable asset for anyone looking to merge the precision of GIS with the predictive power of ML.

--

--