我有一個 1 和 0 的 100x100 網格,我想確定 100x100 陣列上的任何給定 3x3 內是否有超過 4 個 0。如果小于或等于這將回傳真,更大將回傳假。我怎樣才能做到這一點?
uj5u.com熱心網友回復:
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)]
uj5u.com熱心網友回復:
你可以做一個蠻力搜索
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))
uj5u.com熱心網友回復:
你也可以做這樣的事情
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)
“命中”是視窗的左上角。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/433822.html
上一篇:Numpy在哪里使用值串列
