将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();
相关推荐
宝杰X71 小时前
Compose Multiplatform+Kotlin Multiplatfrom 第七弹跨平台 AI开源
人工智能·开源·kotlin
Java樱木1 小时前
AI 编程 Trae ,有重大更新!用 Trae 做了个图书借阅网站!
人工智能·ai编程
悟乙己1 小时前
大型语言模型(LLM)文本中提取结构化信息:LangExtract(一)
人工智能·语言模型·自然语言处理
祁同伟.1 小时前
【C++】多态
开发语言·c++
rechol1 小时前
C++ 继承笔记
java·c++·笔记
Theodore_10221 小时前
机器学习(3)梯度下降
人工智能·机器学习
LiJieNiub2 小时前
YOLOv3:目标检测领域的经典革新
人工智能·计算机视觉·目标跟踪
yanxing.D2 小时前
OpenCV轻松入门_面向python(第六章 阈值处理)
人工智能·python·opencv·计算机视觉
SunkingYang2 小时前
详细介绍C++中捕获异常类型的方式有哪些,分别用于哪些情形,哪些异常捕获可用于通过OLE操作excel异常
c++·excel·mfc·异常捕获·comerror
霍格沃兹测试开发学社测试人社区3 小时前
新手指南:通过 Playwright MCP Server 为 AI Agent 实现浏览器自动化能力
运维·人工智能·自动化