簡體   English   中英

獲取給定中心點索引的2D陣列的子集

[英]Getting a subset of 2D array given indices of center point

給定一個2D數組和一個帶索引(x,y)的特定元素,如何獲得以該元素為中心的子集方形二維數組(nxn)?

只有當子集數組的大小完全在原始數組的范圍內時,我才能實現它。 如果特定元素靠近原始數組的邊緣或角落,我遇到了問題。 對於這種情況,子集數組必須具有原始數組之外的元素的nan值。

示例說明

這是我將如何做到這一點:

def fixed_size_subset(a, x, y, size):
    '''
    Gets a subset of 2D array given a x and y coordinates
    and an output size. If the slices exceed the bounds 
    of the input array, the non overlapping values
    are filled with NaNs
    ----
    a: np.array
        2D array from which to take a subset
    x, y: int. Coordinates of the center of the subset
    size: int. Size of the output array
    ----       
    Returns:
        np.array
        Subset of the input array
    '''
    o, r = np.divmod(size, 2)
    l = (x-(o+r-1)).clip(0)
    u = (y-(o+r-1)).clip(0)
    a_ = a[l: x+o+1, u:y+o+1]
    out = np.full((size, size), np.nan, dtype=a.dtype)
    out[:a_.shape[0], :a_.shape[1]] = a_
    return out

樣品運行:

# random 2D array
a = np.random.randint(1,5,(6,6))

array([[1, 3, 2, 2, 4, 1],
       [1, 3, 1, 3, 3, 2],
       [1, 1, 4, 4, 2, 4],
       [1, 2, 3, 4, 1, 1],
       [4, 1, 4, 2, 3, 4],
       [3, 3, 2, 3, 2, 1]])

fixed_size_subset(a, 3, 3, 5)

array([[3., 1., 3., 3., 2.],
       [1., 4., 4., 2., 4.],
       [2., 3., 4., 1., 1.],
       [1., 4., 2., 3., 4.],
       [3., 2., 3., 2., 1.]])

讓我們嘗試一些切片數組小於預期輸出大小的示例:

fixed_size_subset(a, 4, 1, 4)

array([[ 1.,  2.,  3.,  4.],
       [ 4.,  1.,  4.,  2.],
       [ 3.,  3.,  2.,  3.],
       [nan, nan, nan, nan]])

fixed_size_subset(a, 5, 5, 3)

array([[ 3.,  4., nan],
       [ 2.,  1., nan],
       [nan, nan, nan]])

以下也適用:

fixed_size_subset(a, -1, 0, 3)

array([[ 1.,  3., nan],
       [nan, nan, nan],
       [nan, nan, nan]])

用NaN填充數組,然后選擇相應移位的子陣列可以解決問題。 np.pad(arr, (2, 2), "constant", constant_values = np.NaN)

暫無
暫無

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

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