C++传输图片到python

开发环境:VS2015,python3.6
release版本编译,debug版本 import_array()会有错误,PyArray_SimpleNewFromData()必须引入import_array(),我的头文件#include <numpy/arrayobject.h>,在 F:\Anaconda\envs\python36\Lib\site-packages\numpy\core\include\numpy下,然后添加相应的lib就可以了。

C++测试代码

#include <iostream>
#include <Python.h>
#include <windows.h>
#include "opencv2/opencv.hpp"
#include <numpy/arrayobject.h>

using namespace std;

int transport()
{
	Py_SetPythonHome(L"F:/Anaconda/envs/python36");
	Py_Initialize();
	import_array();

	PyObject* sys = PyImport_ImportModule("sys");

	PyRun_SimpleString("import sys"); // 执行 python 中的短语句  
	PyRun_SimpleString("sys.path.append('./')");

	PyObject *pModule(0);
	pModule = PyImport_ImportModule("test1");//myModel:Python文件名  

	cv::Mat img = cv::imread("2.jpg", CV_LOAD_IMAGE_COLOR);
	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 *pDict = PyModule_GetDict(pModule);
	PyObject*ArgArray = PyTuple_New(1);
	PyTuple_SetItem(ArgArray, 0, PyArray);
	PyObject*pFuncFive = PyDict_GetItemString(pDict, "load_image");
	PyObject_CallObject(pFuncFive, ArgArray);
}



int main()
{
	transport();
	system("pause");
	return 0;
}

python测试代码

import numpy as np
import cv2

def arrayreset(array):
    a = array[:, 0:len(array[0] - 2):3]
    #b = array[:, 1:len(array[0] - 2):3]
    #c = array[:, 2:len(array[0] - 2):3]
    #print(a.shape, b.shape, c.shape)
    #a = a[:, :, None]
    #b = b[:, :, None]
    #c = c[:, :, None]
    #m = np.concatenate((a, b, c), axis=2)

    return a

def load_image(image):
    img = arrayreset(image)
    rgbImg=cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
    print(rgbImg.shape)
    cv2.imshow("test",rgbImg)
    cv2.waitKey(0)

后续更新,c++调用tensorflow模型,c++获取图像直接传入python。

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值