Erosion and Dilation
Erosion and Dilation. Take a look at the
dot_and_hole image file, which is included in the course materials. The left-hand side of this binary image shows a white dot on a black background, while the right-hand side shows a black hole in a solid white section.
00:28 This filter replaces the value of a pixel with the minimum value of the nine pixels in a 3x3 array centered around the pixel. In a binary image, this means that a pixel will have the value of zero if any of its neighboring pixels are zero.
Dilation is the opposite process to erosion. White pixels are added to the boundaries in a binary image. You can achieve dilation by using
ImageFilter.MaxFilter(3), which converts a pixel to white if any of its neighbors are white.
and then apply
.MaxFilter() in a loop three times. This time, the dot has grown bigger, and the hole has shrunk. You can use erosion and dilation together to fill in holes and remove small objects from a binary image. Using the image with a dot and hole, you can perform ten erosion cycles to remove the dot, followed by ten dilation cycles to restore the hole to its original size.
You perform ten erosion cycles with the first
for loop, leading to the image seen on-screen. The dot has disappeared, but the hole is larger than it was in the original image. Next, you perform ten dilation cycles, and this returns the hole to its original size.
02:58 But note that the dot is no longer present in the image. The erosions and dilations have modified the image to keep the hole but remove the dot. The number of erosions and dilations needed depends on the image and what you want to achieve.
Often, you’ll need to experiment to find the right combination of each. You can define functions to perform several cycles of erosion and dilation. Create a file called
functions.py in your working directory and add the code seen on-screen to it.
04:00 These functions make it easier to experiment with erosion and dilation for an image. Placing them in a file allows you to import them quickly into any new REPL session, and you’ll be using them in the next section of the course as you continue working on placing the cat into the monastery.
Become a Member to join the conversation.