如何在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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM