将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();
相关推荐
独立开发者阿乐5 小时前
什么是 GEO:让 AI 搜索引擎引用你内容的完整指南
人工智能·搜索引擎·ai搜索引擎·geo优化·ai爬虫·llms.txt·clarabbs
方知我5 小时前
AI应用-智能伴侣
人工智能·ai
开开心心就好6 小时前
视频压缩工具推荐,绿色版免安装双击即用
java·前端·人工智能·spring·智能手机·intellij-idea·excel
RockHopper20256 小时前
AI时代模型生命周期与软件资产重构:概要版
人工智能·系统架构·软件工程·ai编程·世界模型
zhuo木鸟6 小时前
我用 opencode + Qdrant 搭了五段式小说写作系统
人工智能·个人开发·ai写作·ai写小说
大模型任我行6 小时前
字节:交替蒸馏与强化学习
人工智能·语言模型·自然语言处理·论文笔记
空堂与归6 小时前
AI 与 SI(超级智能):先分清窄智能与超级智能的边界
开发语言·人工智能·gpt
奈落246 小时前
DeepSeek Harness 开源贡献手记:从 Issue 认领到 PR 合入的完整实践
大数据·人工智能·安全·搜索引擎·开源
朝朝辞暮i6 小时前
VLA 系统学习第 2 课:Behavior Cloning——机器人究竟怎么从示范中学动作?
人工智能·python·vla
johnsong6 小时前
AI前沿日报 2026-10-06:推理效率革命
人工智能