![](/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.