gpt4 book ai didi

python - 在 2D 或 3D 数组中查找相邻数字的快速方法

转载 作者:太空宇宙 更新时间:2023-11-04 02:35:06 26 4
gpt4 key购买 nike

我有以下二维数组

regions = array([[3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4],
[3, 3, 3, 3, 8, 8, 8, 8, 8, 4, 4, 4, 4],
[3, 3, 3, 3, 8, 8, 8, 8, 8, 4, 4, 4, 4],
[3, 3, 3, 3, 8, 8, 8, 8, 8, 4, 4, 4, 4],
[3, 6, 6, 6, 8, 8, 8, 8, 8, 7, 7, 7, 4],
[3, 6, 6, 6, 8, 8, 8, 8, 8, 7, 7, 7, 4],
[3, 6, 6, 6, 6, 8, 8, 8, 7, 7, 7, 7, 4],
[3, 6, 6, 6, 6, 2, 2, 2, 7, 7, 7, 7, 4],
[5, 6, 6, 6, 6, 2, 2, 2, 7, 7, 7, 7, 1],
[5, 6, 6, 6, 6, 2, 2, 2, 7, 7, 7, 7, 1],
[5, 6, 6, 6, 6, 2, 2, 2, 7, 7, 7, 7, 1],
[5, 5, 5, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1],
[5, 5, 5, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1]])

我想为所有单个号码查找相邻号码。例如 34,5,6,8 的否定。目前,我正在按照下面提到的代码使用 for 循环 进行此练习。

numbers = scipy.unique(regions)
for i in numbers:
index = i-1
slices = scipy.ndimage.find_objects(regions)
sub_im = regions[slices[index]]
im = sub_im == i
neighbors = scipy.ndimage.binary_dilation(input=im, structure=disk(1))
neighbors = neighbors*sub_im
neighbors_list = scipy.unique(neighbors)[1:] - 1
print (neighbors_list)

问题是我不想使用 for 循环,因为我的区域数组有数百万个。有没有不用for循环的快速解决方法?

最佳答案

您可以使用 numpynp.roll()np.where()np.独特的()。这个想法是将每个条目附加到它的四个邻居,然后从这五个列表中提取唯一成员(该条目及其四个邻居)。这是一个应该澄清的实现:

# make a 3d array with the matrix entry and its four neighbors
neighbor_array = np.array([regions,
np.roll(regions,+1,axis=0),
np.roll(regions,-1,axis=0),
np.roll(regions,+1,axis=1),
np.roll(regions,-1,axis=1),
])
# if you want neighbors to include wraparounds, use above; if not, prune
neighbor_array_pruned = neighbor_array[:,1:-1,1:-1]
# reshape to a 2d array entries x neighbors
neighbor_list = np.reshape(neighbor_array_pruned,[5,-1]).T
# get uniques into a dictionary
neighbor_dict = {}
for num in np.unique(regions):
neighbor_dict[num] = np.unique(neighbor_list[np.where(neighbor_list[:,0]==num)])

这会产生 neighbor_dict:

{1: array([1, 2, 7]),
2: array([1, 2, 5, 6, 7, 8]),
3: array([3, 6, 8]),
4: array([4, 7, 8]),
5: array([2, 5, 6]),
6: array([2, 3, 5, 6, 8]),
7: array([1, 2, 4, 7, 8]),
8: array([2, 3, 4, 6, 7, 8])}

注意我修剪了边缘;如果你想包括环绕式邻居或做一些更细微的事情,你可以详细说明修剪线。

关于python - 在 2D 或 3D 数组中查找相邻数字的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48104401/

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