java - Recursive flood-filling overflows stack -
i'm working on algorithm take images , separate black , white chunks of pixels, unfortunately, seems overflow stack. here's suspected class:
package me.dylan.eat; import java.awt.point; import java.awt.rectangle; import java.awt.image.bufferedimage; import java.util.arraylist; public class cell { public point location = new point(0, 0); public cell(int x, int y) { location.x = x; location.y = y; } public void recurseneighbors(arraylist<cell> universe, bufferedimage img) { if (!universe.contains(this)) { universe.add(this); arraylist<cell> neighbors = cellutil.assimilateneighbors(location, img, new rectangle(0,0,0,0)); //get neighbors of same color (cell c : neighbors) { if (!universe.contains(c)) { c.recurseneighbors(universe, img); } } } } }
edit: image 640x480, big? exception thrown on line 23.
640x480 big. worst case you'll end 640*480 = 307200 levels deep.
you have few options. option 1 not recursively, instead maintain queue of pixels processed. initialize queue first round of cells checked, while queue not empty, remove front item, process it, , add new cells processed queue.
option 2 iterative approach, such ones described here (a queue-based approach described there well).
while recursion seems natural way implement flood fill, in practice hits stack limitations , iterative or queue based algorithms run more efficiently.
depending on goal, may want consider entirely different approach, such union-find (where 2 cells equivalent if both same color), give list of black , white groupings in image in o(log n) time (where n pixel count), in single pass.
Comments
Post a Comment