Question

I'm using openCV 2.3.1 on Xcode4 OS X 10.7

I've got a (demo) code which finds contours after some basic background subtraction and displays it in various colors. This part works.

I would like to filter out contours smaller than a specific size, but when I call contourArea(), I get the following assertion fail:

OpenCV Error: Assertion failed (0 <= i && i < (int)vv.size()) in getMat, file /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_graphics_opencv/opencv/work/OpenCV-2.3.1/modules/core/src/matrix.cpp, line 912
terminate called throwing an exception

The relevant code is:

for( ; idx >= 0; idx = hierarchy[idx][0] ) {
           //double area = contourArea(contours);
           //cout << area << endl;
           Scalar color( rand()&255, rand() &255, rand()&255);
           drawContours(dst, contours, idx, color);
       }

Which is the last for-loop of:

#include "opencv/cv.h"
#include "opencv/highgui.h"
#include <iostream>
#include <vector>
#include "opencv2/video/background_segm.hpp"


using namespace std;
using namespace cv;

void refineSegments(const Mat& img, Mat& mask, Mat& dst)
{
int niters = 3;

vector<vector<Point> > contours;
vector<Vec4i> hierarchy;

Mat temp;

dilate(mask, temp, Mat(), Point(-1,-1), niters);
erode(temp, temp, Mat(), Point(-1,-1), niters*2);
dilate(temp, temp, Mat(), Point(-1,-1), niters);

findContours( temp, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );

dst = Mat::zeros(img.size(), CV_8UC3);

if( contours.size() == 0 )
    return;

// iterate through all the top-level contours,
// draw each connected component with its own random color
int idx = 0;

for( ; idx >= 0; idx = hierarchy[idx][0] ) {
    double area = contourArea(contours);
    cout << area << endl;
    Scalar color( rand()&255, rand() &255, rand()&255);
    drawContours(dst, contours, idx, color);
}
}

I complaining piece of code in the source is:

if( k == STD_VECTOR_VECTOR )
{
    int t = type(i);
    const vector<vector<uchar> >& vv = *(const vector<vector<uchar> >*)obj;
    CV_Assert( 0 <= i && i < (int)vv.size() );
    const vector<uchar>& v = vv[i];

    return !v.empty() ? Mat(size(i), t, (void*)&v[0]) : Mat();
}

But I can't make head or tails of this... i is an int that is passed to getMat, but what it really is, and why it should be less than 0 is beyond me >__<. Seems very odd to me that this standard function does this, can anyone shed a little light on this?

Was it helpful?

Solution

It's a simple typo. You are giving all the contours to the contourArea function:

double area = contourArea(contours);

You probably wanted

double area = contourArea(contours[idx]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top