[Python] Forming a frame of zeros around a matrix in python

Discussão em 'Python' iniciado por Stack, Agosto 12, 2025.

  1. Stack

    Stack Membro Participativo

    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))]

    Continue reading...

Compartilhe esta Página