简体   繁体   中英

How can I find all adjacent pixels of the same value without running into the current issue of a StackOverflowError?

I am working on a project where I need to find all adjacent "pixels" of a boolean array that have the same value (true). I am working with a two-dimensional array, so I am using a recursive method to take in a pixel and check each pixel around it, then run the same function on each successful pixel. I have recursed too deeply and Java doesn't like it. How could I approach this differently?

public static List<Vertex> searchToAdd(int x, int y, List<Vertex> pixelMass, boolean[][] pool)
{
    pixelMass.add(new Vertex(x, y));
    boolean valueToMatch = pool[x][y];

    if(pool[x+1] [y]   == valueToMatch) pixelMass = searchToAdd(x+1, y, pixelMass, pool);
    if(pool[x]   [y+1] == valueToMatch) pixelMass = searchToAdd(x, y+1, pixelMass, pool);

    if(x-1 >= 0)
    {
        if(pool[x-1][y] == valueToMatch) pixelMass = searchToAdd(x-1, y, pixelMass, pool);
    }

    if(y-1 >= 0)
    {
        if(pool[x][y-1] == valueToMatch) pixelMass = searchToAdd(x, y-1, pixelMass, pool);
    }

    return pixelMass;
}

If any more of my code is needed, feel free to ask.

Two observations, firstly can you declare pixelmass as a static list instead of passing it as a function argument? This would save a large amount of stack space. Secondly, there doesn't seem to be any attempt to prevent recursing on a pixel that has already been checked. The recursion will only terminate if there are no adjacent pixels, ie a single pixel without neighbours. Otherwise the recursion will find the original pixel, and call itself until the stack overflows. One way to get round this is is to check your list. A better way is to maintain another boolean array marking which pixels have been recursed from.

// ...
pixelMass.add(new Vertex(x, y));
done[x][y] = 1;
boolean valueToMatch = pool[x][y];

if(pool[x+1][y] == valueToMatch && done[x+1][y] == 0)
    pixelMass = searchToAdd(x+1, y, pixelMass, pool);
// etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM