代码地址:https://github.com/dinglufe/segment-anything-cpp-wrapper

为 Segment Anything 和 MobileSAM 创立了一个纯C++推理API,运行时不依赖Python。

视频演示

示例程序用法:

在发布页面下载压缩文件,解压缩后间接运行sam_cpp_test或在命令行中运行:

# 显示帮忙./sam_cpp_test -h# 示例(更改设施,预处理应用CPU,SAM应用CUDA)# 如果有多个GPU,能够应用CUDA:1、CUDA:2等等。# 也反对全副在CPU或全副在CUDA运行./sam_cpp_test -pre_device="cpu" -sam_device="cuda:0"# 示例(默认选项)./sam_cpp_test -pre_model="models/sam_preprocess.onnx" -sam_model="models/sam_vit_h_4b8939.onnx" -image="images/input.jpg"# 示例(应用MobileSAM)./sam_cpp_test -pre_model="models/mobile_sam_preprocess.onnx" -sam_model="models/mobile_sam.onnx"# 示例(更改图片)./sam_cpp_test -image="images/input2.jpg"

C++库 - sam_cpp_lib

简略示例:

Sam::Parameter param("sam_preprocess.onnx", "sam_vit_h_4b8939.onnx", std::thread::hardware_concurrency());param.providers[0].deviceType = 0; // 预处理应用CPUparam.providers[1].deviceType = 1; // SAM应用CUDASam sam(param);// 应用MobileSAMSam::Parameter param("mobile_sam_preprocess.onnx", "mobile_sam.onnx", std::thread::hardware_concurrency());auto inputSize = sam.getInputSize();cv::Mat image = cv::imread("input.jpg", -1);cv::resize(image, image, inputSize);sam.loadImage(image); // 如果应用CPU,将须要6GB内存,如果应用CUDA,将须要16GB内存// 应用带有提醒的SAM(输出:x、y坐标)cv::Mat mask = sam.getMask({200, 300});cv::imwrite("output.png", mask);// 应用带有多个提醒的SAM(输出:points、negativePoints)cv::Mat mask = sam.getMask(points, negativePoints); // 如果应用CPU,将须要1GB内存/显存cv::imwrite("output-multi.png", mask);// 应用带有框提醒的SAM(输出:points、negativePoints、box)// points和negativePoints能够为空(应用{}作为参数)cv::Rect box{444, 296, 171, 397};cv::Mat mask = sam.getMask(points, negativePoints, box);cv::imwrite("output-box.png", mask);// 主动生成掩码(输出:每边的点数)// 因为在CPU上运行,速度较慢,而且后果不如官网演示好cv::Mat maskAuto = sam.autoSegment({10, 10});cv::imwrite("output-auto.png", maskAuto);