vendredi 30 octobre 2015

debugging code using opencv fails with segmentation fault

Trying to debug some c++11 code that utilizes the opencv library, yields a segmentation fault in gdb.

I am debugging following function using gdb in linux.

MatchedFeatures extract_best_features(vector<Mat> imgs)
{
  MatchedFeatures result;

  cv::Ptr<Feature2D> f2d = xfeatures2d::SIFT::create();
  //cv::Ptr<Feature2D> f2d = xfeatures2d::SURF::create();
  //cv::Ptr<Feature2D> f2d = ORB::create();

  for (auto it = 0; it < imgs.size(); ++it) {
    vector<KeyPoint> keyPoints;
    Mat descriptors;
    f2d->detect(imgs[it], keyPoints);
    f2d->compute(imgs[it], keyPoints, descriptors);
    result.imgFeatures.push_back(ImgFeatures{imgs[it], keyPoints, descriptors});
  }

  BFMatcher matcher;
  vector< DMatch > matches;
  matcher.match(result.imgFeatures[0].descriptors,
                result.imgFeatures[1].descriptors,
                matches);

  cout << matches.size() << "\n";

  //extract top 10
  sort(matches.begin(), matches.end(),
            [&](const DMatch x, const DMatch y) -> bool
            { return x.distance <= y.distance; });
  result.matches = vector<DMatch>(matches.begin(),matches.begin()+5); // <- debug fails here and matches is empty in debug mode
  return result;
}

The segmentation fault is yielded when the debugger reaches the point where I slice the matches vector. Inspecting the matches variable and looking at the stacktrace revealed that matches is empty.. However, only empty in debug mode.

The code works perfectly fine when I just run it normally, it only fails when debugging.

I noticed that the BFMatcher spawns a lot of threads when performing the match, so I suspect that the problem arises because of threads. Though I just started learning c++, so I can only guess whats wrong.

Is there some way to "wait" for the threads to finish properly in gdb? Or is there some other trick that allows me to debug and inspect this kind of code in c++ without getting segmentation faults and empty results from side-effect-generating-procedures such as match in BFMatcher?

Aucun commentaire:

Enregistrer un commentaire