Suppose i have an image like this (the numbers are for explaining, so focus on the white):

I'm working on a method to create a hiearchy of the contours instead of a flat list. In the case of the image above:
-n1 holds 1 contour: n2
-n2 hold 3 contours: n3, n4, n5
-n5 holds 1 contour: n6
-n6 holds 1 contour: n7
Make sure you understand the above before continue reading.
I have the method addContainingBlob, this method is in the blob class. I already checked in another method if the blobToAdd is within the bounds of the blob where i add it. I get a StackOverflowError at this line: b.addContainingBlob(blobToAdd); // <<<<<<.
I'm breaking my head around this for the last hour. Can someone see why it goes wrong?
protected void addContainingBlob(Blob blobToAdd) {
if (containingBlobs.size() == 0) {
containingBlobs.add(blobToAdd);
return;
}
Rectangle r1 = new Rectangle();
r1.setBounds(blobToAdd.minX(), blobToAdd.minY(), blobToAdd.width(), blobToAdd.height());
Rectangle r2 = new Rectangle();
// first check if we already have a containing blob that
// can hold the one we like to add
for (Blob b : containingBlobs) {
r2.setBounds(b.minX(), b.minY(), b.width(), b.height());
if (r2.contains(r1)) {
b.addContainingBlob(blobToAdd); // <<<<<<
return;
}
}
// it can also be that one OR MORE of the containing blobs can fit in the blob we like to add
for (int i = containingBlobs.size()-1; i >= 0; i--) {
Blob b = containingBlobs.get(i);
r2.setBounds(b.minX(), b.minY(), b.width(), b.height());
if (r1.contains(r2)) {
containingBlobs.remove(i);
blobToAdd.addContainingBlob(b);
}
}
containingBlobs.add(blobToAdd);
}
If the code allows a blob to contains itself, the call to blobToAdd.addContainingBlob(b) will lead to infinite recursion because of
if (r2.contains(r1)) {
b.addContainingBlob(blobToAdd); // <<<<<<
return;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With