npz文件作为pybind11中的输入

2024-10-03 19:32:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用pybind11包装一个npz文件。我在Python中有以下参数,其中函数路径查找是在C++中:

import testpy_path
sourcefile1 = np.load('data1.npy')
sourcefile2 = np.load('data2.npz') 
testpy_path.pathlookup(sourcefile1, sourcefile2) //error at sourcefile2 

在C++中使用PybDun11,我尝试生成NUMPY输入源SURCEFIL1和SURCEFILE2这样的:

void pathlookup(py::array_t<double, py::array::c_style | py::array::forecast> sourcefile1, py::array_t<double, py::array::c_style | py::array::forecast> sourcefile2){
    std::vector<double> sources1(sourcefile1.size()); 
    std::memcpy(sources1.data(), sourcefile1.data(), sourcefile1.size() * sizeof(double)); 
}

它适用于sourcefile1.npy文件,但不适用于numpy.npz文件。我的问题是,函数路径查找C++需要使用NPZ文件的参数,我如何将NPZ文件存储到向量中?p>

多谢各位


Tags: 文件path函数py路径参数npload
1条回答
网友
1楼 · 发布于 2024-10-03 19:32:01

我对numpy不是很有经验,但这是我在手册中发现的:

当您将load()npz文件一起使用时,将创建numpy.lib.npyio.NpzFile实例,而不是array实例。以下是手册中关于NpzFile的重要部分:

A dictionary-like object with lazy-loading of files in the zipped archive provided on construction.

NpzFile is used to load files in the NumPy .npz data archive format. It assumes that files in the archive have a .npy extension, other files are ignored.

The arrays and file strings are lazily loaded on either getitem access using obj['key'] or attribute lookup using obj.f.key. A list of all files (without .npy extensions) can be obtained with obj.files and the ZipFile object itself using obj.zip.

这意味着您可以通过以下方式访问阵列:

np.savez("out.npz", x=data)
x = np.load("out.npz")['x']

然后可以将x传递给函数

https://www.kite.com/python/docs/numpy.lib.npyio.NpzFile

编辑:

如果希望通过pybind直接加载numpy数组,可以执行以下操作:

auto np = py::module::import("numpy");
py::dict d = np.attr("load")("out.npz");
for(auto k : d)
{
    std::cout << k.first.cast<std::string>() << std::endl;
    std::cout << k.second.cast<py::array>().size() << std::endl;
}

或者将npz文件句柄作为dict传递

相关问题 更多 >