Beginning Python Visualization: Crafting Visual Transformation Scripts

Page 326

308

CH APT ER 9 N IMA G E P R OC ES S ING

Part 3: Flood Fill and Recursion We now turn to something completely different: recursion. Recursion describes a scenario where a function calls itself. Some known recursion algorithms implement the factorial operation and Fibonacci sequences. We’ll use recursion for image processing, specifically to fill an image using a flood-fill algorithm. Flood fill, sometimes also referred to as bucket fill, is an algorithm to fill a closed area of a specific color with a different color. This is a quite common operation in most image processing applications. Kids love to use it to paint digital coloring images. To implement flood fill, we’ll use recursion. In the implementation, we’ll assume that the image to fill is given to us as a NumPy array, more specifically as a 2-D array (i.e., a matrix). It’s also possible to manipulate a PIL Ei]ca object, but I prefer using a matrix for two reasons:

s )T S MORE GENERIC ) CAN PORT THE FLOOD FILL ALGORITHM TO OTHER OBJECTS AS LONG AS ) CAN convert the objects to a NumPy array (matrix).

s )T S EASIER TO VIEW THE CODE BY INDEXING OVER MATRIX ELEMENTS THAN TO USE THE capletah$% and oapletah$% methods provided by the Ei]ca object.

So how does flood fill work? Flood fill starts by receiving a point to start filling from. If the point is the color to be converted, flood fill will change the color to the desired color. It then moves to a point adjacent to it, say to the right, and calls itself. As the process continues, points to the right will start filling up with the new color. If the point to the right is not in the desired color (that is, shouldn’t be painted), the point to the top is checked, and the process resumes. This process is repeated for left and bottom points surrounding each point. The end process is a filled, closed object.

FLOOD FILL AND MINESWEEPER The flood-fill algorithm can also be used in the coding of the game Minesweeper (shipped with Windows). You can use the algorithm to expand an area and reveal points adjacent to mines. The algorithm will follow a similar path, and one option would be to create a matrix of values corresponding to whether a square is empty (value 0) or adjacent to a mine (value equal to the number of mines it is adjacent to), with a different value indicating a mine (say, value –1). When the user clicks on a square, the flood-fill algorithm kicks in and decides how many squares to reveal. If you’re not familiar with Minesweeper, I suggest you refrain from trying it; the game is addictive.

Listing 9-11 presents a simple flood-fill implementation.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.