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

描述

前言

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

FileStorage类介绍

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

 

cv::FileStorage(
const String & filename,
int flags,
const String & encoding = String()
)

 

各个参数的解释意义如下:

filename 表示读写的文件名称

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

算法

写入

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

读出

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

释放文件

FileStorage读写完成之后,必须通过release方法实现文件资源释放。

C++代码演示

从YAML文件中读出数据

// 加载参数
cv::FileStorage fs(fileName, cv::READ);
if (!fs.isOpened()) {
    std::cout<< "could not find the parameters config file..." <> 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::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文件内容截图:

 

算法

  审核编辑:汤梓红
 
打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分