识别二维numpy数组中的连续区域 [英] Identify contiguous regions in 2D numpy array
问题描述
我有一个很大的numpy
数组,已对其应用过滤器.我想确定此蒙版数组中的连续区域.在这里,我定义了一个连续区域,如果对于任何索引(x1,y1)
到任何其他索引(x2,y2)
,如果在轴上沿着相等整数步长的True
值路径都属于同一区域,则它们属于同一区域(对角线是有效步骤.
I have a large numpy
array that I've applied a filter over. I'd like to identify the contiguous regions in this masked array. Here I'm defining a region to be contiguous if, for any index (x1,y1)
to any other index (x2,y2)
, they belong to the same region if there is a path of True
values along equal integer steps along the axes (diagonals are valid steps).
那可能不像一张简单的图片那么清晰.给定面具:
That may not be as clear as a simple picture. Given the mask:
0010000
0100000
0110000
0000011
1000010
应该确定三个区域,以使输出类似于
There should be three regions identified such that the output is something like
[ [[0,2],[1,1],[2,1],[2,2]], [[3,5],[3,6],[4,5]], [[4,0]] ]
我想使用numpy
中内置的内容,而不必借助自己的 Flood Fill 算法.在文档中进行的少量研究仅显示了我要问的一维版本.
I'd like to use something built into numpy
, without resorting to writing my own Flood Fill algorithm. A little bit of research in the docs only turned up a 1D version of what I'm asking.
推荐答案
You're looking for scipy.ndimage.label
, more info here. label
returns an array the same shape as the input where each "unique feature has a unique value", so if you want the indices of the features you can do something like:
labels, numL = label(array)
label_indices = [(labels == i).nonzero() for i in xrange(1, numL+1)]
这篇关于识别二维numpy数组中的连续区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!