簡體   English   中英

創建 NxN 矩陣,其中每個單元格都具有它在大 NxN 矩陣中表示的 nxn 矩陣的值

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

給定 NxN 維度,我打算創建一個函數,該函數返回代表 NxN 矩陣中的單元格的值列表。 例如:

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

到目前為止,我只是手動創建了列表,但它對大型矩陣沒有好處

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

數組中的值是他們到中心的曼哈頓距離的 function。 具體來說,它是: f(d) = 1 + 2 * d

def make_window(N):
    return 1 + 2 * abs(np.stack(np.mgrid[:N, :N]) - (N - 1) // 2).max(0)

N=7產生:

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

一種使用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]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM