Skip to content

Instantly share code, notes, and snippets.

@JDWarner
Created May 19, 2015 06:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JDWarner/1158a9515c7f1b1c21f1 to your computer and use it in GitHub Desktop.
Save JDWarner/1158a9515c7f1b1c21f1 to your computer and use it in GitHub Desktop.
Flood fill - pure Python
# 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))
@nandrana
Copy link

nandrana commented Sep 1, 2020

Hello JD,
It was a great help!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment