0

I have the following M_Matrix

M = np.array([[0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1]])

which I want to erose using this structuring element.

st_element = np.ones((3, 3))

The final output sould seem like this

Output = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                   [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0],
                   [0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0],
                   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

My question is: is it possible to do erosion using only numpy_functions ? thanks

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
ABA
  • 37
  • 5
  • Why only numpy? You can perform a 2D convolution: https://stackoverflow.com/questions/43086557/convolve2d-just-by-using-numpy – mozway Feb 26 '22 at 16:40
  • It does seem a bit masochistic to try to do this without `scikit-image` or at least `scipy`. But really, you should do some research, then try some things, then come back with a question about aspects of the problem you can't crack. I'm not sure why a person would take the time to completely solve this for you when it's a 1-liner in `skimage`. – Matt Hall Feb 26 '22 at 16:59

1 Answers1

1

Using sliding_window_view (not the fastest, but not the slowest either)

import numpy as np
from numpy.lib.stride_tricks import sliding_window_view

M = np.array([[0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1]]).astype(bool)

st_element = np.ones((3, 3), dtype=bool)

padded = np.pad(M, st_element.shape[0]//2)

windows = sliding_window_view(padded, window_shape=st_element.shape)

eroded = np.all(windows | ~st_element, axis=(-1, -2))

Checking that it gives the same as scipy:

from scipy.ndimage import binary_erosion
np.testing.assert_array_equal(eroded, binary_erosion(M, st_element))
kuppern87
  • 1,125
  • 9
  • 14