填充NumPy数组numpy.ndarray e。为元素分配新值并更改相同值的相邻元素

问题描述:

另一篇类似的帖子,名为 Flood Fill in Python 这是一个关于洪水填充的非常普遍的问题,答案仅包含一个广泛的伪代码示例。我正在寻找使用 numpy scipy 的显式解决方案。

Another, similar post called Flood Fill in Python is a very general question on flood fill and the answer only contains a broad pseudo code example. I'm look for an explicit solution with numpy or scipy.

让我们以这个数组为例:

Let's take this array for example:

a = np.array([
    [0, 1, 1, 1, 1, 0],
    [0, 0, 1, 2, 1, 1],
    [0, 1, 1, 1, 1, 0]
])

用于选择元素 0、0 和值 3 的洪水填充,我希望:

For selecting element 0, 0 and flood fill with value 3, I'd expect:

[
    [3, 1, 1, 1, 1, 0],
    [3, 3, 1, 2, 1, 1],
    [3, 1, 1, 1, 1, 0]
]

用于选择元素 0、1 和值 3 的洪水填充,我希望:

For selecting element 0, 1 and flood fill with value 3, I'd expect:

[
    [0, 3, 3, 3, 3, 0],
    [0, 0, 3, 2, 3, 3],
    [0, 3, 3, 3, 3, 0]
]

对于选择元素 0、5 和值 3 的洪水填充,我期望:

For selecting element 0, 5 and flood fill with value 3, I'd expect:

[
    [0, 1, 1, 1, 1, 3],
    [0, 0, 1, 2, 1, 1],
    [0, 1, 1, 1, 1, 0]
]

这应该是一个相当基本的操作,不是吗?我忽略了哪个 numpy scipy 方法?

This should be a fairly basic operation, no? Which numpy or scipy method am I overlooking?

方法#1

模块 scikit-image 提供了内置功能,可对 skimage.segmentation.flood_fill -

Module scikit-image offers the built-in to do the same with skimage.segmentation.flood_fill -

from skimage.morphology import flood_fill

flood_fill(image, (x, y), newval)

示例运行-

In [17]: a
Out[17]: 
array([[0, 1, 1, 1, 1, 0],
       [0, 0, 1, 2, 1, 1],
       [0, 1, 1, 1, 1, 0]])

In [18]: flood_fill(a, (0, 0), 3)
Out[18]: 
array([[3, 1, 1, 1, 1, 0],
       [3, 3, 1, 2, 1, 1],
       [3, 1, 1, 1, 1, 0]])

In [19]: flood_fill(a, (0, 1), 3)
Out[19]: 
array([[0, 3, 3, 3, 3, 0],
       [0, 0, 3, 2, 3, 3],
       [0, 3, 3, 3, 3, 0]])

In [20]: flood_fill(a, (0, 5), 3)
Out[20]: 
array([[0, 1, 1, 1, 1, 3],
       [0, 0, 1, 2, 1, 1],
       [0, 1, 1, 1, 1, 0]])

方法2

我们可以使用 skimage.measure.label 和一些 array-masking -

from skimage.measure import label

def floodfill_by_xy(a,xy,newval):
    x,y = xy
    l = label(a==a[x,y])
    a[l==l[x,y]] = newval
    return a

使用基于SciPy的标签函数- scipy.ndimage.measurements.label ,大多数情况下都相同-

To make use of SciPy based label function - scipy.ndimage.measurements.label, it would mostly be the same -

from scipy.ndimage.measurements import label

def floodfill_by_xy_scipy(a,xy,newval):
    x,y = xy
    l = label(a==a[x,y])[0]
    a[l==l[x,y]] = newval
    return a

注意:这些将用作原位编辑。

Note : These would work as in-situ edits.