Batch segmentation with text prompts¶
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
Change runtime type and select
GPU as the hardware accelerator.
# %pip install segment-geospatial groundingdino-py leafmap localtileserver
import leafmap from samgeo import tms_to_geotiff, split_raster from samgeo.text_sam import LangSAM
m = leafmap.Map(center=[-22.1278, -51.4430], zoom=17, height="800px") m.add_basemap("SATELLITE") m
bbox = m.user_roi_bounds() if bbox is None: bbox = [-51.4494, -22.1307, -51.4371, -22.1244]
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
split_raster(image, out_dir="tiles", tile_size=(1000, 1000), overlap=0)
sam = LangSAM()
text_prompt = "tree"
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_batch( images='tiles', out_dir='masks', text_prompt=text_prompt, box_threshold=0.24, text_threshold=0.24, mask_multiplier=255, dtype='uint8', merge=True, verbose=True, )
m.add_raster('masks/merged.tif', cmap='viridis', nodata=0, layer_name='Mask') m.add_layer_manager() m