Created
May 19, 2015 06:29
-
-
Save JDWarner/1158a9515c7f1b1c21f1 to your computer and use it in GitHub Desktop.
Flood fill - pure Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Pure Python, usable speed but over 10x greater runtime than Cython version | |
def fill(data, start_coords, fill_value): | |
""" | |
Flood fill algorithm | |
Parameters | |
---------- | |
data : (M, N) ndarray of uint8 type | |
Image with flood to be filled. Modified inplace. | |
start_coords : tuple | |
Length-2 tuple of ints defining (row, col) start coordinates. | |
fill_value : int | |
Value the flooded area will take after the fill. | |
Returns | |
------- | |
None, ``data`` is modified inplace. | |
""" | |
xsize, ysize = data.shape | |
orig_value = data[start_coords[0], start_coords[1]] | |
stack = set(((start_coords[0], start_coords[1]),)) | |
if fill_value == orig_value: | |
raise ValueError("Filling region with same value " | |
"already present is unsupported. " | |
"Did you already fill this region?") | |
while stack: | |
x, y = stack.pop() | |
if data[x, y] == orig_value: | |
data[x, y] = fill_value | |
if x > 0: | |
stack.add((x - 1, y)) | |
if x < (xsize - 1): | |
stack.add((x + 1, y)) | |
if y > 0: | |
stack.add((x, y - 1)) | |
if y < (ysize - 1): | |
stack.add((x, y + 1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello JD,
It was a great help!!