问题
I'm currently having the following issue, given an array let's say for simplicity a 4 x 4 array (I'm actually working with 512 x 512 )
X = np.array([[3, 5, 2, 4],
[7, 6, 8, 8],
[1, 6, 7, 7],
[2, 1, 3, 4]])
I would like to loop/slide around the array in a way that I can save new arrays in the form
np.array([3,5],[7,6]), np.array([2,4], [8,8]), np.array([1,6],[2,1]), np.array ([7,7],[1,4])
and so on (Ideally that I could choose the step and the size of my "sliding" window). Also I would like to select these arrays according to some conditions , see below.
For the moment I managed to do almost everything by slicing (see code) my matrix. This gives the correct slicing with the step which I want, then by using the itertools
module I can loop over all my list of lists, count the elements smaller than a certain value and save them.
What I cannot do is to link the indices between all these new lists together to the main matrix.
For this reason, I was thinking to move everything to numpy
arrays which should be (in my understanding) much more efficient in terms of computing and I guess should solve my issue of indices. Now the only problem is that I don't know to solve this problem for an arbitrary n x n
matrix.
X = np.array([[3, 5, 2, 4],
[7, 6, 8, 8],
[1, 6, 7, 7],
[2, 1, 3, 4]])
width = len(m[0])
height = len(m)
height = 2 # size of the matrix sliding
width = 2
for i in range(0, height - slice_y + 1,2):
for j in range(0, width - slice_x + 1,2):
Appended.append(
[
[m[a][b] for b in range(j, j + slice_x)]
for a in range(i, i + slice_y)
]
)
Ideally what I would like is for a general matrix N x N but for the moment also only like in the example to get the output as a form of arrays like:
np.array([3,5],[7,6]) . np.array ([2,4], [8,8]) , np.array ([1,6],[2,1]), np.array ([7,7],[1,4])
And let's say once found that e.g the array np.array([2,4], [8,8])
has two elements bigger than 7
and the sum is more than 20
to save the coordinates of this array with respect of my initial matrix. So saving the indices couples X[0][2]
, X[0][3]
, X[1][2]
, X[1][3]
or at least the first X[0][2]
so by knowing the step of my "window" I can access my subarrays by indexing my main matrix.
回答1:
You can apparently slice numpy arrays directly
X = np.array([[3, 5, 2, 4],
[7, 6, 8, 8],
[1, 6, 7, 7],
[2, 1, 3, 4]])[0:2,0:2]
I would in your case generate a list of the indices of the edges of the submatrix you're going to use. Then use that to generate the list of submatricies then use that to generate a list of true or false values based on the submatricies. Then you can use that list of true/false values to prune your initial list of indicies. You could also do this without storing the submatricies at all.
indicies= [((i,i+s_width),(j,j+s_height)) for i in range(0,width-s_width) for j in range(0,height-s_height)]
来源:https://stackoverflow.com/questions/55778969/looping-through-n-x-n-matrix-with-a-smaller-matrix-of-certain-size-with-numpy-ar