如何遍历数组的3x3窗口?

时间:2018-01-21 14:32:57

标签: python-3.x numpy sliding-window

我使用下面的代码在3x3窗口中打印大小(189,101)的数组。另外我想提出一个适用于每个大小为3x3的窗口的条件。如何以不同的方式遍历每个(3,3)数组? 这是在(3,3)窗口中生成数组的修改代码。

from itertools import islice
 np.set_printoptions(threshold=np.inf)
 img=gdal.Open(path)
  arr = np.array([[1,2,3,4],
           [2,3,4,5],
           [3,4,5,6],
           [4,5,6,7]])

 def rolling_window(a, shape):
s = (a.shape[0] - shape[0] + 1,) + (a.shape[1] - shape[1] + 1,) + shape
strides = a.strides + a.strides

return np.lib.stride_tricks.as_strided(a, shape=s, strides=strides)

 def window2(arr, shape=(3,3)):
     r_extra = np.floor(shape[0] / 2).astype(int)
     c_extra = np.floor(shape[1] / 2).astype(int)
       out = np.empty((arr.shape[0] + 2 * r_extra, arr.shape[1] + 2 * c_extra))
#print(out)
out[:] = np.nan
out[r_extra:-r_extra, c_extra:-c_extra] = arr
view = rolling_window(out, shape)
#print(view)
for i in range(len(view)):
    for j in range(len(view[i])):
        i=0
        j=range(0,4)
        i+=1
        for x in view[i,j]:
            np.apply_along_axis(np.any, 0, x == 4)
            print(x)
        #print(view[i,j])
#print(len(view[i,j]))

 window2(arr, (3,3))

输出:

   [[ nan  nan  nan  nan  nan]
   [  1.   1.   1.   1.   1.]
   [  1.   1.   1.   1.   1.]
   [  1.   1.   1.   1.   1.]
   [  1.   1.   1.   1.   1.]]


  [[ nan  nan  nan  nan  nan]
  [  1.   1.   1.   1.   1.]
  [  1.   1.   1.   1.   1.]
  [  1.   1.   1.   1.   1.]
  [  1.   1.   1.   1.   1.]]


  [[ nan  nan  nan  nan  nan]
  [  1.   1.   1.   1.   1.]
  [  1.   1.   1.   1.   1.]
  [  1.   1.   1.   1.   1.]
  [  1.   1.   1.   1.   1.]]

我需要的是在每个窗口尺寸3x3中打印或突出显示不等于1的值。可以在这做什么?

1 个答案:

答案 0 :(得分:0)

我不是100%确定你要做什么,但如果x是你的结果视图,你可以做类似的事情

np.apply_along_axis(np.any, 0, x == 1)

np.any(x == 1, axis=0)