Search code examples
dataframenumpyrasterpixel

Creating NxN matrix where each cell has the value of the nxn matrix it represents inside the large NxN matrix


Given NxN dimensions, I'm traying to create a functions that returns a list of values that represent cells from the NxN matrix. for example:

a_3x3 = [   # 3x3 pixel window
    [3,3,3],
    [3,1,3],
    [3,3,3]
    ]
a_3x3_lis = [3, 3, 3, 3, 1, 3, 3, 3, 3] # same window flattend

a_5x5 = [       # 5x5 pixel window
    [5,5,5,5,5],
    [5,3,3,3,5],
    [5,3,1,3,5],
    [5,3,3,3,5],
    [5,5,5,5,5]
    ]
a_5x5_lis = [5, 5, 5, 5, 5, 5, 3, 3, 3, 5, 5, 3, 1, 3, 5, 5, 3, 3, 3, 5, 5, 5, 5, 5, 5] # same window flattened

I've just created the lists manually so far but its no good for large matrixes

near_win_3x3 = [3, 3, 3, 3, 1, 3, 3, 3, 3]
near_win_5x5 = [5, 5, 5, 5, 5, 5, 3, 3, 3, 5, 5, 3, 1, 3, 5, 5, 3, 3, 3, 5, 5, 5, 5, 5, 5]
near_win_7x7 = [7, 7, 7, 7, 7, 7, 7, 7, 5, 5, 5, 5, 5, 7, 7, 5, 3, 3, 3, 5, 7, 7, 5, 3, 1, 3, 5, 7, 7, 5, 3, 3, 3, 5, 7, 7, 5, 5, 5, 5, 5, 7, 7, 7, 7, 7, 7, 7, 7,]

Solution

  • One way using numpy.minimum:

    def reversed_pyramid(n):
        a = np.arange(n)
        m = np.minimum(a, a[::-1])
        return n - np.minimum.outer(m, m) * 2
    

    Output:

    # reversed_pyramid(7)
    array([[7, 7, 7, 7, 7, 7, 7],
           [7, 5, 5, 5, 5, 5, 7],
           [7, 5, 3, 3, 3, 5, 7],
           [7, 5, 3, 1, 3, 5, 7],
           [7, 5, 3, 3, 3, 5, 7],
           [7, 5, 5, 5, 5, 5, 7],
           [7, 7, 7, 7, 7, 7, 7]])