Binary Erosion with a 3x3 Window

~12 mincode completion

Implement binary_erode(mask).

  • is a 2D array of 0s and 1s.
  • Return a 2D integer array of the same shape.

Examples

A 3x3 block of ones erodes to its centre pixel

Input
binary_erode([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
Output
[[0, 0, 0], [0, 1, 0], [0, 0, 0]]

A 4x4 block keeps its 2x2 interior

Input
binary_erode([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]])
Output
[[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]]

An isolated speckle is removed

Input
binary_erode([[0, 0, 0], [0, 1, 0], [0, 0, 0]])
Output
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Hints

Hint 1

Loop a fixed number of times and update the running value each pass.

Hint 2

Watch for this: padded with ones so the border survived.

Requirements

  • : 2D array of 0/1

  • Return 2D integer array, same shape: 1 where the whole 3x3 window was 1

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~12 min

8 employers weight this skill

4 autonomy companies, 1 defense company, 1 health and bio company, 1 enterprise vendor, 1 AI product company. Top match scores 81.

Python
import numpy as np


def binary_erode(mask):
    """
    3x3 binary erosion with zero padding.

    Args:
        mask: 2D array of 0/1

    Returns:
        2D integer array, same shape: 1 where the whole 3x3 window was 1
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.