Flood Fill in Python

后端 未结 2 1701
有刺的猬
有刺的猬 2020-12-11 08:35

I\'m complitely new to Flood Fill algorithm. I checked it out from Wikipedia (http://en.wikipedia.org/wiki/Flood_fill). But didn\'t become that much wiser. I\'m trying to us

相关标签:
2条回答
  • 2020-12-11 08:53

    There are several implementations of the flood fill algorithm in image processing libraries for Python. I'm aware of two: skimage.segmentation.flood and OpenCV's floodFill. The former is implemented in Python using an algorithm similar to the one in amit's answer above. The latter is implemented in C++ using a conceptually similar algorithm, but without recursion, making it much more efficient (about 25x for large images).

    To use OpenCV's floodFill, you'd need to convert your matrix to an np.array of integers, which could be done as follows:

    import numpy as np
    import cv2
    
    matrix_np = np.asarray(matrix)
    numeric_matrix = np.where(matrix_np=="a", 255, 0).astype(np.uint8)
    mask = np.zeros(np.asarray(numeric_matrix.shape)+2, dtype=np.uint8)
    start_pt = (y,x)
    if matrix_np[start_pt]:
      cv2.floodFill(numeric_matrix, mask, start_pt, 255, flags=4)
    mask = mask[1:-1, 1:-1]
    matrix_np[mask==1] = "c"
    matrix = matrix_np.tolist()
    

    With the example matrix you gave above and x,y=(0,0), this will set matrix to

    [['c', 'c', 'b', 'a', 'a', 'b'],
     ['c', 'b', 'b', 'a', 'b', 'b'],
     ['b', 'a', 'b', 'a', 'a', 'b'],
     ['b', 'a', 'b', 'a', 'b', 'b'],
     ['a', 'a', 'b', 'a', 'a', 'a'],
     ['a', 'b', 'b', 'a', 'a', 'b']]
    
    0 讨论(0)
  • 2020-12-11 08:59

    Well, the idea of flood fill is:

    1. Check if the point meet the criteria.
    2. If it is, change it to "c" (in your case) - and invoke flood fill on all surrounding cells.

    python-like pseudo code:

    def floodfill(matrix, x, y):
        #"hidden" stop clause - not reinvoking for "c" or "b", only for "a".
        if matrix[x][y] == "a":  
            matrix[x][y] = "c" 
            #recursively invoke flood fill on all surrounding cells:
            if x > 0:
                floodfill(matrix,x-1,y)
            if x < len(matrix[y]) - 1:
                floodfill(matrix,x+1,y)
            if y > 0:
                floodfill(matrix,x,y-1)
            if y < len(matrix) - 1:
                floodfill(matrix,x,y+1)
    
    0 讨论(0)
提交回复
热议问题