c++ - findContours, contourArea give errors with nested contours. "Assertion failed", "input array is not a valid matrix" -
i trying find largest contour in binarized image. judging this question , this tutorial think trivial, , agree. when run code on the image below though, produces errors. note 2x2 dot in upper left hand corner, should count 1 contour.
mat img = imread("problem.png", cv_load_image_grayscale); vector<vector<point>> contourvector; findcontours(img, contourvector, cv_retr_list, cv_chain_approx_none); //findcontours(img, contourvector, cv_retr_external, cv_chain_approx_none); // alternative mode int biggest = 0; double biggestcontourarea = contourarea(contourvector[biggest]); (int = 1; != contourvector.size(); ++i){ if ( (contourarea(contourvector[i])) > biggestcontourarea) { biggest = i; biggestcontourarea = contourarea(contourvector[biggest]); } } img = scalar(0,0,0); drawcontours(img, contourvector, biggest, scalar(255,255,255), cv_filled ); imshow("largest contour", img); waitkey(0);
if mode cv_retr_list used, error @ = 3, although contourvector has size 4. why vector larger number of contours, though?
"assertion failed: (0 <= contouridx && contouridx < (int)last) in unknown function, file ..[..]contours.cpp, line 1810"
if mode cv_retr_external used (which make more sense), error. why happen
opencv error: bad argument (input array not valid matrix) in unknown function, file ..[..]utils.cpp, line 54
i'd grateful if explain errors.
i wonder why result of contourarea inside loop 0 reason , contourvector[i].size() gives absurdly large number (around 4 billion).
i cannot judge cv_external case. in first case problem seems simple.
for (int = 1; != contourvector.size(); ++i){ if ( (contourarea(contourvector[i])) > biggestcontourarea) { biggest = i; biggestcontourarea = contourarea(contourvector[biggest]); } }
in c++ arrays , vectors indexed zero. first item in vector has index 0
, , last 1 has contourvector.size() - 1
.
to fix code change cycle to:
for (int = 1; < contourvector.size(); ++i) ....
Comments
Post a Comment