使用cv::FileStorage时出错 Can‘t open file: yaml‘ in read mode

7 篇文章 0 订阅
2 篇文章 0 订阅

1. 使用说明

在做的一个c++工程项目,想加一个配置文件,我发现主要有两种主流的方式,

(1)opencv有cv::FileStorage这样的一个函数可以使用。

(2)也可以使用cpp-yaml GitHub - jbeder/yaml-cpp: A YAML parser and emitter in C++

第一种是opencv自带的库,如果你工程已经依赖opencv库,建议用这种,它支持xml,yaml,json三种配置文件的处理;

第二种是一个开源的yaml项目,需要自己编译一下,使用可参考:CSDN

2. 代码

这里仅介绍cv::FileStorage

直接上代码:

(1)头文件:
#ifndef BOUNDARY_SETTING_H
#define BOUNDARY_SETTING_H

#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/core/utility.hpp>
#include <iostream>
#include <string>

class Setting
{
public:
    int max_width_;
    std::string model_path_;
public:
    void ReadSetting(const cv::FileNode& node);
    void DisplayPara();

// private:
};
#endif
(2)cpp源文件
#include "Setting.hpp"

void Setting::ReadYaml(const cv::FileNode& node)
{    
    node["max_width"] >> max_width_;
    node["model_path"] >> model_path_;
}

void Setting::DisplayPara()
{
    std::cout<<"max_width_:" <<max_width_<<std::endl;
    std::cout<<"model_path:"  <<model_path_<<std::endl;
}
(3)main文件
#include "BoundarySetting.hpp"


int main(int argc,char** argv)
{
    std::shared_ptr<Setting> g_setting = std::make_shared<Setting>();
    std::string strSettingsFile="./Setting.yaml";
    cv::FileStorage fs(strSettingsFile, cv::FileStorage::READ);


    if(!fs.isOpened())
    {
       std::cout << "Failed to open settings file at: " << strSettingsFile << std::endl;
       return 0;
    }
    g_setting->ReadYaml(fs["paras"]);
    fs.release();
    g_setting->DisplayPara();

    return 0;
}

3.YAML文件

%YAML:1.0
---
PARA:
  max_width: 1280
  model_path: ""
 

4. 问题

(1)编译后运行主要遇到了这个错误就是不能打开yaml文件。类似如下:

Can't open file: yaml' in read mode

这个问题主要是因为yaml文件的格式不对,建议先用cv::FileStorage::WRITE生成一个yaml文件,保证格式无误,然后再在上面手动修改或添加参数。

其他的可能遇到的一些问题就是:

(1)yaml文件的相对路径有问题,就用绝对路径,有网友这么说的;

(2)注意读yaml文件后的传参类型

(3)我任务yaml,json,xml 遇到的文件打不开,可能原因是类似的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值