您可以拆分每个2x2 子数组,然后重新整形,使每个窗口块成为2D 数组中的一行。
从每一行中,使用boolean indexing 提取与f==1 位置对应的元素。
然后,查看每一行中所有提取的元素是否相同,给我们一个掩码。使用此掩码与f 相乘,得到整形后的最终二进制输出。
因此,假设 f 作为过滤器数组,A 作为数据数组,遵循这些步骤的矢量化实现将如下所示 -
# Setup size parameters
M = A.shape[0]
Mh = M/2
N = A.shape[1]/2
# Reshape input array to 4D such that the last two axes represent the
# windowed block at each iteration of the intended operation
A4D = A.reshape(-1,2,N,2).swapaxes(1,2)
# Determine the binary array whether all elements mapped against 1
# in the filter array are the same elements or not
S = (np.diff(A4D.reshape(-1,4)[:,f.ravel()==1],1)==0).all(1)
# Finally multiply the binary array with f to get desired binary output
out = (S.reshape(Mh,N)[:,None,:,None]*f[:,None,:]).reshape(M,-1)
示例运行 -
1) 输入:
In [58]: A
Out[58]:
array([[1, 1, 1, 1, 2, 1],
[1, 1, 3, 1, 2, 2],
[1, 3, 3, 3, 2, 3],
[3, 3, 3, 3, 3, 1]])
In [59]: f
Out[59]:
array([[0, 1],
[1, 1]])
2) 中间输出:
In [60]: A4D
Out[60]:
array([[[[1, 1],
[1, 1]],
[[1, 1],
[3, 1]],
[[2, 1],
[2, 2]]],
[[[1, 3],
[3, 3]],
[[3, 3],
[3, 3]],
[[2, 3],
[3, 1]]]])
In [61]: S
Out[61]: array([ True, False, False, True, True, False], dtype=bool)
3) 最终输出:
In [62]: out
Out[62]:
array([[0, 1, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0],
[1, 1, 1, 1, 0, 0]])