将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();
相关推荐
普if加的帕1 小时前
java Springboot使用扣子Coze实现实时音频对话智能客服
java·开发语言·人工智能·spring boot·实时音视频·智能客服
KoiC1 小时前
Dify接入RAGFlow无返回结果
人工智能·ai应用
lilye661 小时前
精益数据分析(20/126):解析经典数据分析框架,助力创业增长
大数据·人工智能·数据分析
2301_807611491 小时前
77. 组合
c++·算法·leetcode·深度优先·回溯
盈达科技2 小时前
盈达科技:登顶GEO优化全球制高点,以AICC定义AI时代内容智能优化新标杆
大数据·人工智能
安冬的码畜日常2 小时前
【AI 加持下的 Python 编程实战 2_10】DIY 拓展:从扫雷小游戏开发再探问题分解与 AI 代码调试能力(中)
开发语言·前端·人工智能·ai·扫雷游戏·ai辅助编程·辅助编程
古希腊掌管学习的神2 小时前
[LangGraph教程]LangGraph04——支持人机协作的聊天机器人
人工智能·语言模型·chatgpt·机器人·agent
FIT2CLOUD飞致云2 小时前
问答页面支持拖拽和复制粘贴文件,MaxKB企业级AI助手v1.10.6 LTS版本发布
人工智能·开源
起个破名想半天了2 小时前
计算机视觉cv入门之答题卡自动批阅
人工智能·opencv·计算机视觉
早睡早起吧2 小时前
目标检测篇---Fast R-CNN
人工智能·目标检测·计算机视觉·cnn