I have a mask which may have holes inside. I want to erode from the outside of the mask (so not the holes), horizontally in, a certain number of pixels.
The trick being if I'm eroding inwards 5px and at a certain point there is a hole 3px in from the edge, I want to erode those 3px and then the remaining 2px past the hole. So I'm always eroding 5px each side, essentially skipping over any holes.
For example with this mask:
These grey areas will be eroded:
I can see how to do this by looping over each row, something like:
erode_px = 5
for y, row in enumerate(mask):
idxs = np.nonzero(row)[0]
if idxs.size:
if idxs.size < erode_px * 2:
mask[y] = 0
else:
mask[y, :idxs[erode_px]] = 0
mask[y, idxs[-erode_px]:] = 0
But I am dealing with very large masks and this needs to be efficient. Is there a way to achieve this without looping over each row in Python? Preferably just using OpenCV / numpy.



