opencv / opencv_contrib

Repository for OpenCV's extra modules
Apache License 2.0
9.43k stars 5.76k forks source link

read access violation on RTrees' getRoots getNodes getSplits methods #3657

Open smasoudn opened 8 years ago

smasoudn commented 8 years ago

Please state the information for your system

Exception thrown for "read access violation" when using RTrees' methods. Mat.copyTo (vector) also doesn't copy the elements properly.

Code example to reproduce the issue / Steps to reproduce the issue

#include <iostream>

#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\ml\ml.hpp>

using namespace std;
using namespace cv;
using namespace cv::ml;

static Ptr<TrainData> prepareTrainData(Mat& pts, Mat& classes)
{
    Mat samples;
    Mat(pts).reshape(1, (int)pts.rows).convertTo(samples, CV_32F);
    Ptr<TrainData> a = TrainData::create(samples, ROW_SAMPLE, classes);
    return a;
}

int main()
{
    Mat training = (Mat_<float>(7, 2) << 1, 1, 2, 2, 3, 3, 1, 2, 3, 4, 5, 4, 3, 2);
    Mat classes = (Mat_<int>(7, 1) << 0, 0, 0, 1, 1, 2, 2);

    cout << "training data" << endl;
    cout << endl << training << " " << endl << endl;
    cout << "classes" << endl;
    cout << endl << classes << " " << endl << endl;

    Ptr<RTrees> rtrees = RTrees::create();

    rtrees->setMaxDepth(14);
    rtrees->setMinSampleCount(2);
    rtrees->setRegressionAccuracy(0.f);
    rtrees->setUseSurrogates(false);
    rtrees->setMaxCategories(3);
    rtrees->setPriors(Mat());
    rtrees->setCalculateVarImportance(false);

    rtrees->setActiveVarCount(1);
    rtrees->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 5, 0));
    Ptr<TrainData> a = prepareTrainData(training, classes);
    rtrees->train(a);

    // my own prediction
    vector<int> roots = rtrees->getRoots();                          // runtime error
    vector<DTrees::Node> nodes = rtrees->getNodes();    // runtime error
    vector<DTrees::Split> splits = rtrees->getSplits();        // runtime error

    Range range = Range(0, (int)roots.size());
    Mat sample = training.row(0);

    int nclasses = 2;
    vector<int> votes(nclasses, 0);
    Mat varIdx0 = a->getVarIdx();
    vector<int> varIdx;
    varIdx0.copyTo(varIdx);                                                        // wrong copy

    getchar();
    return 0;
}
ohnozzy commented 8 years ago

I tried the code with the latest commit 06ea0aa and did not get any runtime error. My environment: OS: WIndows 10 Compiler: VS2015

liquidmetal commented 7 years ago

Tried this on master commit 0330934c8bf932 and could not reproduce this.