需求
有個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);