Shape detection, why try several threshold levels?

I would like simply to know why in most of the shape detection algorythm the approach is search the contours by applying several threshold levels of binarization.

I'm referring in particular to this snippet of code extacted by the Squares.cpp sample:

...
// try several threshold levels
for( int l = 0; l < N; l++ )
{
// hack: use Canny instead of zero threshold level.
if( l == 0 )
{
// apply Canny. Take the upper threshold from slider
// and set the lower to 0 (which forces edges merging)
Canny(gray0, gray, 0, thresh, 5);
// dilate canny output to remove potential
// holes between edge segments
dilate(gray, gray, Mat(), Point(-1,-1));
}
else
{
// apply threshold if l!=0:
//     tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
gray = gray0 >= (l+1)*255/N;
}
...
}


I understood the reason to use Canny when N is 0, but I can't say the same for the several threshold attempts. Any help will be very appreciated. Thanks.

edit retag close merge delete

Sort by ยป oldest newest most voted

From my experience, it helps you to avoid those situations where you might not get a blob of isolated points belonging to the shape you'd like to detect.

An example: the first image comes from a threshold of 75, the second one from a threshold of 95. These are sections of two close squares, but in the first case you won't fine any result because the borders are still connected in some points.

You can solve this by trying more threshold levels (well, not as much as in squares.cpp example because the last 3 iterations are removing most of the points in the resulting binary image) or perform an erode to remove those points between the borders (if they're small enough).

more