Automatic Mask Generation with SAM 2¶
This notebook shows how to segment objects from an image using the Segment Anything Model 2 (SAM2) with a few lines of code.
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 -U segment-geospatial
import leafmap
from samgeo import SamGeo2
Create an interactive map¶
m = leafmap.Map(center=[29.6768, -95.3692], zoom=19)
m.add_basemap("SATELLITE")
m
Pan and zoom the map to select the area of interest. Use the draw tools to draw a polygon or rectangle on the map
if m.user_roi_bounds() is not None:
bbox = m.user_roi_bounds()
else:
bbox = [-95.3704, 29.6762, -95.368, 29.6775]
Download a sample image¶
image = "satellite.tif"
leafmap.map_tiles_to_geotiff(
output=image, bbox=bbox, zoom=20, 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 SAM class¶
sam2 = SamGeo2(model_id="sam2-hiera-large", automatic=True)
Automatic mask generation¶
Segment the image and save the results to a GeoTIFF file. Set unique=True
to assign a unique ID to each object.
sam2.generate(image)
sam2.save_masks(output="masks.tif")
sam2.show_masks(cmap="binary_r")
sam2.show_masks(cmap="jet")
Show the object annotations (objects with random color) on the map.
sam2.show_anns(axis="off", alpha=0.7, output="annotations.tif")
Compare images with a slider.
leafmap.image_comparison(
"satellite.tif",
"annotations.tif",
label1="Satellite Image",
label2="Image Segmentation",
)
Add image to the map.
m.add_raster("masks.tif", colormap="jet", layer_name="Masks", nodata=0, opacity=0.7)
m
Convert the object annotations to vector format, such as GeoPackage, Shapefile, or GeoJSON.
sam2.raster_to_vector("masks.tif", "masks.gpkg")
m.add_vector("masks.gpkg", layer_name="Objects")
Automatic mask generation options¶
There are several tunable parameters in automatic mask generation that control how densely points are sampled and what the thresholds are for removing low quality or duplicate masks. Additionally, generation can be automatically run on crops of the image to get improved performance on smaller objects, and post-processing can remove stray pixels and holes. Here is an example configuration that samples more masks:
sam2 = SamGeo2(
model_id="sam2-hiera-large",
apply_postprocessing=False,
points_per_side=32,
points_per_batch=64,
pred_iou_thresh=0.7,
stability_score_thresh=0.92,
stability_score_offset=0.7,
crop_n_layers=1,
box_nms_thresh=0.7,
crop_n_points_downscale_factor=2,
min_mask_region_area=25.0,
use_m2m=True,
)
sam2.generate(image, output="masks2.tif")
sam2.show_masks(cmap="jet")
sam2.show_anns(axis="off", alpha=0.7, output="annotations2.tif")
Compare images with a slider.
leafmap.image_comparison(
image,
"annotations2.tif",
label1="Image",
label2="Image Segmentation",
)