Open In App

Floodfill Image using Python-Pillow

Seed Fill also known as flood fill, is an algorithm used to identify connected paths in a definite enclosed region. The algorithm has an array of practical applications, such as –

There are various ways in which the algorithm could be implemented such as –



We will be utilizing floodfill algorithm in order to do image processing tasks. For this purpose, we will be using pillow library. To install the library, execute the following command in the command-line:-

pip install pillow

Note: Several Linux distributions tend to have Python and Pillow preinstalled into them



Syntax: ImageDraw.floodfill(image, seed_pos, replace_val, border-None, thresh=0) 

Parameters: 
image – Open Image Object (obtained via Image.open, Image.fromarray etc). 
seed_pos – Seed position (coordinates of the pixel from where the seed value would be obtained). 
replace_val – Fill color (the color value which would be used for replacement). 
border – Optional border value (modifies path selection according to border color) 
thresh – Optional Threshold Value (used to provide tolerance in floodfill, to incorporate similar valued pixel regions) 

Return: NoneType (modifies the image in place, rather than returning then modified image)

Example: 

Image Used:

  




# Importing the pillow library's
# desired modules
from PIL import Image, ImageDraw
  
# Opening the image (R prefixed to
# string in order to deal with '\'
# in paths)
img = Image.open(R"sample.png")
 
# Converting the image to RGB mode
img1 = img.convert("RGB")
 
# Coordinates of the pixel whose value
# would be used as seed
seed = (263, 70)
  
# Pixel Value which would be used for
# replacement
rep_value = (255, 255, 0)
  
# Calling the floodfill() function and
# passing it image, seed, value and
# thresh as arguments
ImageDraw.floodfill(img, seed, rep_value, thresh=50)
  
# Displaying the image
img.show()

Output:

  

Explanation:


Article Tags :