@malette/sam
v0.1.3
Published
SAM components
Readme
SAM 前端组件
SAM (Segment Anything Model) 前端组件库,用于图像分割和标注。
项目结构
.
├── dist/ # 构建输出目录
├── src/ # 源代码
│ ├── components/ # 组件目录
│ │ ├── helpers/ # 辅助工具和函数
│ │ └── hooks/ # React Hooks
│ ├── Segment.tsx # 主要的分割组件
│ └── index.ts # 入口文件
├── example/ # 开发和测试示例
└── tsup.config.ts # 构建配置开发环境
我们提供了一个简单的开发环境用于实时调试组件。
安装依赖
# 安装主项目依赖
npm install
# 安装示例应用依赖
cd example
npm install启动开发服务器
# 在 example 目录中
cd example
npm run dev这将启动一个开发服务器,通常在 http://localhost:5173 上运行。
实时调试和修改
- 修改
src目录中的任何文件 - Vite 的 HMR(热模块替换)会自动应用这些更改
- 在浏览器中实时查看您的修改效果
构建组件库
npm run build这将在 dist 目录中生成构建后的文件。
使用组件
import Segment from '@malette/sam';
function App() {
return (
<Segment
model={model}
apiUrl="https://your-api-endpoint.com/sam"
imageSrc="path/to/image.jpg"
onLoad={() => console.log('模型加载完成')}
/>
);
}属性说明
| 属性 | 类型 | 描述 | |------|------|------| | model | InferenceSession | null | ONNX模型实例 | | apiUrl | string | SAM API端点URL | | imageSrc | string | 要分割的图像URL | | onLoad | () => void | 模型加载完成后的回调函数 |
Installation
npm install @malette/sam onnxruntime-webQuick Example
import React, { useState, useEffect } from 'react';
import { InferenceSession } from 'onnxruntime-web';
import Segment from '@malette/sam';
// 模型地址,需要替换成自己的模型地址,可下载此模型然后上传到自己的 OSS
const MODEL_FILE_URL =
'https://industryai.oss-cn-beijing.aliyuncs.com/ai/style-fusion/2024-06-20/51836dc7-08cd-4604-a0ed-647c50c92ce8.onnx';
const Demo = () => {
const [model, setModel] = useState<InferenceSession | null>(null);
useEffect(() => {
const initModel = async () => {
try {
const url: string = MODEL_FILE_URL;
const session = await InferenceSession.create(url);
setModel(session);
} catch (e) {
console.error(e);
}
};
initModel();
}, []);
return (
<Segment
model={model}
apiUrl="https://adic.d.design/api/v1/sam/embedding"
imageSrc="https://img.alicdn.com/imgextra/i1/O1CN01HuBEuL1kdrIW2tdXB_!!6000000004707-0-tps-1072-603.jpg"
/>
);
};参数
model
- Type:
Object
ONNX 模型的运行时实例。
apiUrl
- Type:
String
api接口地址。
imgSrc
- Type:
String
图片地址
positiveClickColor
- Type:
String - Default:
#F6FF00
正向选择的圆点颜色
negativeClickColor
- Type:
String - Default:
#FF8CB2
反向选择的圆点颜色
svgMaskFill
- Type:
String - Default:
rgba(216, 255, 0, 0.3)
选中区域的蒙层颜色
stroke
- Type:
String - Default:
#D8FF00
选中区域的外轮廓颜色
onLoad
- Type:
Function - Default:
null
初始化成功后的回调。
方法
handleUndoInteraction()
撤销。
handleRedoInteraction()
重做。
handleResetInteraction()
重置组件状态。
getCroppedCanvas(padding)
- padding (optional):
- Type:
Boolean - Default:
false - 设置为
true可以保留图片的边框.
- Type:
获取裁剪图片的Canvas。
setScale(scale)
- scale:
- Type:
Number
- Type:
设置缩放。
