我有一个二维的numpy数组,如下所示:
start = np.array([
[1,1,0,1],
[1,0,0,1],
[0,1,0,0]
])
我需要获得相同的矩阵,但是通过沿任意方向移动一步但只能沿 1
结果,我应该得到以下信息:
finish = np.array([
[4,4,0,2],
[4,0,0,2],
[0,4,0,0]
])
在我看来,这是一个众所周知的问题,但是我什至没有想出如何在搜索中表述它,因为我所寻找的一切都有些不同。最好的方法是什么?
您可以将scipy.ndimage
标签功能与自定义结构数组一起使用s
:
import numpy as np
from scipy.ndimage import label
start = np.asarray([ [1,1,0,1],
[1,0,0,1],
[0,1,0,0] ])
#structure array what to consider as "neighbors"
s = [[1,1,1],
[1,1,1],
[1,1,1]]
#label blobs in array
labeledarr,_ = label(start, structure=s)
#retrieve blobs and the number of elements within each blobs
blobnr, blobval = np.unique(labeledarr.ravel(), return_counts=True)
#substitute blob label with the number of elements
finish = np.zeros_like(labeledarr)
for k, v in zip(blobnr[1:], blobval[1:]):
finish[labeledarr==k] = v
print(finish)
输出:
[[4 4 0 2]
[4 0 0 2]
[0 4 0 0]]
我相信可以用速度来优化用标签编号替换标签编号的最后一步。
@ mad-physicist正确地提到,最初使用的labeledarr.flat
应替换为labeledarr.ravel()
。在此解释其原因。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句