将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 分钟前
11. isaacsim4.2教程-Transform 树与Odometry
人工智能·机器人·自动驾驶·ros·rviz·isaac sim·仿真环境
静心问道1 小时前
InstructBLIP:通过指令微调迈向通用视觉-语言模型
人工智能·多模态·ai技术应用
宇称不守恒4.01 小时前
2025暑期—06神经网络-常见网络2
网络·人工智能·神经网络
小楓12012 小时前
醫護行業在未來會被AI淘汰嗎?
人工智能·醫療·護理·職業
数据与人工智能律师2 小时前
数字迷雾中的安全锚点:解码匿名化与假名化的法律边界与商业价值
大数据·网络·人工智能·云计算·区块链
chenchihwen2 小时前
大模型应用班-第2课 DeepSeek使用与提示词工程课程重点 学习ollama 安装 用deepseek-r1:1.5b 分析PDF 内容
人工智能·学习
说私域2 小时前
公域流量向私域流量转化策略研究——基于开源AI智能客服、AI智能名片与S2B2C商城小程序的融合应用
人工智能·小程序
Java樱木2 小时前
AI 编程工具 Trae 重要的升级。。。
人工智能
AntBlack2 小时前
从小不学好 ,影刀 + ddddocr 实现图片验证码认证自动化
后端·python·计算机视觉
凪卄12133 小时前
图像预处理 二
人工智能·python·深度学习·计算机视觉·pycharm