Earth Engine Image Segmentation with the Segment Anything Model
Uncomment the following line to install geemap if needed.
# !pip install -U geemap
# %pip install segment-geospatial
import ee
import geemap
from samgeo import SamGeo
Map = geemap.Map()
point = ee.Geometry.Point(-122.259679, 37.871838)
collection = (
ee.ImageCollection('USDA/NAIP/DOQQ')
.filterBounds(point)
.filterDate('2008-01-01', '2018-01-01')
.filter(ee.Filter.listContains("system:band_names", "N"))
)
image = collection.first()
Map.addLayer(image, {}, 'NAIP')
Map.centerObject(point, 16)
Map
bbox = Map.user_roi_coords()
if bbox is None:
bbox = [-122.2666, 37.8682, -122.252, 37.8752]
geemap.ee_to_geotiff(
image, 'naip.tif', bbox, zoom=17, vis_params={'bands': ['R', 'G', 'B']}
)
sam = SamGeo(
model_type="vit_h",
checkpoint="sam_vit_h_4b8939.pth",
device=None,
sam_kwargs=None,
)
sam.generate("naip.tif", output="masks.tif", foreground=True, unique=True)
sam.show_masks(cmap="binary_r")
sam.show_anns(axis="off", alpha=1, output="annotations.tif")
Map.add_raster("annotations.tif", alpha=0.5, layer_name="Masks")
Map
sam.tiff_to_vector("masks.tif", "masks.shp")
style = {
"color": "#3388ff",
"weight": 2,
"fillColor": "#7c4185",
"fillOpacity": 0.5,
}
Map.add_vector('masks.shp', layer_name="Vector", style=style)
Map