In a boolean matrix, what is the best way to make every value adjacent to True/1 to True?

Question:

I have a numpy boolean 2d array with True/False. I want to make every adjacent cell of a True value to be True. What’s the best/fastest of doing that in python?

For Eg:

#Initial Matrix
1 0 0 0 0 1 0
0 0 0 1 0 0 0
0 0 0 0 0 0 0

#After operation
1 1 1 1 1 1 1
1 1 1 1 1 1 1
0 0 1 1 1 0 0
Asked By: Gopal Chitalia

||

Answers:

It looks like you want to do dilation. OpenCV might be your best tool

import cv2
dilatation_dst = cv2.dilate(src, np.ones((3,3)))

https://docs.opencv.org/3.4/db/df6/tutorial_erosion_dilatation.html

Answered By: Tom Nijhof

Given

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

You can do

from scipy.ndimage import shift

arr2 = arr | shift(arr, (0, 1), cval=0) | shift(arr, (0, -1), cval=0)
arr3 = arr2 | shift(arr2, (1, 0), cval=0), (-1, 0), cval=0)
Answered By: Steven Rumbalski

You can use scipy.signal.convolve2d.

import numpy as np
from scipy.signal import convolve2d
result = convolve2d(src, np.ones((3,3)), mode='same').astype(bool).astype(int)
print(result)

Or we can use scipy.ndimage.

from scipy import ndimage
result = ndimage.binary_dilation(src, np.ones((3,3))).astype(int)
print(result)

Output:

[[1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1]
 [0 0 1 1 1 0 0]]
Answered By: I'mahdi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.