前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >OpenCV中YAML配置文件读写使用演示

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

作者头像
OpenCV学堂
发布2023-08-22 13:38:44
4130
发布2023-08-22 13:38:44
举报
文章被收录于专栏:贾志刚-OpenCV学堂
前言

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

FileStorage类介绍

FileStorage类是OpenCV封装的支持读写XML、JSON、YAML文件的工具类。有多个构造函数支持创建实例,最常用的创建方式如下:

代码语言:javascript
复制
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文件中读出数据

代码语言:javascript
复制
// 加载参数
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文件

代码语言:javascript
复制
// 保存参数
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文件读写的示例如下:

代码语言:javascript
复制
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文件内容截图:

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-08-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 OpenCV学堂 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档