@bunnio/rembg-web (英语)
网络背景删除 - 类型脚本/Java脚本端口 丹尼尔加蒂斯/伦布克 被设计在使用ONNX Runtime Web的浏览器中直接运行.
页:1 二. 支助 实例 二. 支助 时间 二. 支助 问题
几分钟后开始使用
在您的工程中安装 :
npm install @bunnio/rembg-web onnxruntime-web
# or
yarn add @bunnio/rembg-web onnxruntime-web
使用嵌入式 :
ES模块 :
<head>
<!-- Load ONNX Runtime Web -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ort.min.js"></script>
</head>
<body>
<script type="module">
import {
remove,
rembgConfig,
} from 'https://unpkg.com/@bunnio/rembg-web@latest/dist/index.js';
// If you want to use the huggingface hosted model (only for dev)
// Configure model base URL
rembgConfig.setBaseUrl(
'https://huggingface.co/bunnio/dis_anime/resolve/main'
);
// Basic usage
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const result = await remove(file);
const url = URL.createObjectURL(result);
// Display result
document.getElementById('result').src = url;
</script>
</body>
UMD: (英语)
<head>
<!-- Make sure to load runtimes in the header, before the scripts is called -->
<!-- Load ONNX Runtime Web -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ort.min.js"></script>
<script src="https://unpkg.com/@bunnio/rembg-web@latest/dist/index.umd.min.js"></script>
</head>
<script>
// If you want to use the huggingface hosted model (only for dev)
// Configure model base URL
rembgWeb.rembgConfig.setBaseUrl(
'https://huggingface.co/bunnio/dis_anime/resolve/main'
);
// Basic usage
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const result = await rembgWeb.remove(file);
const url = URL.createObjectURL(result);
// Display result
document.getElementById('result').src = url;
</script>
现场预览 :
业绩
在@3.87Ghz(x5687),单核心运行时间(没有线程),没有WebNN或WebGPU(不是说这很重要)上被测试. (见下文)
| 型号 | Anime 示例( 毫秒) | 车厢示例( 毫秒) | 人类实例( ms) | 植物示例 |
|---|---|---|---|---|
| u2netp 数据 | 1002.34 (韩语) | 916.45亿 | 961.62亿 | 1005.66亿 |
| 锡卢埃塔 | 2060.13 (韩语) | 2007.23ms (英语) | 1940.59亿 | 1962.44亿 |
| u2net 人文主题 | 2534.33 (中文(简体) ) | 2723.88亿 | 2706.10亿 | 2747.44毫米口径 |
| u2net (中文(简体) ) | 第2711.10号决议 | 2621.96亿 | 2688.20亿 | 2521.23毫米口径 |
| 网络动画 | 710.79 (中文(简体) ) | 7054.62亿 | 6975.49分钟 | 7641.50毫米口径 |
| 一般用途 | 7194.93 (英语) | 7064.19亿 | 7285.58亿 | 7667.17亿 |
| u2net 布料 seg | 15150.91 (英语) | 14794.81亿 | 14949.86亿 | 14931.25毫米口径 |
平均20起“预测”结果
可用模式
u2net模型, silueta, 综合安全分遣队(inet-general, isnet-anime)
未计划
双RefNet 家族
由于某些原因 Bir RefNet Simple 开始有问题 onyx-web, 目前我不打算添加.
我可能会试试拥抱脸的版本 看看它是否有效
规模问题
所有其他的模型都有显著的尺寸,使得它作为web dev类工具的可操作性更低. 如果有需求,我可以有一个裂缝 对于它,请随意创建一个特性请求.
CORS 问题
由于这些模型预计将在浏览器中运行,可能会有皮层问题
默认情况下, 所有模型都期望您在本地服务相应的 onx 配置文件
- /型号/u2net 服装 seg.onnx
- /型号/u2net human seg.onnx
- /型号/u2net.onnx
- /型号/u2netp.onnx
- /型号/英网-通用.onnx
- (原始内容存档于2019-09-26) (英语). /models/isnet-anime.onnx
- /型号/silueta.onnx)
.
大测试崩溃
我花了四个小时 试图理解为什么 测试一开始没有工作, 最终有一个外卖
网络gl
结果质量取决于webgl的可用性,所以如果测试它确保启用了旗帜(默认是)
见:剧作家. config.ts
重要:网络NN
WebNN的支持正在起作用,但是在我的个人测试中,我并没有看到明显的区别. 这是因为WebNN仍然使用CPU.
如果要检查设备上的贝壳,可以使用"基准"演示.
• 重要:网络GPU
WebGPU支持得到实施和提供,但目前所有的模型都没有兼容ONNX Runtime Web中的WebGPU执行提供者.
虽然WebGPU将提供显著的性能改进,但目前的模型执行需要WebGL或CPU执行. 由于ONNX Runtime Web为这些模型类型添加了WebGPU支持,因此包含WebGPU支持,用于未来的相容性.
目前,使用WebGL或CPU执行供应商进行最优化的相容性.
QQ 重要: 自定义模型
在使用自定义模型时,必须管理模型和会话缓存!
如果您不确定最后的自定义模型是否和你现在试图使用的相同, 最好只禁用缓存( 有旗帜) .
您可以使用 DataURL- s 在本地存储文件, 并将其传递给会话 Factory .
AI 下面生成的信息
一个基于网络的背景去除库由AI模型提供动力. 这是流行版本的 TypeScript/ JavaScript 端口 缩写 Python库,旨在使用ONNX Runtime Web在浏览器中直接运行.
特征
- 🚀 浏览器本地: 完全使用 Web Assembly 在浏览器中运行
- 🎯 多个AI模型: 支持U2Net家庭模式优化,以适应不同的使用案例
- 📱 无依赖: 不需要服务器 - 一切运行客户端( 模式托管除外)
- 🎨 弹性输入: 接受文件、 Blob、 矩阵缓冲器、 HTML ImageElement, 或 HTML CanvasElement
- ⚡ 缓存: 自动模式和会话缓存,以提高性能
- 🔧 可自定义: 支持自定义模型和后处理选项
- 🚀 WebNN 支持:通过Web神经网络API实现可选硬件加速(Chrome 119+,Edge 119+)
- 🎮 WebGPU 支持系统:通过WebGPU API实现高性能GPU加速(Chrome 113+,Edge 113+)
可用模式
- u2net (中文(简体) ): 普通用途背景去除(默认)
- u2netp 数据: U2Net 的轻量级版本
- u2net 人文主题:优化人类主体
- u2net 布料 seg: 服装分块专用
- 一般用途: 通用病例综合安全分遣队模型(更精确,更大的模型)
- 网络动画: 为动漫/曼加风格图像优化了DIS模型
- 锡卢埃塔: 清除背景的Silueta模型
- u2net 客户端: 使用自定义的 ONNX 模型
安装
npm install @bunnio/rembg-web onnxruntime-web
# or
yarn add @bunnio/rembg-web onnxruntime-web
CDN 使用量
您也可以直接从 CDN 中使用 rembg-web 不安装:
<script type="module">
import {
remove,
newSession,
} from 'https://unpkg.com/@bunnio/rembg-web@latest/dist/index.js';
// Your code here
</script>
快速启动
import { remove, newSession } from '@bunnio/rembg-web';
// Basic usage
const fileInput = document.getElementById('fileInput') as HTMLInputElement;
const file = fileInput.files[0];
const result = await remove(file);
const url = URL.createObjectURL(result);
// With custom options
const result = await remove(file, {
onlyMask: true, // Return only the mask
postProcessMask: true, // Apply smoothing
bgcolor: [255, 0, 0, 255], // Red background
session: newSession('u2net_human_seg'), // Use specific model
onProgress: info => {
console.log(`${info.step}: ${info.progress}% - ${info.message}`);
},
});
// With WebNN acceleration (optional)
const webnnSession = newSession('u2net', undefined, {
preferWebNN: true,
webnnDeviceType: 'gpu',
webnnPowerPreference: 'high-performance',
});
const acceleratedResult = await remove(file, { session: webnnSession });
// With WebGPU acceleration (optional)
const webgpuSession = newSession('u2net', undefined, {
preferWebGPU: true,
webgpuPowerPreference: 'high-performance',
});
const webgpuResult = await remove(file, { session: webgpuSession });
// With both WebNN and WebGPU (priority: WebNN > WebGPU > WebGL > CPU)
const hybridSession = newSession('u2net', undefined, {
preferWebNN: true,
preferWebGPU: true,
webnnDeviceType: 'gpu',
webnnPowerPreference: 'high-performance',
webgpuPowerPreference: 'high-performance',
});
const hybridResult = await remove(file, { session: hybridSession });
模型设置
要使用这些模型,您需要下载并将ONNX模型文件放入您的公共目录:
下载模型
使用提供的脚本下载所需的模型文件 :
# Download all models
yarn fetch-models
# Download a specific model
yarn fetch-models u2net.onnx
# Force re-download all models
yarn fetch-models --force
脚本将从 GitHub 版本下载模型并将其放入 public/models/。在您的浏览器索引DB中缓存模型,供将来使用.
示范信息
| 型号 | 大小 | 输入大小 | 使用大小写 |
|---|---|---|---|
| u2net (中文(简体) ) | ~176MB 坐标 | 320x320 (英语) | 普通用途(违约) |
| u2netp 数据 | ~4.7MB 坐标 | 320x320 (英语) | 重量一般用途 |
| u2net 人文主题 | ~176MB 坐标 | 320x320 (英语) | 人类主题 |
| u2net 布料 seg | ~176MB 坐标 | 320x320 (英语) | 服装分割 |
| 一般用途 | ~178MB 键 | 1024x1024 (英语) | 高精度一般用途 |
说明: 这个 isnet-general-use 模型使用更大的输入大小(1024x1024),可能为复杂的场景提供更好的精度,但需要更多的处理时间和内存.
配置
rembg-web包含一个中央配置系统,允许您自定义每个模型的模型路径. 这在您想要在自己的服务器上主机模型或者使用不同的模型版本时是有用的.
使用配置系统
import { rembgConfig } from '@bunnio/rembg-web';
// Set custom model path for u2net
rembgConfig.setCustomModelPath(
'u2net',
'https://my-server.com/models/u2net.onnx'
);
// Set custom model path for u2net_human_seg
rembgConfig.setCustomModelPath(
'u2net_human_seg',
'/custom/path/human_seg.onnx'
);
// Check if a model has a custom path
if (rembgConfig.hasCustomPath('u2net')) {
console.log('u2net has a custom path configured');
}
// Get the current path for a model
const u2netPath = rembgConfig.getCustomModelPath('u2net');
// Reset all paths to defaults
rembgConfig.resetToDefaults();
// Get all available models
const models = rembgConfig.getAvailableModels();
环境变量(备选)
您也可以在节点环境中使用环境变量设置模型路径:
export REMBG_U2NET_MODEL_PATH="/custom/path/u2net.onnx"
export REMBG_U2NETP_MODEL_PATH="/custom/path/u2netp.onnx"
export REMBG_U2NET_HUMAN_SEG_MODEL_PATH="/custom/path/human_seg.onnx"
浏览器环境
在浏览器环境中,您可以设置全局变量或使用元标记:
<!-- Using meta tags -->
<meta name="REMBG_U2NET_MODEL_PATH" content="/custom/path/u2net.onnx" />
<!-- Or set global variables -->
<script>
window.REMBG_U2NET_MODEL_PATH = '/custom/path/u2net.onnx';
</script>
高级配置
全局设置
这个 rembgConfig 单通为记录、缓存和硬件加速提供高级配置选项:
import { rembgConfig } from '@bunnio/rembg-web';
// Enable detailed logging
rembgConfig.enableGeneralLogging(true);
rembgConfig.enablePerformanceLogging(true);
// Configure cache behavior
rembgConfig.setSessionCacheBypass(false);
rembgConfig.setModelCacheBypass(false);
// Global WebNN/WebGPU settings
rembgConfig.enableWebNN(true);
rembgConfig.setWebNNDeviceType('gpu');
rembgConfig.enableWebGPU(true);
会话选项
精细控制的额外会话选项 :
const session = await newSession('u2net', undefined, {
// Cache control
bypassSessionCache: false, // Force new session creation
bypassModelCache: false, // Force model re-download
// Progress tracking during session initialization
onProgress: info => {
console.log(`Session: ${info.step} - ${info.progress}%`);
},
});
见 API 文档 用于完整的配置选项.
API 参考
remove(data, options?)
从图像中删除背景, 返回为 Blob .
参数:
data: 文件 QQ Blob QQ 组合缓冲器 HTML ImageElement QHTML CanvasElementoptions: 删除选项(可选)
回返情况: 答应
removeToCanvas(data, options?)
从图像中删除背景, 返回为 HTML CanvasElement .
参数:
data: 文件 QQ Blob QQ 组合缓冲器 HTML ImageElement QHTML CanvasElementoptions: 删除选项(可选)
回返情况: 答应
newSession(modelName, config?)
创建新模式会话 .
参数:
modelName: 字符串( 默认为 “ u2net ”)config: U2NetCustom Config(需要为u2net custom) 互联网档案馆的存檔,存档日期2013-12-20
回返情况: 基期会议
删除选项
interface RemoveOptions {
session?: BaseSession; // Custom session to use
onlyMask?: boolean; // Return only mask (black/white)
postProcessMask?: boolean; // Apply post-processing smoothing
bgcolor?: [number, number, number, number]; // RGBA background color
onProgress?: (info: ProgressInfo) => void; // Progress callback
}
interface ProgressInfo {
step: 'downloading' | 'processing' | 'postprocessing' | 'complete';
progress: number; // 0-100
message: string; // Human-readable status message
}
模型管理
import {
getAvailableModels,
clearModelCache,
clearModelCacheForModel,
disposeAllSessions,
} from '@bunnio/rembg-web';
// Get available models
const models = getAvailableModels();
console.log(models); // ['u2net', 'u2netp', 'u2net_human_seg', 'u2net_cloth_seg', 'isnet-general-use', 'isnet-anime', 'silueta', 'u2net_custom']
// Clear all cached models from IndexedDB
await clearModelCache();
// Clear cache for a specific model
await clearModelCacheForModel('u2net');
// Dispose all sessions
await disposeAllSessions();
自定义模型
import { newSession } from '@bunnio/rembg-web';
// Use a custom ONNX model
const customSession = newSession('u2net_custom', {
modelPath: '/path/to/your/model.onnx',
});
const result = await remove(imageFile, { session: customSession });
套装大小
图书馆的大小和性能都得到了优化:
- 主捆绑:~8KB gziped (不包括 ONNX 运行时间)
- 总规模:~65KB 未压缩
- ONNX 运行时间:~1.5MB (由浏览器单独装入)
库使用树摇动来保证您使用的代码只包含在您的捆绑中 .
浏览器支持
- Chrome/Edge 88+ (WebNN支持于119+,WebGPU支持于113+)
- Firefox 78+ (后旗WebGPU) (中文(简体) )
- Safari 14+ (技术预览中的WebGPU)
需要网络大会和网络工人的支持.
硬件加速
WebNN 支持
提供WebNN支助(附带说明,见上文,简称:无差别)
WebGPU 支持系统
WebGPU 支持是可用的(附带警告,见上文,简称:不与模型合作,执行时会失败)
执行提供者优先级
当同时启用了WebNN和WebGPU时,系统使用以下优先排序:
- 网络NN (如有)
- 网络GPU (如有)
- 网络GL (倒计时)
- CPU 软件 (最终倒计时)
发展
# Install dependencies
yarn install
# Build the library
yarn build
# Run tests
yarn test
# Start directly linked demos
yarn test:demo
# Analyze bundle size
yarn size
# Check bundle size limits
yarn analyze
# Start Docs devserver
yarn docs:dev
实例
这个 /examples 目录中包含显示不同特性的几个 HTML 示例 :
- 基本用途: 简单的背景去除
- 仅遮盖: 生成口罩而不是经过处理的图像
- 自定义背景: 用自定义颜色替换背景
- 会话重用: 多个图像的性能优化
- 进展跟踪: 实时进度更新
- WebNN 加速: 用 WebNN 进行硬件加速处理
- WebGPU 加速: 使用 WebGPU 的高性能 GPU 加速
运行示例
-
启动开发服务器 :
yarn docs:dev -
在浏览器中打开 :
- 导航到
http://localhost:3000 - 点击任意示例 HTML 文件
- 导航到
重要内容: 实例必须通过HTTP服务器提供(不是直接打开)来避免CORS出错.
许可证
麻省理工学院执照 - 看 自由主义 详细文件.
高级特性
模式完整性核查
验证模型完整性并验证下载 :
import { verifyModelIntegrity, validateModel } from '@bunnio/rembg-web';
// Verify model integrity
const isValid = await verifyModelIntegrity('u2net.onnx', modelData);
const validated = await validateModel('u2net.onnx', modelData);
服装分区选项
服装分型专用选项:
import { U2NetClothSegSession } from '@bunnio/rembg-web';
const session = new U2NetClothSegSession();
session.setClothCategory('upper'); // 'upper' | 'lower' | 'full' | 'all'
硬件检测
检查WebNN和WebGPU的可用性 :
import {
isWebNNAvailable,
isWebGPUAvailable,
getWebNNInfo,
} from '@bunnio/rembg-web';
const webnnAvailable = isWebNNAvailable();
const webgpuAvailable = isWebGPUAvailable();
const webnnInfo = await getWebNNInfo();
直接会话使用
直接使用会话类进行高级控制 :
import { U2NetSession, IsNetGeneralUseSession } from '@bunnio/rembg-web';
const session = new U2NetSession({ preferWebNN: true });
await session.initialize();
const masks = await session.predict(imageCanvas);
见 API 文档 用于完整的公用事业功能和高级使用.
解决问题
共同问题
CORS 错误
- 确定您正在从 HTTP 服务器服务您的应用程序,而不是直接打开 HTML 文件
- 使用
yarn examples或者像本地服务器python3 -m http.server 8080
未找到模型
- 运行
yarn fetch-models下载所需的 ONNX 模型文件 - 确保模式在
public/models/目录 - 检查浏览器控制台中的特定错误信息
Web 大会出错
- 校验您的浏览器支持 Web Assembly
- 请检查WASM 文件是否可访问
- 尝试刷新页面并清除浏览器缓存
记忆问题
- 使用更小的图像进行更快的处理
- 试试看
u2netp降低内存使用率的模型 - 关闭其他浏览器标签以释放内存
- 对多个图像使用会话再利用
业绩问题
- 使用
u2netp快速处理的模型 - 处理前调整大图像大小
- 如果可用, 启用硬件加速( WebNN/ WebGPU)
- 用会话再利用进行批次处理
获取帮助
捐款
我们欢迎捐款! 请看我们的 贡献指南 详细情况.
承认
这个项目的灵感来自 丹尼尔加蒂斯/伦布克 并使用相同的AI模型来取得一致的结果. 由现代网络技术所建,为浏览器-第一世界所设计.