如何在numpy数组中查找由零包围的1区域?

2024-10-04 09:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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-水 1-土地 我想找到岛屿的索引,周围有水。 例如,在arr1中,水从指数4开始,岛屿指数68被两个水带包围。所以arr1的答案是

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

但在第二种情况下,没有被水包围的土地,因此没有产出


Tags: 答案numpynp情况数组指数array土地
1条回答
网友
1楼 · 发布于 2024-10-04 09:22:44

以下方法在阵列的开始和结束处填充一个。并计算差异:从水到陆地的差异为-1,从陆地到水的差异为1,其他地方的差异为0

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

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()

test plot

相关问题 更多 >