今天场合用SAM大模型samgeo的sam2 box prompts案例。
应用场景为有卫星遥感影像(satellit.tiff)和比较粗的初始建筑轮廓矢量数据(building_bboxes.geojson),通过SAM大模型sam2对图像进行分割,获取更为准确的建筑轮廓数据(building_masks.tiff;building_vector.geojson;building_regularized.geojson)。项目参考地址如下:
由于原来项目需要科学上网,为了方便大家,将下载的数据也分享给大家。另外代码中也将调用改为了调用本地文件,大家可以下载数据试试。数据免费下载地址为:
import leafmap
from samgeo import SamGeo2, raster_to_vector, regularize
#导入所需要的模块
image = r'D:/test/satellite.tif'
geojson = r'D:/test/building_bboxes.geojson'
#导入数据,需要注意坐标系一定要一致,文件地址自行修改
sam = SamGeo2(
model_id="sam2-hiera-large",
automatic=False,
)
#导入sam2模型
sam.set_image(image)
#配置图片
output_masks = "building_masks.tif"
sam.predict(
boxes=geojson,
point_crs="EPSG:4326",
output=output_masks,
dtype="uint8",
multimask_output=False,
)
#定义输出文件和运行sam2
output_vector = "building_vector.geojson"
raster_to_vector(output_masks, output_vector)
#将输出的tiff格式文件转换为geojson
output_regularized = "building_regularized.geojson"
regularize(output_vector, output_regularized)
#将building_regularized.geojson文件做规则化处理,边框更加规则
由于原项目leafmap加载失败,我用gis软件把过程可视化展示如下:
(上图 黄色框为building_bboxes.geojson可视化效果,后续作为sam2的box prompts)
(上图为sam2模型输出的building_masks.tiff)
(上图为将tiff格式转换为geojson格式,building_vector.geojson)
(上图为对geojosn文件进行了规则化处理得到的building_regularized.geojson)