最近在做C++调用Pytorch模型进行识别的任务,C++关于Pytorch的教程很少,基本上都是用Python写的,但因为要识别任务是实时的,Python的执行效率不如C++,所以主题代码还是没用Python。
网上利用C++调用Pytorch模型的方法主要是把模型文件转化成C++可以加载和执行的模型文件,利用的是Torch Script,但这个方法我目前还没有看懂…(先放上一个链接,后续再看:https://blog.youkuaiyun.com/tlzhatao/article/details/86555269)
现在我使用的方法是在C++文件里调用Python,Python文件主要执行的是调用模型、接受图片进行检测并返回坐标结果的功能,C++需要向Python传入模型所在位置(因为需要根据不同的任务选择不同的模型)以及图片(视频流),并接受返回的坐标
原始的C++代码里有涉及到摄像头的打开,图片的实时获取等功能,所以先写了一个简单的代码来实现C++调用Python的功能,代码如下:
#include <iostream>
#include <Python.h>
#include <vector>
#include "opencv2/opencv.hpp"
#include <numpy/arrayobject.h>
using namespace std;
int transport(PyObject *pDict)
{
import_array();
cv::Mat img = cv::imread("2.jpg", CV_LOAD_IMAGE_COLOR);
cout<<"读取完毕"<<endl;
int m, n;
n = img.cols*3;
m = img.rows;
unsigned char *data = (unsigned char*)malloc(sizeof(unsigned char) * m * n);
int p = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
data[p] = img.at<unsigned char>(i, j);
p++;
}
}
npy_intp Dims[2] = {
m, n }; //给定维度信息
PyObject*PyArray = PyArray_SimpleNewFromData(2, Dims, NPY_UBYTE, data);
PyObject *ArgArray = PyTuple_New(2);
PyObject *arg = PyLong_FromLong(30);
PyTuple_SetItem(ArgArray, 0, PyArray);
PyTuple_SetItem(ArgArray, 1, arg);
PyObject*pFuncFive = PyDict_GetItemString<