当前位置: 首页 > news >正文

opencv--把cv::Mat数据转为二进制数据的保存和读取

保存

#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>void saveMatToBinary(const cv::Mat& mat, const std::string& filename) {std::ofstream ofs(filename, std::ios::binary);if (!ofs.is_open()) {std::cerr << "Failed to open file for writing: " << filename << std::endl;return;}// Write the matrix type and sizeint type = mat.type();int rows = mat.rows;int cols = mat.cols;ofs.write((char*)&type, sizeof(type));ofs.write((char*)&rows, sizeof(rows));ofs.write((char*)&cols, sizeof(cols));// Write the matrix dataofs.write((char*)mat.data, mat.total() * mat.elemSize());ofs.close();
}int main() {cv::Mat image = cv::imread("path_to_your_image.jpg");if (image.empty()) {std::cerr << "Failed to load image" << std::endl;return -1;}saveMatToBinary(image, "output.bin");return 0;
}

读取

#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>cv::Mat loadMatFromBinary(const std::string& filename) {std::ifstream ifs(filename, std::ios::binary);if (!ifs.is_open()) {std::cerr << "Failed to open file for reading: " << filename << std::endl;return cv::Mat();}// Read the matrix type and sizeint type, rows, cols;ifs.read((char*)&type, sizeof(type));ifs.read((char*)&rows, sizeof(rows));ifs.read((char*)&cols, sizeof(cols));// Create the matrixcv::Mat mat(rows, cols, type);// Read the matrix dataifs.read((char*)mat.data, mat.total() * mat.elemSize());ifs.close();return mat;
}int main() {cv::Mat loadedImage = loadMatFromBinary("output.bin");if (loadedImage.empty()) {std::cerr << "Failed to load image from binary file" << std::endl;return -1;}cv::imshow("Loaded Image", loadedImage);cv::waitKey(0);return 0;
}

http://www.lryc.cn/news/395785.html

相关文章:

  • 【微信小程序开发实战项目】——个人中心页面的制作
  • 基于MCU平台的HMI开发的性能优化与实战(下)
  • 评估测试用例有效性 5个方面
  • CentOS 7.9 快速更换 阿里云源教程
  • Python 编程快速上手——让繁琐工作自动化(第2版)读书笔记01 Python基础快速过关
  • 实战 | YOLOv8使用TensorRT加速推理教程(步骤 + 代码)
  • 绝区陆--大语言模型的幻觉问题是如何推动科学创新
  • 集训 Day 2 模拟赛总结
  • Linux系统(CentOS)安装Mysql5.7.x
  • YModem在Android上的实现
  • 循环练习题
  • Seata解决分布式事务
  • C语言编译报错error: expected specifier-qualifier-list before
  • 无缝协作:如何实现VMware与Ubuntu虚拟机的剪切板共享!
  • linux 进程堆栈分析
  • 【续集】Java之父的退休之旅:从软件殿堂到多彩人生的探索
  • LVS+Nginx高可用集群---Nginx进阶与实战
  • Appium环境搭建,华为nova8鸿蒙系统(包括环境安装,环境配置)(一)
  • 【React】React18 Hooks 之 useReducer
  • 【cocos creator】2.4.x实现简单3d功能,点击选中,旋转,材质修改,透明材质
  • Android EditText+ListPopupWindow实现可编辑的下拉列表
  • dify/api/models/task.py文件中的数据表
  • hdu物联网硬件实验3 按键和中断
  • pytorch通过 tensorboardX 调用 Tensorboard 进行可视化
  • linux查看目录下的文件夹命令,find 查找某个目录,但是不包括这个目录本身?
  • 单一设备上的 2 级自动驾驶:深入探究 Openpilot 的奥秘
  • 向github远程仓库中push,要求使用token登录
  • 最全windows提权总结(建议收藏)
  • Could not find Chrome (ver.xxxxx). This can occur if either\n
  • Conmi的正确答案——ESP32-C3开启安全下载模式