![](/img/trans.png)
[英]How to I transfer an image(opencv Matrix/numpy array) from c++ publisher to python sender via ZeroMQ?
[英]How do I access a numpy array in embedded python from c++?
在c ++中访问2dim numpy数组的好方法是什么? 我已经检查了numpy / c api和其他一些文章,但是并没有进一步介绍我。 情况如下:
我在一个名为Testfile.py的python文件中定义了以下numpy数组:
import numpy as np
A = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
现在,我想使用c ++访问此数组以将其用于进一步的计算。 这是我到目前为止所做的。 注意:为简单起见,我省略了错误处理和引用计数代码段。
#define NPY_NO_DEPRECATED_APINPY_1_7_API_VERSION
#define PY_ARRAY_UNIQUE_SYMBOL cool_ARRAY_API
#include <Python.h>
#include <arrayobject.h> // numpy!
#include <iostream>
using namespace std;
#include <stdlib.h>
#include <string>
int main(){
// Name of input-file
char pyfilename[] = "Testfile";
// initilaize python interpreter
Py_Initialize();
import_array();
// load input-file
PyObject *pyName = PyUnicode_FromString(pyfilename);
PyObject *pyModule = PyImport_Import(pyName);
// import my numpy array object
char pyarrayname[] = "A";
PyObject *obj = PyObject_GetAttrString(pyModule, pyarrayname);
//------------------------------------------------------------
// The Problem starts here..
// Array Dimensions
npy_intp Dims[] = { PyArray_NDIM(obj) }; // array dimension
Dims[0] = PyArray_DIM(obj, 0); // number of rows
Dims[1] = PyArray_DIM(obj, 1); // number of columns
// PyArray_SimpleNew allocates the memory needed for the array.
PyObject *ArgsArray = PyArray_SimpleNew(2, Dims, NPY_DOUBLE);
// The pointer to the array data is accessed using PyArray_DATA()
double *p = (double *)PyArray_DATA(ArgsArray);
for (int i = 0; i<Dims[0]; i++)
{
for (int j = 0; j<Dims[1]; j++)
{
p[i * Dims[1] + j] = *((int *)PyArray_GETPTR2(obj, i, j));
}
}
// -----------------------------------------------------------
Py_Finalize();
return 0;
}
我使用python 3.6和MSVC 2015。
编辑:我添加了我使用的标头,并稍微改变了问题的表述。
编辑:我添加了由Swift和Alan Stokes提供的建议的解决方案策略
在通过访问数组之后
double *p = (double*)PyArray_DATA(ArgsArray);
int* pA = (int*)PyArray_DATA(obj);
您可以像处理数组一样使用它。 什么是尺寸?
int height = PyArray_DIM(obj, 0);
int width = PyArray_DIM(obj, 1);
现在您可以使用该指针访问数组中的数据
for ( int i = 0; y<height; y++)
{
for (int j = 0; x<width; x++)
{
p[i * width + j] = pA[i * width + j];
}
}
实际上,如果只需要复制数组,请在此时使用memcpy或std :: copy。
Tbh,我曾考虑改为使用boost.python,但这是我自己的偏好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.