0

I am working on an image project, and I'm trying to make a connected components algorithm. This is what I have come up with:

Mat OPG3::cc(Mat imgCC) {

int p = 1;
int lable = 1;
copyMakeBorder(imgCC, imgCC, p, p, p, p, BORDER_CONSTANT, 0);

for (int imgRow = p; imgRow < imgCC.rows - p; imgRow++) {
    for (int imgCol = p; imgCol < imgCC.cols - p; imgCol++) {
        if (imgCC.at < uchar >(imgRow,imgCol) == 255) {
            imgCC.at<uchar>(imgRow, imgCol) = lable;
            recursive(imgRow, imgCol - 1, lable, p, imgCC);
            recursive(imgRow + 1, imgCol, lable, p, imgCC);
            recursive(imgRow, imgCol + 1, lable, p, imgCC);
            recursive(imgRow - 1, imgCol, lable, p, imgCC);
            ++lable;

        }
    }
}
    return imgCC;
}

void OPG3::recursive(int i, int j, int lable, int p, Mat& imgCC) {

if (imgCC.at < uchar >(i, j) == 255) {
    imgCC.at<uchar>(i, j) = lable;
    recursive(i, j - 1, lable, p, imgCC);
    recursive(i + 1, j, lable, p, imgCC);
    recursive(i, j + 1, lable, p, imgCC);
    recursive(i - 1, j, lable, p, imgCC);

}

}

When I run the code, it stops in the middle of the execution with some images, but with outhers it executes correctly.

Is it possible that the algorithm in some cases makes too many function calls?

Vikash Chauhan
  • 792
  • 2
  • 9
  • 18
  • 1
    *Is it possible that the algoritme in some cases makes to many function calls?* Yes. Every function call takes up some amount of Automatic storage for book-keeping, parameters, and local variables. Recursion that goes too deep can easily run you out of Automatic storage (usually a stack of 1-10 MB in size for a PC) and invoke Undefined Behaviour. – user4581301 Oct 27 '18 at 22:01
  • C++ does not, in general, support tail call recursion. As a programmer, the burden is on the programmer to use an appropriate loop. (That being said, languages that require tail call recursion have some strict requirements to allow it, and if the programmer makes a mistake such that the optimization can't happen the compiler won't even warn about it.) – Eljay Oct 27 '18 at 22:13

1 Answers1

0

I didn't understand all the details, but I can see that your recursion may visit neighboring pixels over and over.

For example you go from (i, j) to (i+1, j) and from there back to (i, j).

Most likely, there are initial states where this recursion never stops, when lable reaches 255 and becomes reassigned over and over to all pixels before it could be incremented again.

Such an infinite recursion comes to a halt when execution resources are exhausted or some inner compiler limit was reached.

bjhend
  • 1,538
  • 11
  • 25