【发布时间】:2017-05-03 11:26:01
【问题描述】:
我正在做一个项目,我需要将 Python 中的 ndarray 转换为 C++ 中的 vector,然后将处理后的 vector 从 C++ 返回到 ndarray 中的 Python。我正在使用 Boost.Python 及其 NumPy 扩展。我的问题特别在于从ndarray 转换为vector,因为我使用的是向量的扩展类:
class Vector
{
public:
Vector();
Vector(double x, double y, double z);
/* ... */
double GetLength(); // Return this objects length.
/* ... */
double x, y, z;
};
我收到的 ndarray 是 nx2 并填充了 x,y 数据。然后我用一个函数在 C++ 中处理数据,该函数返回一个std::vector<Vector>。然后,该向量应作为 ndarray 返回给 Python,但仅包含 x 和 y 值。
我编写了以下代码,灵感来自“how to return numpy.array from boost::python?”和 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;
}
编辑:我知道这是一次(可能)失败的尝试,我对解决这个问题的更好方法更感兴趣,而不是编辑我的代码。
总结一下:
- 如何将
boost::python::numpy::ndarray转换为std::vector<Vector>? - 如何将
std::vector<Vector>转换为boost::python::numpy::ndarray,只返回 x 和 y?
最后一点:我对 Python 几乎一无所知,而且我是 C++ 的初学者/中等水平。
【问题讨论】:
标签: python c++ numpy vector boost