Morphological operations are fundamental tools for processing binary images. Erosion shrinks foreground regions (removing thin protrusions and noise), while dilation expands them (filling small holes and connecting nearby components).
Given a binary image (0s and 1s), a binary structuring element (kernel), and an operation type ("erode" or "dilate"), apply the morphological operation with zero-padding.
Pad the image with zeros using padding = kernel_size // 2 on each side. For each output pixel at position (i, j):
Erosion: the output is 1 only if every position where the kernel is 1 also has a 1 in the corresponding image position. Otherwise the output is 0.
Dilation: the output is 1 if any position where the kernel is 1 has a 1 in the corresponding image position. Otherwise the output is 0.
Input: image = [[0, 0, 0], [0, 1, 0], [0, 0, 0]], kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]], operation = "dilate"
Output: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
Explanation: The active center pixel reaches every location covered by the kernel.
Input: image = [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]], operation = "erode"
Output: [[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]]
For erosion, begin with one and clear it when any active-kernel position sees zero.
For dilation, begin with zero and set it when any active-kernel position sees one.
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: string
Morphological operations are fundamental tools for processing binary images. Erosion shrinks foreground regions (removing thin protrusions and noise), while dilation expands them (filling small holes and connecting nearby components).
Given a binary image (0s and 1s), a binary structuring element (kernel), and an operation type ("erode" or "dilate"), apply the morphological operation with zero-padding.
Pad the image with zeros using padding = kernel_size // 2 on each side. For each output pixel at position (i, j):
Erosion: the output is 1 only if every position where the kernel is 1 also has a 1 in the corresponding image position. Otherwise the output is 0.
Dilation: the output is 1 if any position where the kernel is 1 has a 1 in the corresponding image position. Otherwise the output is 0.
Input: image = [[0, 0, 0], [0, 1, 0], [0, 0, 0]], kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]], operation = "dilate"
Output: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
Explanation: The active center pixel reaches every location covered by the kernel.
Input: image = [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]], operation = "erode"
Output: [[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]]
For erosion, begin with one and clear it when any active-kernel position sees zero.
For dilation, begin with zero and set it when any active-kernel position sees one.
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: string