微信公众号:OpenCV学堂
关注获取更多计算机视觉与深度学习知识
前言
FileStorage类介绍
FileStorage类是OpenCV封装的支持读写XML、JSON、YAML文件的工具类。有多个构造函数支持创建实例,最常用的创建方式如下:
cv::FileStorage::FileStorage(
const String & filename,
int flags,
const String & encoding = String()
)
各个参数的解释意义如下:
filename 表示读写的文件名称
flags表示文件类型cv::FileStorage::Mode,当前支持的模式包含:
写入
读出
释放文件
C++代码演示
// 加载参数
cv::FileStorage fs(fileName, cv::FileStorage::READ);
if (!fs.isOpened()) {
std::cout<< "could not find the parameters config file..." <
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();
// 保存参数
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代码演示
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()
扫码查看 CV系统化学习路线图(OpenCV+Pytorch)