简体   繁体   中英

Summing partly overlapping matrices

I have 3x3 matrices which can have different positions on a 5x5 matrix, so that those 3x3 matrices overlap partially or fully. Finally I want to sum those matrices together, to get a final 5x5 matrix. Here is a toy example:

import numpy as np
# I have 3 matrices which partly overlap, defined by their center index
mat1 = np.arange(9).reshape(3,3)
mat2 = np.arange(9).reshape(3,3)+2
mat3 = np.arange(9).reshape(3,3)*2.+1
# I construct 3 empty 5x5 matrices and store my 3x3 matrices there
A = np.zeros((3,5,5))
A[0,0:3,0:3]=mat1
A[1,2:5,2:5]=mat2
A[2,1:4,0:3]=mat3
# Finally I sum the matrices
output = A.sum(0)

In my opinion I waste a lot of memory space and time by constructing the matrix A, if the number of the 3x3 matrices becomes large. I am looking for another way, to add those partly overlapping 3x3 matrices together. Note, that the positions (indices) of the 3x3 matrices are known.

You can avoid the temporary (3,5,5) using add.at and as_strided :

>>> out = np.zeros((5, 5))
>>> oas = np.lib.stride_tricks.as_strided(out, (3,3,3,3), 2*out.strides)
>>> at = [0,2,1], [0,2,0]
>>> np.add.at(oas, at, (mat1, mat2, mat3))
>>> out
array([[ 0.,  1.,  2.,  0.,  0.],
       [ 4.,  7., 10.,  0.,  0.],
       [13., 16., 21.,  3.,  4.],
       [13., 15., 22.,  6.,  7.],
       [ 0.,  0.,  8.,  9., 10.]])

If, for each matrice, you have a tuple (offrow, offcol) , you could create your output directly by iterating over all your matrices:

output = np.zeros((5,5))
matrices = [mat1, mat2, mat3]
offsets = [(0, 0), (2, 2), (1, 0)]
for m, o in zip(matrices, offsets):
    for i in range(3):
       for j in range(3):
           output[i + o[0], j + o[1]] += m[i,j]

This avoids to create temporary 5x5 matrices, created from the 3x3 matrices. This will consume less memory but it might not be faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM