问题描述
即使在numpy上阅读了Pybind11 documentation之后,我仍然不确定如何在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)
解决方法
这有效。
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());
}