需求:
将python处理好的数据转到同维度数组
失败方式:
1 .保存文本文件
import numpy as np
# result为一个二维数组
result = np.array([[1, 2, 3,5, 6, 3]])
# 写入文件
np.savetxt("result2", result)
# 读取文件
dataset = np.loadtxt('result2.npy')
2.保存二进制文件
import numpy as np
# result为一个二维数组
result = np.array([[1, 2, 3,5, 6, 3]])
# 写入文件
np.save("result2", result)
# 读取文件
dataset = np.load('result2')
转载内容
C++读取numpy数据二进制文件 作者:pan_jinquan
可行案例![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/765759ef3fa37005549727e2ab61f6de.png)
将numpy数组保存为二进制文件
def save_bin(data, bin_file, dtype="double"):
"""
C++int对应Python np.intc
C++float对应Python np.single
C++double对应Python np.double
:param data:
:param bin_file:
:param dtype:
:return:
"""
data = data.astype(np.double)
data.astype(dtype).tofile(bin_file)
用numpy读取二进制文件
def load_bin(bin_file, shape=None, dtype="double"):
"""
:param bin_file:
:param dtype:
:return:
"""
data = np.fromfile(bin_file, dtype=dtype)
if shape:
data = np.reshape(data, shape)
return data
if __name__ == "__main__":
bin_file = "data.bin"
shape = (2, 5)
data1 = np.arange(10, 20).reshape(shape)
save_bin(data1, bin_file)
data2 = load_bin(bin_file, shape)
print(data1)
print(data2)
用C++读取二进制文件
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int row=2;
int col=5;
double fnum[row][col] = {0};
ifstream in("bin/data.bin", ios::in | ios::binary);
in.read((char *) &fnum, sizeof fnum);
cout << in.gcount() << " bytes read\n";
// show values read from file
for(int i=0; i<row; i++){
for(int j=0;j<col;j++){
cout << fnum[i][j] << ",";
}
std::cout<<endl;
}
in.close();
return 0;
}