Morphological Opening and Closing
Implement a function to compute morphological opening and closing on a binary image using a given structuring element. Morphological operations are essential in Computer Vision for image processing and analysis, as they allow for the removal of noise and the extraction of relevant features. The opening operation, defined as , removes small bright noise, while the closing operation, defined as , fills small dark holes.
The structuring element is centred on each pixel (its middle cell is the anchor). Erosion sets an output pixel to 1 only if every image pixel lying under a 1 of se is 1; dilation sets it to 1 if at least one image pixel lying under a 1 of se is 1. Pixels outside the image count as 0 for both operations, so erosion turns off any pixel whose neighbourhood reaches past the border. The output grids have the same size as image.
- Apply erosion to the image using the structuring element to shrink the image.
- Apply dilation to the eroded image using the structuring element to expand it, resulting in the opening operation.
- Apply dilation to the original image using the structuring element to expand it.
- Apply erosion to the dilated image using the structuring element to shrink it, resulting in the closing operation.
This technique is widely used in image denoising and object detection applications.
Example
image = [[0,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,0]] se = [[0,1,0],[1,1,1],[0,1,0]]
{'opening': [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], 'closing': [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]}imageis a binary grid with one bright pixel at row 1, column 1 (from 0).seis a cross: the centre and its four direct neighbours.- Opening, erosion first: a pixel stays 1 only if all 5 cross positions centred on it are bright. The lone pixel at has dark neighbours, so erosion leaves all 0, and dilating an empty grid keeps the opening all 0.
- Closing, dilation first: a pixel turns on if its cross touches a bright pixel. That lights and its four neighbours , , , , a plus of 5 ones.
- Eroding the plus: at all five cross cells are bright, so it stays 1. The cross at reaches row , outside the image, which counts as 0; the other arms also touch a dark or outside pixel. Only remains.
- Notice the opening erased the speck while the closing returned the original image. Because outside pixels count as 0, closing can also shrink bright regions that touch the border.
Constraints
- image is a 2D binary list
- se is a 2D binary structuring element with odd dimensions
- Return dict with 'opening' and 'closing' keys