如何在C++中载入numpy ndarray

需求

有个tensor保存在numpy数组中,想用C++读取。

操作

首先使用np.save()将数组保存为npy文件,注意dtype需要指定。
读写npy主要用到这个库 https://github.com/llohse/libnpy
调用只需包含一个hpp文件
可获取array对应size并将数据flat到vector保存

代码

save in python

import numpy as np

#create your tensor var
np.save("/dev/shm/fpp.npy",np.float32(tensor))

load in c++

#include <vector>
#include <string>
#include "npy.hpp"

std::string npy_file = "/dev/shm/foo.npy";
std::vector<unsigned long> shape;
std::vector<float> data; // 必须指定<dtype>类型与npy对应
shape.clear();
data.clear();
bool is_fortran;
// load ndarray voxel as vector<float>
npy::LoadArrayFromNumpy(npy_file, shape, is_fortran, data);
原文地址:https://www.cnblogs.com/azureology/p/14784509.html