135 segmentation
Earth Engine Image Segmentation with the Segment Anything Model
Uncomment the following line to install geemap if needed.
In [ ]:
Copied!
# !pip install -U geemap
# !pip install -U geemap
In [ ]:
Copied!
# %pip install segment-geospatial pycrs
# %pip install segment-geospatial pycrs
In [ ]:
Copied!
import ee
import geemap
from samgeo import SamGeo
import ee
import geemap
from samgeo import SamGeo
In [ ]:
Copied!
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
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
In [ ]:
Copied!
bbox = Map.user_roi_coords()
if bbox is None:
bbox = [-122.2666, 37.8682, -122.252, 37.8752]
bbox = Map.user_roi_coords()
if bbox is None:
bbox = [-122.2666, 37.8682, -122.252, 37.8752]
In [ ]:
Copied!
geemap.ee_to_geotiff(
image, "naip.tif", bbox, zoom=17, vis_params={"bands": ["R", "G", "B"]}
)
geemap.ee_to_geotiff(
image, "naip.tif", bbox, zoom=17, vis_params={"bands": ["R", "G", "B"]}
)
In [ ]:
Copied!
sam = SamGeo(
model_type="vit_h",
checkpoint="sam_vit_h_4b8939.pth",
device=None,
sam_kwargs=None,
)
sam = SamGeo(
model_type="vit_h",
checkpoint="sam_vit_h_4b8939.pth",
device=None,
sam_kwargs=None,
)
In [ ]:
Copied!
sam.generate("naip.tif", output="masks.tif", foreground=True, unique=True)
sam.generate("naip.tif", output="masks.tif", foreground=True, unique=True)
In [ ]:
Copied!
sam.show_masks(cmap="binary_r")
sam.show_masks(cmap="binary_r")
In [ ]:
Copied!
sam.show_anns(axis="off", alpha=1, output="annotations.tif")
sam.show_anns(axis="off", alpha=1, output="annotations.tif")
In [ ]:
Copied!
Map.add_raster("annotations.tif", opacity=0.5, layer_name="Masks")
Map
Map.add_raster("annotations.tif", opacity=0.5, layer_name="Masks")
Map
In [ ]:
Copied!
sam.tiff_to_vector("masks.tif", "masks.shp")
sam.tiff_to_vector("masks.tif", "masks.shp")
In [ ]:
Copied!
style = {
"color": "#3388ff",
"weight": 2,
"fillColor": "#7c4185",
"fillOpacity": 0.5,
}
Map.add_vector("masks.shp", layer_name="Vector", style=style)
Map
style = {
"color": "#3388ff",
"weight": 2,
"fillColor": "#7c4185",
"fillOpacity": 0.5,
}
Map.add_vector("masks.shp", layer_name="Vector", style=style)
Map