C++调用python训练的pytorch模型(四)-----C++向python传输图片

C++向python传输图片

参考:c++向python传输图片 高效方法 mat转numpy

参考:c++ 调用python传输图片

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"
    
  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值