PLC论坛-全力打造可编程控制器专业技术论坛

 找回密码
 注册哦

QQ登录

只需一步,快速开始

微信扫码登录

查看: 56140|回复: 0

OpenCV中YAML配置文件读写使用演示

[复制链接]
发表于 2024-3-15 11:11:29 | 显示全部楼层 |阅读模式


关注获取更多计算机视觉与深度学习知识

前言
我们在做OpenCV开发的时候经常需要把算法在一些场景下的调试好的参数作为默认值保存然后自动加载,然后在默认值的基础上根据需要适度调整。OpenCV中支持把参数保存为TXT格式的YAML文件,实现类似XML与JSON的参数文件读写,主要是基于FileStorage这个类完成。
FileStorage类介绍

FileStorage类是OpenCV封装的支持读写XML、JSON、YAML文件的工具类。有多个构造函数支持创建实例,最常用的创建方式如下:
cv::FileStorage::FileStorage(const String & filename,int flags,const String & encoding = String())
各个参数的解释意义如下:

filename 表示读写的文件名称

flags表示文件类型cv::FileStorage::Mode,当前支持的模式包含:



写入
写入文本内容的函数是write,支持不同类型函数的重载,支持的数据类型包含int、double、string等,OpenCV C++支持直接通过操作符<<重载实现写入。

读出
FileStroage通过操作符重载实现读出各种数据类型,通过在Python SDK支持通过getNode方式完成参数数据读出。OpenCV C++ 支持通过操作符>>重载实现读出。

释放文件
FileStorage读写完成之后,必须通过release方法实现文件资源释放。
C++代码演示
从YAML文件中读出数据// 加载参数cv::FileStorage fs(fileName, cv::FileStorage::READ);if (!fs.isOpened()) {    std::cout<< "could not find the parameters config file..." <<std::endl;    return;}fs["onnxModelPath"] >> this->onnxModelPath;fs["labelmapPath"] >> this->labelmapPath;fs["score"] >> this->score;fs["confidence"] >> this->conf;fs["nms"] >> this->nms;fs["mode"] >> this->mode;fs["showFPS"] >> this->showFPS;fs["showLabel"] >> this->showLabel;fs["showBox"] >> this->showBox;fs["showMask"]>> this->showMask;fs.release();
把数据保存为YAML文件// 保存参数cv::FileStorage fs(fileName, cv::FileStorage::WRITE);fs << "onnxModelPath" << this->onnxModelPath;fs << "labelmapPath" << this->labelmapPath;fs << "score" << this->score;fs << "confidence" << this->conf;fs << "nms" << this->nms;fs << "mode" << this->mode;fs << "showFPS" << this->showFPS;fs << "showMask" << this->showMask;fs << "showLabel" << this->showLabel;fs << "showBox" << this->showBox;fs.release();

Python代码演示
OpenCV-Python SDK实现YAML文件读写的示例如下:import cv2 as cv

param1 = 25
param2 = 0.25
param3 = "lena.jpg"

# 写文件
model_settings = cv.FileStorage("mytest.yaml", cv.FILE_STORAGE_WRITE)
model_settings.write('version', 'v1.0')
model_settings.write('author', 'gloomyfish')
model_settings.write('param1', param1)
model_settings.write('param2', param2)
model_settings.write('param3', param3)
model_settings.release()

# 读文件
cv_setting = cv.FileStorage("mytest.yaml", cv.FileStorage_READ)
param1 = cv_setting.getNode('param1').real()
param2 = cv_setting.getNode('param2').real()
param3 = cv_setting.getNode('param3').real()
YAML文件内容截图:




本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册哦

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册哦

本版积分规则

QQ|小黑屋|手机版|Archiver|PLC技术网-PLC论坛 ( 粤ICP备17165530号 )|网站地图

GMT+8, 2024-5-10 00:09 , Processed in 0.053404 second(s), 26 queries .

快速回复 返回顶部 返回列表