Probhakar Sarkar
Probhakar Sarkar

Reputation: 189

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

I have a numpy array like

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 I want to find the index of the island with water surrounding it. For example in the arr1 water starts at index 4 and island index 6 to 8 is surrounded by two water strip. So the answer for arr1 is

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

but in the second case there is not land surrounded by water, so no output.

Upvotes: 1

Views: 893

Answers (1)

JohanC
JohanC

Reputation: 80279

The following approach pads the array with a one at the start and the end. And calculates the differences: these are -1 when going from water to land, 1 when going from land to water, and 0 everywhere else.

The following code constructs a series of test cases and visualizes the function. It can serve as a test bed for different definitions of the desired outcome.

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

Upvotes: 1

Related Questions