繁体   English   中英

如何在 numpy 数组中找到被零包围的区域?

[英]How to find regions of ones surrounded by zeros in a numpy array?

我有一个 numpy 数组,比如

arr1 = np.array([1,1,1,1,0,0,1,1,1,0,0,0,1,1])
arr2 = np.array([1,1,1,1,0,0,0,1,1,1,1,1,1,1])

0 -water 1 -land 我想找到周围有水的岛屿的索引。 例如,在arr1中,水从索引4开始,岛屿索引68被两个水带包围。 所以arr1的答案是

[4,5,6,7,8,9,10,11]

但在第二种情况下,没有被水包围的土地,所以没有 output。

以下方法在数组的开头和结尾填充一个。 并计算差异:从水到陆地时为-1 ,从陆地到水时为1 ,其他地方为0

下面的代码构造了一系列的测试用例,将function可视化。 它可以作为对期望结果的不同定义的测试平台。

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np

def find_islands(arr):
    d = np.diff(np.pad(arr, pad_width=(1, 1), constant_values=1))
    land_starts, = np.nonzero(d == 1)
    land_ends, = np.nonzero(d == -1)
    if len(land_starts) > 1 and len(land_ends) > 1:
        return np.arange(arr.size)[land_ends[0]: land_starts[-1]]
    else:
        return None

def show_array(arr, y, color0='skyblue', color1='limegreen'):
    if arr is not None:
        plt.imshow(arr[np.newaxis, :], cmap=ListedColormap([color0, color1]), vmin=0, vmax=1,
                   extent=[0, arr.size, y, y + 2])

def mark_array(arr, y, color0='none', color1='crimson'):
    if arr is not None:
        pix = np.zeros(arr[-1] + 1)
        pix[arr] = 1
        show_array(pix, y, color0, color1)

tests = [np.array([1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1]),
         np.array([1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]),
         np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]),
         np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
         np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]),
         np.array([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1]),
         np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
         np.array([1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0]),
         np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0]),
         np.array([0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0]),
         np.array([1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0])]
for arr, y in zip(tests, range(0, 1000, 5)):
    show_array(arr, y + 2)
    result = find_islands(arr)
    mark_array(result, y)

ax = plt.gca()
ax.relim()
ax.autoscale()
ax.axis('auto')
plt.show()

测试图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM