After thresholding an image or predicting a segmentation mask you often get a binary image with specks of noise and small holes. Morphological operations clean it up by sliding a small structuring element over it. Erosion keeps a pixel only if the whole element fits inside the white region around it, so it shrinks shapes and deletes specks smaller than the element. Dilation turns a pixel white if the element touches any white pixel, so it grows shapes and fills small holes. Eroding then dilating is an opening: it removes small noise while mostly restoring the size of the large shapes.
Implement erode, dilate and opening.
binary is a 2-D array of 0 and 1. The structuring element is a full k x k square of ones with odd k. Pixels outside the image count as 0.erode(binary, k): output is 1 where all pixels in the k x k window centred on the pixel are 1.dilate(binary, k): output is 1 where any pixel in the window is 1.opening(binary, k) is dilate(erode(binary, k), k). All outputs have the input's shape and integer dtype.Pad with k // 2 zeros, then take the minimum (erosion) or maximum (dilation) over the k * k shifted slices.
Erosion treats the border as background, so a shape touching the border loses its border pixels.
No results yet
Run your code to check it against the examples, or submit to run every test.