我用Cython封装了一个来自segment-anything-master项目里的.pth模型,我的.pyx文件是这么写的import sys import numpy as np import matplotlib import matplotlib.pyplot as plt import cv2 from typing import Any, Dict, List, Optional, Tuple sys.path.append("/app/PythonProjects/segment-anything-main") from segment_anything import sam_model_registry, SamAutomaticMaskGenerator, SamPredictor # model.pyxcdef class SamModel: def __init__(self, str model_type,str sam_checkpoint, str device = "cpu", points_per_side: Optional[int] = 32, points_per_batch: int = 64, point_grids: Optional[List[np.ndarray]] = None): self.sam = sam_model_registry[model_type](checkpoint=sam_checkpoint) self.sam.to(device) self.mask_generator = SamAutomaticMaskGenerator(self.sam,points_per_side = points_per_side, points_per_batch = points_per_batch, point_grids = point_grids) def __getmodel__(self): return self.sam def __callmodel__( self, input: np.array ): masks = self.mask_generator.generate(input) return masks,我的setup.py文件是这样写的:from distutils.core import setup from distutils.extension import Extension import Cython from Cython.Build import cythonize import numpy extensions = [ Extension('models.model', ['/app/PythonProjects/segment-anything-main/SamCython/models/model.pyx'], include_dirs=[numpy.get_include()]), ] setup( name='models', ext_modules=cythonize(extensions), ),给我一篇C++调动这个模型的实例
时间: 2023-12-27 16:02:24 浏览: 213
好的,以下是一个简单的C++调用这个模型的示例代码:
```cpp
#include <Python.h>
#include <numpy/arrayobject.h>
#include <iostream>
int main()
{
// 初始化 Python 解释器
Py_Initialize();
// 加载 NumPy 模块
import_array();
// 加载 Python 模块和函数
PyObject* pModule = PyImport_ImportModule("models.model");
if (!pModule) {
std::cerr << "Failed to import module" << std::endl;
return 1;
}
PyObject* pFunc = PyObject_GetAttrString(pModule, "__callmodel__");
if (!pFunc || !PyCallable_Check(pFunc)) {
std::cerr << "Failed to get function" << std::endl;
return 1;
}
// 准备输入数据
int width = 640;
int height = 480;
npy_intp dims[3] = { height, width, 3 };
unsigned char* inputData = new unsigned char[width * height * 3];
// 填充 inputData 数据
// 创建 NumPy 数组
PyObject* pInputArray = PyArray_SimpleNewFromData(
3, dims, NPY_UINT8, inputData);
// 调用函数
PyObject* pOutputArray = PyObject_CallFunction(pFunc, "O", pInputArray);
if (!pOutputArray) {
std::cerr << "Failed to call function" << std::endl;
return 1;
}
// 获取输出数据
unsigned char* outputData = PyArray_DATA((PyArrayObject*)pOutputArray);
// 处理 outputData 数据
// 释放资源
Py_DECREF(pInputArray);
Py_DECREF(pOutputArray);
Py_DECREF(pFunc);
Py_DECREF(pModule);
Py_Finalize();
delete[] inputData;
return 0;
}
```
需要注意的是,在编译时,需要链接 Python 和 NumPy 库。可以使用以下命令进行编译:
```
g++ -o main main.cpp -I/usr/include/python3.8 -lpython3.8 -lpython3 -lm -ldl -I/usr/local/lib/python3.8/dist-packages/numpy/core/include -L/usr/local/lib/python3.8/config-3.8-x86_64-linux-gnu -lpython3.8 -lcrypt -lpthread -ldl -lutil -lm -Wno-unused-result
```
其中,`-I` 参数指定 Python 和 NumPy 的头文件路径,`-l` 参数指定 Python 的库文件和 NumPy 的库文件(需要根据自己的 Python 版本和安装路径进行调整)。
阅读全文