pythonnumpymultidimensional-arrayaverage

Python: Average Values in 2D-Array


I want to generate a twodimensional array in Python and I would like to iterate through each element and take an average. An element i should be averaged using the 8 surrounding array elements (including element i).

I generated the twodimensional array with a frame of zeros using Forming a frame of zeros around a matrix in python.

A = np.array([[1,2,3],[4,5,6],[7,8,9]])
x,y = A.shape
n = 1    
B = np.zeros((x+2*n,y+2*n),dtype=int)
B[n:x+n, n:y+n] = A
print(B)

What is the easiest way to take the average?


Solution

  • What you want is a 2D convolution, use scipy.signal.convolve2d with numpy.ones to get the sum:

    from scipy.signal import convolve2d
    
    out = convolve2d(B, np.ones((3, 3), dtype='int'), mode='same')
    

    Output:

    array([[ 1,  3,  6,  5,  3],
           [ 5, 12, 21, 16,  9],
           [12, 27, 45, 33, 18],
           [11, 24, 39, 28, 15],
           [ 7, 15, 24, 17,  9]])
    

    If you want the small matrix, no need to pad with zeros:

    convolve2d(A, np.ones((3, 3), dtype='int'), mode='same')
    
    # array([[12, 21, 16],
    #        [27, 45, 33],
    #        [24, 39, 28]])
    

    For the average, repeat the same operation with an array od ones and divide:

    kernel = np.ones((3, 3), dtype='int')
    out = (convolve2d(A, kernel, mode='same')
          /convolve2d(np.ones_like(A), kernel, mode='same')
          )
    

    output:

    array([[3. , 3.5, 4. ],
           [4.5, 5. , 5.5],
           [6. , 6.5, 7. ]])