如何使用Boost.Python将NumPy ndarray转换为C++向量并返回?

Kri*_*ian 8 c++ python boost numpy vector

我正在开发一个项目,我需要将ndarrayPython 转换为vectorC++,然后将处理vector后的C++返回给Python ndarray.我正在使用Boost.Python及其NumPy扩展.我的问题特别在于转换ndarrayvector,因为我正在使用扩展类向量:

class Vector
{
   public:
      Vector();
      Vector(double x, double y, double z);
      /* ... */
      double GetLength(); // Return this objects length.
      /* ... */
      double x, y, z;
};
Run Code Online (Sandbox Code Playgroud)

ndarray我收到的是nX 2和充满X,Y数据.然后我用一个函数处理C++中的数据,该函数返回一个std::vector<Vector>.然后这个向量应该作为一个返回给Python ndarray,但只有x和y值.

我编写了下面这段代码,灵感来自" 如何从boost :: python返回numpy.array? "和Boost NumPy示例中的gaussian.cpp.

#include <vector>
#include "Vector.h"
#include "ClothoidSpline.h"

#include <boost/python/numpy.hpp>

namespace py = boost::python;
namespace np = boost::python::numpy;

std::vector<Vector> getFineSamples(std::vector<Vector> data)
{
    /* ... */
}

np::ndarray wrapper(np::ndarray const & input)
{
    std::vector<Vector> data;

    /* Python ndarray --> C++ Vector */
    Py_intptr_t const* size = input.get_shape();
    Py_intptr_t const* strides = input.get_strides();

    double x;
    double y;
    double z = 0.0;

    for (int i = 0; i < size[0]; i++)
    {
        x = *reinterpret_cast<double const *>(input.get_data() + i * strides[0] + 0 * strides[1]);
        y = *reinterpret_cast<double const *>(input.get_data() + i * strides[0] + 1 * strides[1]);
        data.push_back(Vector::Vector(x,y,z));
    }

    /* Run Algorithm */
    std::vector<Vector> v = getFineSamples(data);

    /* C++ Vector --> Python ndarray */
    Py_intptr_t shape[1] = { v.size() };
    np::ndarray result = np::zeros(2, shape, np::dtype::get_builtin<std::vector<Vector>>());
    std::copy(v.begin(), v.end(), reinterpret_cast<double*>(result.get_data()));

    return result;
}
Run Code Online (Sandbox Code Playgroud)

编辑:我知道这是一个(可能)失败的尝试,我更感兴趣的是一个更好的方法来解决这个问题,而不是编辑我的代码.

总结一下:

  1. 如何将其转换boost::python::numpy::ndarraystd::vector<Vector>
  2. 如何转换std::vector<Vector>boost::python::numpy::ndarray,只返回x和y?

作为最后一点:我对Python几乎一无所知,而且我在C++中是初学/中等.

yel*_*w01 5

我会考虑你的问题的标题,为找到这篇文章的人提供一个更笼统的答案。

您有一个包含的boost::python::numpy::ndarray调用inputdoubles并且您想将其转换为std::vector<double>调用v

int input_size = input.shape(0);
double* input_ptr = reinterpret_cast<double*>(input.get_data());
std::vector<double> v(input_size);
for (int i = 0; i < input_size; ++i)
    v[i] = *(input_ptr + i);
Run Code Online (Sandbox Code Playgroud)

现在,您有一个std::vector<double>callv并且您想将其转换回boost::python::numpy::ndarrayof doublescalled output

int v_size = v.size();
py::tuple shape = py::make_tuple(v_size);
py::tuple stride = py::make_tuple(sizeof(double));
np::dtype dt = np::dtype::get_builtin<double>();
np::ndarray output = np::from_data(&v[0], dt, shape, stride, py::object());
Run Code Online (Sandbox Code Playgroud)

假设你正在包装这个函数,不要忘记你需要在将它返回给 python 之前创建一个对这个数组的新引用:

np::ndarray output_array = output.copy();
Run Code Online (Sandbox Code Playgroud)