StereoMatching
StereoMatching

Reputation: 5019

Write and read opencv3.0 ml files(random forest)

How coulod I read the data of the xml files of opencv3.0 written by cv::FileStorage, I use the same solution from this [post][1] but no avail.

The error messages are

"C:\Users\yyyy\Qt\3rdLibs\opencv\opencv-3.0.0\sources\modules\core\src\persistence.cpp:739: error: (-2) The node is neither a map nor an empty collection in function cvGetFileNodeByName"

Codes : write

    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());

Any idea what is going on?How could I load the data from the xml file?Thanks

Upvotes: 3

Views: 2470

Answers (2)

Steven
Steven

Reputation: 430

Using the save() and load() functions from the StatModel class is in general a safer option to properly I/O all the info in a machine learning model. This is also given as an input/output example in samples/cpp/letter_recog.cpp

model_trained->save(filename_model);

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

Upvotes: 0

Miki
Miki

Reputation: 41765

You should use:

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

Testing Code

#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;
}

Upvotes: 2

Related Questions