gpt4 book ai didi

python - 给定中心点索引获取二维数组的子集

转载 作者:行者123 更新时间:2023-11-28 17:58:20 24 4
gpt4 key购买 nike

给定一个二维数组和一个索引为 (x,y) 的特定元素,如何获得以该元素为中心的二维正方形子集 (n x n)?

只有当子集数组的大小完全在原始数组的范围内时,我才能实现它。如果特定元素靠近原始数组的边缘或角落,我会遇到问题。对于这种情况,子集数组对于原始数组之外的元素必须具有 nan 值。

Example illustration

最佳答案

这是我将如何做到这一点:

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

关于python - 给定中心点索引获取二维数组的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56983818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com