Morphological Dilation

Computer VisionMedium+15 XP+15

Morphological Dilation

Dilation is erosion's mirror image. Where erosion demands that the whole structuring element fit inside white, dilation is satisfied by a single hit — so white shapes grow outward, small holes fill in, and broken lines reconnect.

Task: write dilate(binary_image, kernel) returning a new grid of 0s and 1s, the same size as the input.

For each output position, centre the kernel on it, then:

  • Look at every kernel cell holding a 1.

  • The output is 1 if any one of those positions lands on a 1 in the image.

  • Otherwise the output is 0.

  • binary_image holds only 0 and 1. kernel is square with an odd side length, anchored at its centre.

  • Everything outside the image counts as 0, so an out-of-bounds cell simply never produces a hit. Unlike erosion, this convention leaves the border alone rather than eating it — a shape touching the edge grows along the edge.

So the pair differs in exactly one word: erosion is all, dilation is any. Written carefully, the two functions are the same loops with and swapped for or, which is worth seeing directly — it's the clearest example of a duality in image processing.

The practical use is repair. A scanned document with faint broken strokes, or a segmentation mask pitted with small holes, both come back whole after one dilation; follow it with an erosion and you've filled the gaps without permanently fattening everything.

Examples

binary_image = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
kernel = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
returns [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
binary_image = [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 0, 0]]
kernel = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]
returns [[0, 1, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 0, 1]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run