将ncnn及opencv的mat存储成bin文件的方法

利用fstream,将ncnn及opencv的mat存储成bin文件。

ncnn::Mat to bin

std::ios::binary标志指示文件以二进制模式进行读写,

cpp 复制代码
std::ofstream file("output_x86.bin", std::ios::binary);

将input_mat中的宽、高和通道数分别赋值给width、height和channels,

cpp 复制代码
int width = input_mat.w;
int height = input_mat.h;
int channels = input_mat.c;

使用file.write函数将width、height和channels的值以二进制形式写入文件。reinterpret_cast用于将指针类型进行类型转换,这里将 int* 类型转换为 const char* 类型,以便将其作为字节流写入文件,

cpp 复制代码
file.write(reinterpret_cast<const char*>(&width), sizeof(int));
file.write(reinterpret_cast<const char*>(&height), sizeof(int));
file.write(reinterpret_cast<const char*>(&channels), sizeof(int));

将input_mat.data所指向的数据以二进制形式写入文件。input_mat.data是一个指向input_mat数据的指针,reinterpret_cast将其转换为const char*类型,以便将其作为字节流写入文件。input_mat.cstep * sizeof(float)表示要写入的字节数,input_mat.cstep是input_mat数据中每一行的字节数,乘以 sizeof(float) 表示将所有数据写入文件,

cpp 复制代码
file.write(reinterpret_cast<const char*>(input_mat.data), input_mat.cstep * sizeof(float));
file.close();

cv::Mat to bin

cpp 复制代码
std::ofstream file(filename, std::ios::binary);

int width = mat.cols;
int height = mat.rows;
int channels = mat.channels();
    
file.write(reinterpret_cast<const char*>(&width), sizeof(int));
file.write(reinterpret_cast<const char*>(&height), sizeof(int));
file.write(reinterpret_cast<const char*>(&channels), sizeof(int));  
file.write(reinterpret_cast<const char*>(mat.data), mat.total() * mat.elemSize());
file.close();
相关推荐
IT猿手6 分钟前
超多目标优化:基于导航变量的多目标粒子群优化算法(NMOPSO)的无人机三维路径规划,MATLAB代码
人工智能·算法·机器学习·matlab·无人机
JolyouLu16 分钟前
PyTorch-基础(CUDA、Dataset、transforms、卷积神经网络、VGG16)
人工智能·pytorch·cnn
CS_木成河20 分钟前
【深度学习】预训练和微调概述
人工智能·深度学习·语言模型·微调·预训练
Alidme23 分钟前
cs106x-lecture14(Autumn 2017)-SPL实现
c++·学习·算法·codestepbystep·cs106x
小王努力学编程24 分钟前
【算法与数据结构】单调队列
数据结构·c++·学习·算法·leetcode
新加坡内哥谈技术28 分钟前
微软发布Majorana 1芯片,开启量子计算新路径
人工智能·深度学习·语言模型·自然语言处理
真智AI1 小时前
使用 DistilBERT 进行资源高效的自然语言处理
人工智能·自然语言处理
OpenBuild.xyz1 小时前
我是如何从 0 到 1 找到 Web3 工作的?
人工智能·web3·去中心化·区块链·智能合约
Sui_Network1 小时前
Sui 如何支持各种类型的 Web3 游戏
大数据·数据库·人工智能·游戏·web3·区块链
ZKNOW甄知科技1 小时前
IT服务运营管理体系的常用方法论与实践指南(上)
大数据·数据库·人工智能