写和读取opencv3.0 ml文件(随机森林)

时间:2015-08-01 10:28:11

标签: c++ opencv

我如何阅读cv :: FileStorage编写的opencv3.0 xml文件的数据,我使用了[post] [1]中的相同解决方案,但没有用。

错误消息是

“C:\ Users \ yyyy \ Qt \ 3rdLibs \ opencv \ opencv-3.0.0 \ sources \ modules \ core \ src \ persistence.cpp:739:错误:( - 2)节点既不是地图也不是函数cvGetFileNodeByName“

中的空集合

代码:写

    auto rtrees = cv::ml::RTrees::create();
    rtrees->setMaxDepth(10);
    rtrees->setMinSampleCount(2);
    rtrees->setRegressionAccuracy(0);
    rtrees->setUseSurrogates(false);
    rtrees->setMaxCategories(16);
    rtrees->setPriors(cv::Mat());
    rtrees->setCalculateVarImportance(false);
    rtrees->setActiveVarCount(0);
    rtrees->setTermCriteria({cv::TermCriteria::MAX_ITER, 100, 0});

    rtrees->train(features_.reshape(1, labels_.size()),
                  cv::ml::ROW_SAMPLE, labels_);
    rtrees->write(cv::FileStorage("smoke_classifier.xml",
                                  cv::FileStorage::WRITE));


Codes : read

    using namespace cv::ml;    
    cv::FileStorage read("smoke_classifier.xml",
                         cv::FileStorage::READ);
    rtrees->read(read.getFirstTopLevelNode());

知道发生了什么吗?我如何加载xml文件中的数据?谢谢

2 个答案:

答案 0 :(得分:2)

您应该使用:

rtrees->read(read.root());

测试代码

#include <opencv2\opencv.hpp>

using namespace cv;
using namespace std;

int main()
{
    {
        auto rtrees = cv::ml::RTrees::create();
        rtrees->setMaxDepth(10);
        rtrees->setMinSampleCount(2);
        rtrees->setRegressionAccuracy(0);
        rtrees->setUseSurrogates(false);
        rtrees->setMaxCategories(16);
        rtrees->setPriors(cv::Mat());
        rtrees->setCalculateVarImportance(false);
        rtrees->setActiveVarCount(0);
        rtrees->setTermCriteria({ cv::TermCriteria::MAX_ITER, 100, 0 });

        // Some dummy stuff here...
        Mat1f feat(1, 5, 0.f);
        Mat1f labels = (Mat1f(1, 5) << 1, 0, 1, 0, 1);

        rtrees->train(feat, cv::ml::ROW_SAMPLE, labels);
        rtrees->write(cv::FileStorage("smoke_classifier.xml",
            cv::FileStorage::WRITE));
    }

    {
        auto rtrees2 = cv::ml::RTrees::create();

        cv::FileStorage read("smoke_classifier.xml", cv::FileStorage::READ);
        rtrees2->read(read.root());

        int a = rtrees2->getMinSampleCount();
    }

    return 0;
}

答案 1 :(得分:0)

使用StatModel类中的save()和load()函数通常是一个更安全的选项,可以正确地I / O机器学习模型中的所有信息。 这也是samples / cpp / letter_recog.cpp

中的输入/输出示例
model_trained->save(filename_model);

Ptr<RTrees> model_read = StatModel::load<RTrees>( filename_model );