Cheng Ma Cheng Ma - 5 months ago 95
C++ Question

Opencv Findcontours cause heap error

I am using opencv 2.49.

But I am stuck by find contours function for hours.

When I run the program in debug mode and the error box returns

Debug assertion failed

Program: ...
File f:\dd\vctools\crt_bld\self_x86\crt\src\dbgheap.c

Line: 1322

Exception:_ CrtIsValidHeapPoionter(pUserData)

And here is my function

HRESULT OpenCVHelper::DrawHand(Mat* pImg)
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
cvtColor(*pImg, *pImg, CV_RGBA2GRAY);
//Canny(*pImg, *pImg, 30,50);
threshold( *pImg, *pImg, 50, 255,THRESH_BINARY);
if(pImg->type() == CV_8UC1)
findContours( *pImg, contours, hierarchy, CV_RETR_LIST,CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
for( int i = 0; i< contours.size(); i++ )
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
Scalar color( rand()&255, rand()&255, rand()&255 );
drawContours( *pImg, contours, i, color, 2, 8, hierarchy, 0, Point() );

cvtColor(*pImg, *pImg, CV_GRAY2RGBA);
return S_OK;


When I remove findcontour function there is no error.

When I use findcontour it pops the error box showed above.

When I add "contours.clear(); hierarchy.clear();" these two lines, there is no error message but the program still crashes.

Anyone can help?

EDIT 1. I find out the allocator for causing heap corruption, which is vector > contours; but I still don't know how to fix it.


The code you have should work. Most likely point of failure is having an empty image when you get to findContours. I am not talking about uninitialized image but the one that was initialized with Size(0,0). Change your 'if-statement' to be:

if ((pImg->type() == CV_8UC1) && (pImg->rows>0))

If this won't help, than next step is to verify that the function that crushes is indeed findContours and not drawContours. The crash may be in drawContours because it is not used when you remove findContours.

Also it is VERY not recommended to use pointer to Mat. Mat is a smart pointer by itself, and it has reference counter. This will create all kinds of nasty bugs.