Search code examples
pythonmatrixpaddingzero-paddingzero-pad

Forming a frame of zeros around a matrix in python


I am trying to pad a matrix with zeros, but am not really sure how to do it. Basically I need to surround a matrix with an n amount of zeros. The input matrix is huge (it represents an image)

Example:

Input:
1 2 3 4
5 6 7 8
4 3 2 1

n = 2

Output:
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 1 2 3 4 0 0
0 0 5 6 7 8 0 0
0 0 4 3 2 1 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0

The problem is that I get "k" is not accessed and "l" is not accessed.

Code:

import numpy as np

n = 2

matrix = [[1, 2, 3, 4],
          [5, 6, 7, 8],
          [4, 3, 2, 1]]
modified_matrix = np.zeros(shape=((len(matrix) + n), (len(matrix[0]) + n)), dtype=int)

k = n
l = n
modified_matrix = [[l] for l in range(len(matrix[k])] for k in range(len(matrix))]

Solution

  • You can use NumPy's slice notation.

    import numpy as np
    
    #input matrix
    A = np.array([[1,2,3,4],
                  [3,4,5,6]])
    
    #get matrix shape
    x,y=A.shape
    
    #set amount of zeros
    n=2    
    
    #create zero's matrix
    B=np.zeros((x+2*n,y+2*n),dtype=int)
    
    # insert & slice
    B[n:x+n, n:y+n] = A
    
    #show result
    for row in B:
        print(row)  
    

    Output:

    [0 0 0 0 0 0 0 0]
    [0 0 0 0 0 0 0 0]
    [0 0 1 2 3 4 0 0]
    [0 0 3 4 5 6 0 0]
    [0 0 0 0 0 0 0 0]
    [0 0 0 0 0 0 0 0]