Find number of islands and affected area in an image

Viewed 68

I have the following problem that I wanted to solve using opencv or scikit-image.

Suppose I have a "map" in the following form: 1 is ground 0 is water

map = np.array([
  [ 0., 0., 0., 0., 0., 0.],
  [ 0., 0., 0., 0., 0., 0.],
  [ 0., 1., 1., 1., 0., 0.],
  [ 0., 0., 1., 0., 1., 0.],
  [ 0., 0., 0., 0., 1., 0.],
  [ 0., 0., 0., 0., 0., 0.]])
  1. How many islands in the map? considering 4 neighbors. In this example there is 2
  2. Given an (i,j) position, return the number of ground neighbors. example: (2,2) -> 4
1 Answers

Solving question no. 1 with Scikit-Image: The measure module will be your friend. Please checkout the documentation for it.

import numpy as np
from skimage import measure
import matplotlib.pyplot as plt

img = np.array([ [ 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0.],
[ 0., 1., 1., 1., 0., 0.],
[ 0., 0., 1., 0., 1., 0.],
[ 0., 0., 0., 0., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])

imglabeled,island_count = measure.label(img,background=0,return_num=True,connectivity=1)

plt.imshow(imglabeled)

labeled image

Related