c++ - 如何使用 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)
解决方案
这行得通。
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());
}
推荐阅读
- python - 将值和函数重新序列化到 Python 中的新环境中
- python - 在python中循环遍历数据框字典并将字典中的每个数据框与单个数据框合并
- docker - 发布容器端口时如何使用另一个容器的网络堆栈
- c# - C#计数计时器不会停止计数
- python - Netmiko OSError:在 send_command_expect:Destination 中从未检测到搜索模式
- ruby-on-rails - Rails Mailgun::CommunicationError 403 仅在生产中
- azure - 我如何知道 Azure VMSS 的特定实例上安装了哪个映像版本?
- r - 将具有特定名称的空列列表添加到 R 中的 df 列表
- python - 禁用特定扩展显示的 vscode 工具提示提示
- javascript - 导入 winston 导致“未定义进程”