Flood Fill in Python


/ Published in: Python
Save to your folder(s)

A short snippet to demonstrate how to mark pixels inside e.g.a circle.
Note that checking if a pixel was already added or not would be done faster using as input to the floodfill function a duplicate array of the pixel data and simply setting any added pixels to one.


Copy this code and paste it in your HTML
  1. def floodfill( x,y,array, pixels_x, pixels_y):
  2. if x < 0 or x > len(array)-1:
  3. return
  4. if y < 0 or y > len(array[x])-1:
  5. return
  6. if array[x][y] == 1:
  7. return
  8. for i in range(0,len(pixels_x)):
  9. if pixels_x[i] == x and pixels_y[i] == y :
  10. return
  11. pixels_x.append(x)
  12. pixels_y.append(y)
  13. floodfill(x+1,y,array,pixels_x,pixels_y)
  14. floodfill(x-1,y,array,pixels_x,pixels_y)
  15. floodfill(x,y+1,array,pixels_x,pixels_y)
  16. floodfill(x,y-1,array,pixels_x,pixels_y)
  17. return
  18.  
  19. pixels_x = []
  20. pixels_y = []
  21.  
  22. array = [[0,0,0,0,0,0,0],
  23. [0,0,0,1,0,0,0],
  24. [0,0,1,0,1,0,0],
  25. [0,1,0,0,0,1,0],
  26. [1,0,0,0,1,0,0],
  27. [0,1,0,0,0,1,0],
  28. [0,0,1,0,1,0,0],
  29. [0,0,0,1,0,0,0]]
  30.  
  31. floodfill( 3,3, array, pixels_x, pixels_y )
  32. for i in range(0,len(pixels_x)):
  33. print "Pixel: " + str(pixels_x[i]) + "," + str(pixels_y[i])

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.