np数组转化成 c++可读取的数组操作

需求:

将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

可行案例在这里插入图片描述

将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;
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值