Search code examples
javaandroidstack-overflowedge-detection

Canny edge detector for Android -- StackOverflow on recursive function


I'm working on an augmented reality app for Android. I'm implementing Tom Gibara's canny edge detector class and have replaced BufferedImage, which is not supported by Android, with Bitmap.

The method "follow" (posted below) is causing a StackOverflow error for me. It's a recursive function, but what baffles me is that it will work correctly for about 10-15 seconds before crashing, on the device.

From Google, it looks like people have successfully implemented this class in Java, but I'm wondering if, for whatever reason, it doesn't work on Android. Gibara's code specifies that it is for single-threaded use only; could this be part of the problem? If not that, is my error obvious to anyone?

Thank you!

private void follow(int x1, int y1, int i1, int threshold) {  
    int x0 = x1 == 0 ? x1 : x1 - 1;  
    int x2 = x1 == width - 1 ? x1 : x1 + 1;  
    int y0 = y1 == 0 ? y1 : y1 - 1;  
    int y2 = y1 == height -1 ? y1 : y1 + 1;

    data[i1] = magnitude[i1];  
    for (int x = x0; x <= x2; x++) {  
        for (int y = y0; y <= y2; y++) {  
            int i2 = x + y * width;  
            if ((y != y1 || x != x1) && data[i2] == 0 
                    && magnitude[i2] >= threshold) {  
                follow(x, y, i2, threshold);  
                return;  
            }  
        }  
    }  
}

Solution

  • Android's default thread stack is much smaller than what you get on a desktop. In current Android builds (2.3), the stack size is set to 12kB I believe. Your recursion is simply too deep.