Enlarge holes in 2D array mask

173 Views Asked by At

I have a 2D binary mask and I want to enlarge the holes in it by creating squares of dimension WxW where W is a parameter.

Supposing W = 3 I would like to trasform this matrix:

[[0, 0, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

Into this matrix:

[[0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

I'm currently using numpy to manage arrays. I think I can do it but I can't find an efficient way to do it, and I'm not sure how to handle edge cases (if a 1 is in the upper right corner, I still want WxW squares, not smaller...)

Thanks to all.

1

There are 1 best solutions below

0
On BEST ANSWER

If you can consider opencv, you can use dilation

import cv2
import numpy as np

img = cv2.imread('j.png',0)
kernel = np.ones((3, 3), np.uint8)
dilation = cv2.dilate(img, kernel, iterations=1)

You can also consider scipy's version


For pure numpy you will have to work a little by using this with a kernel of ones, and thresholding afterwards.