python本地离线调用meta的开源sam分割模型segment-anything点击分割图片示例代码
代码语言:python
所属分类:其他
代码描述:python本地离线调用meta的开源sam分割模型segment-anything点击分割图片示例代码
代码标签: python 本地 离线 调用 meta 开源 分割 sam 模型segment-anything
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
#pip install fastapi uvicorn python-multipart opencv-python numpy torch torchvision segment-anything
import os
import sys
import cv2
import numpy as np
import torch
import base64
import requests
from fastapi import FastAPI, UploadFile, Form
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from segment_anything import sam_model_registry, SamPredictor
# ================= 配置区域 =================
# 模型类型: vit_b (默认, 均衡), vit_l (大), vit_h (巨大)
MODEL_TYPE = "vit_b"
# 对应权重的下载地址 (Meta官方源)
CHECKPOINT_URL = "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth"
CHECKPOINT_PATH = "sam_vit_b_01ec64.pth"
# 设备选择: 优先使用 GPU (CUDA) 或 Mac (MPS),否则使用 CPU
device = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
print(f"正在使用设备: {device}")
# ================= 自动下载权重 =================
def download_checkpoint():
if not os.path.exists(CHECKPOINT_PATH):
print(f"未检测到模型权重文件,正在下载 {MODEL_TYPE} 模型 (约375MB)...")
print("请耐心等待,下载完成后将自动启动服务...")
try:
response = requests.get(CHECKPOINT_URL, stream=True)
response.raise_.........完整代码请登录后点击上方下载按钮下载查看















网友评论0