gpt4 book ai didi

python - 如何使用 Boost.Python 将 NumPy ndarray 转换为 C++ vector 并返回?

转载 作者:太空狗 更新时间:2023-10-29 21:56:15 25 4
gpt4 key购买 nike

我正在做一个需要转换 ndarray 的项目在 Python 中为 vector在 C++ 中,然后返回处理过的 vectorndarray 中从 C++ 回到 Python .我正在使用 Boost.Python 及其 NumPy 扩展。我的问题具体在于从 ndarray 转换至 vector ,因为我正在使用扩展的 vector 类:

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

ndarray我收到的是n x 2并填充了 x,y 数据。然后我用一个函数在 C++ 中处理数据,该函数返回 std::vector<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;
}

编辑:我知道这是一次(可能)失败的尝试,与编辑我的代码相比,我对解决此问题的更好方法更感兴趣。

总结:

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

最后一点:我对 Python 几乎一无所知,而且我是 C++ 的初学者/中等水平。

最佳答案

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

你有一个 boost::python::numpy::ndarray称为 input包含 doubles并且您想将其转换为 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);

现在,你有一个 std::vector<double>称为 v并且您想将其转换回 boost::python::numpy::ndarraydoubles称为 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());

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

np::ndarray output_array = output.copy();

关于python - 如何使用 Boost.Python 将 NumPy ndarray 转换为 C++ vector 并返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43758709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com