I have a 100x100 grid of 1s and 0s, and I want to determine whether there are more than 4 0s within any given 3x3 on the 100x100 array. If less or equal this would return true, greater would return False. How can I do this?
CodePudding user response:
import numpy as np
# Dimensions of array
n, m, = 10, 10
# Length of sub-arrays to check
delta = 3
# Max amount of 0's before condition met
zeros = 4
# Generate random example array
a = np.random.randint(0,2,(n,m))
# Lists True or False for each sub array
[np.sum(a[i:i delta, j:j delta]) < (delta**2 - zeros) for i in range(0,n-delta) for j in range(0,m-delta)]
CodePudding user response:
You could just do a brute force search
import numpy as np
grid = np.random.randint(0, 5, (100, 100))
summ = 0
searched = 0
for ii in range(100 - delta):
for jj in range(100 - delta):
searched = 1
if np.where(grid[ii:ii delta, jj:jj delta] == 0)[0].size > 4:
print('zeros found in (%i,%i) through (%i,%i) ' % (ii, jj, ii delta, jj delta))
summ = 1
print('number of sets of zeros > 4: %i/%i' % (summ, searched))
CodePudding user response:
You could also do something like this
from scipy.signal import convolve2d
window_size = 3
kernel = np.ones((window_size, window_size))
test_array = np.zeros((100, 100))
test_array[33:35, 33] = 1
test_array[34, 33:36] = 1
output = convolve2d(test_array, kernel, mode='valid')
threshold = 4
hits = np.nonzero(output >= threshold)
Where the "hits" are the top-left corners of the windows.