首页 > 解决方案 > 如何使用 pybind11 在 C++ 中使用 numpy 数组?

问题描述

即使在阅读了有关 numpy 的 Pybind11文档之后,我仍然不确定如何在 C++ 中使用 numpy 数组,例如,如果它是一维的,则将其转换为向量,或者如果它是二维的,则将其转换为向量的向量。

这是我的代码片段。我将如何实施make_vector_from_1d_numpy_array()

#include <pybind11/embed.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
using namespace pybind11::literals; 

py::scoped_interpreter guard {};
py::module np = py::module::import("numpy");
py::module librosa = py::module::import("librosa");

auto filters_py = librosa.attr("filters").attr("mel")(16000, 1024, "n_mels"_a = 80, "fmin"_a = 0, "fmax"_a = 8000, "htk"_a = true);
auto shape_py = filters_py.attr("shape");

// above code runs fine. At this point, shape_py is "numpy.ndarray"
// auto shape = make_vector_from_1d_numpy_array<size_t>(shape_py)

标签: c++numpypybind11

解决方案


这行得通。

template<class T>
std::vector<T>make_vector_from_1d_numpy_array( py::array_t<T>py_array )
{
    return std::vector<T>(py_array.data(), py_array.data() + py_array.size());
}

推荐阅读