C++向python传输图片
参考:c++向python传输图片 高效方法 mat转numpy
c++代码实现
#include <Python.h>
#include <memory>
#include <iostream>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <numpy/arrayobject.h>
int main(){
// 读一张图片
cv::Mat img = cv::imread("183101.jpg",CV_LOAD_IMAGE_COLOR);
int m,n;
n = img.cols*3;
m = img.rows;
cout<< "cols:"<<img.cols<<" rows:"<<img.rows<<" c:"<<3<<endl;
unsigned char *image_data = new unsigned char[m*n];
int count=0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
image_data[count] = img.at<unsigned char>(i,j);
count++;
}
}
// 调用python api加载python文件
Py_SetPythonHome(L"/home/bob/anaconda2/envs/benchmark_py36");
Py_Initialize();
import_array(); //必须有。传数组时需要
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
g_pModule = PyImport_ImportModule("webcam_test");
if(g_pModule == nullptr)
{
cout<<"Error: python module is null!"<<endl;
return -1;
}
g_pFunc_forward = PyObject_GetAttrString(g_pModule,"forward");
if(g_pFunc_forward == nullptr)
{
cout<<"Error: python pFunc_forward is null!"<<endl;
return -1;
}
npy_intp Dims[3] = {img.rows,img.cols,3};
PyObject *pyarray = PyArray_SimpleNewFromData(3,Dims,NPY_UBYTE,(void*)image_data);
PyObject *argarray = PyTuple_New(1);
PyTuple_SetItem(argarray,0,pyarray);
PyObject *pRet = PyObject_CallObject(g_pFunc_forward,argarray);
if(pRet == nullptr)
{
cout<<"Error: python pFunc_forward pRet is null!"<<endl;
return -1;
}
}
python代码实现
# 接收图片数据,并进行转换。因为C++与python读取图片的矩阵不一致
def forward(image):
global g_model
a=image[:,:,0]
b=image[:,:,1]
c=image[:,:,2]
a = np.expand_dims(a,axis=2)
b = np.expand_dims(b,axis=2)
c = np.expand_dims(c,axis=2)
image = np.concatenate((a,b,c),axis=2)
return "ok"