Segmenting remote sensing imagery with text prompts and the Segment Anything Model (SAM)¶
This notebook shows how to generate object masks from text prompts with the Segment Anything Model (SAM).
Make sure you use GPU runtime for this notebook. For Google Colab, go to Runtime
-> Change runtime type
and select GPU
as the hardware accelerator.
Install dependencies¶
Uncomment and run the following cell to install the required dependencies.
# %pip install segment-geospatial groundingdino-py leafmap localtileserver
import leafmap
from samgeo import tms_to_geotiff
from samgeo.text_sam import LangSAM
Create an interactive map¶
m = leafmap.Map(center=[-22.17615, -51.253043], zoom=18, height="800px")
m.add_basemap("SATELLITE")
m
Download a sample image¶
Pan and zoom the map to select the area of interest. Use the draw tools to draw a polygon or rectangle on the map
bbox = m.user_roi_bounds()
if bbox is None:
bbox = [-51.2565, -22.1777, -51.2512, -22.175]
image = "Image.tif"
tms_to_geotiff(output=image, bbox=bbox, zoom=19, source="Satellite", overwrite=True)
You can also use your own image. Uncomment and run the following cell to use your own image.
# image = '/path/to/your/own/image.tif'
Display the downloaded image on the map.
m.layers[-1].visible = False
m.add_raster(image, layer_name="Image")
m
Initialize LangSAM class¶
The initialization of the LangSAM class might take a few minutes. The initialization downloads the model weights and sets up the model for inference.
sam = LangSAM()
Specify text prompts¶
text_prompt = "tree"
Segment the image¶
Part of the model prediction includes setting appropriate thresholds for object detection and text association with the detected objects. These threshold values range from 0 to 1 and are set while calling the predict method of the LangSAM class.
box_threshold
: This value is used for object detection in the image. A higher value makes the model more selective, identifying only the most confident object instances, leading to fewer overall detections. A lower value, conversely, makes the model more tolerant, leading to increased detections, including potentially less confident ones.
text_threshold
: This value is used to associate the detected objects with the provided text prompt. A higher value requires a stronger association between the object and the text prompt, leading to more precise but potentially fewer associations. A lower value allows for looser associations, which could increase the number of associations but also introduce less precise matches.
Remember to test different threshold values on your specific data. The optimal threshold can vary depending on the quality and nature of your images, as well as the specificity of your text prompts. Make sure to choose a balance that suits your requirements, whether that's precision or recall.
sam.predict(image, text_prompt, box_threshold=0.24, text_threshold=0.24)
Visualize the results¶
Show the result with bounding boxes on the map.
sam.show_anns(
cmap="Greens",
box_color="red",
title="Automatic Segmentation of Trees",
blend=True,
)
Show the result without bounding boxes on the map.
sam.show_anns(
cmap="Greens",
add_boxes=False,
alpha=0.5,
title="Automatic Segmentation of Trees",
)
Show the result as a grayscale image.
sam.show_anns(
cmap="Greys_r",
add_boxes=False,
alpha=1,
title="Automatic Segmentation of Trees",
blend=False,
output="trees.tif",
)
Convert the result to a vector format.
sam.raster_to_vector("trees.tif", "trees.shp")
Show the results on the interactive map.
m.add_raster("trees.tif", layer_name="Trees", palette="Greens", opacity=0.5, nodata=0)
style = {
"color": "#3388ff",
"weight": 2,
"fillColor": "#7c4185",
"fillOpacity": 0.5,
}
m.add_vector("trees.shp", layer_name="Vector", style=style)
m
Interactive segmentation¶
sam.show_map()