Home > Net >  Python: how to count the adjacent values with values of 1 in a geotiff array?
Python: how to count the adjacent values with values of 1 in a geotiff array?

Time:09-29

Let's that we have geotiff of 0 and 1.

import rasterio
src = rasterio.open('myData.tif')
data = src.read(1)
data
array([[0, 1, 1, 0],
       [1, 0, 0, 1],
       [0, 0, 1, 0],
       [1, 0, 1, 1]])

I would like to have for each pixel 1 the sum of all adjacent pixels forming a cluster of ones and to have something like the following:

array([[0, 2, 2, 0],
       [1, 0, 0, 1],
       [0, 0, 3, 0],
       [1, 0, 3, 3]])

CodePudding user response:

You can use scipy.ndimage.label:

from scipy.ndimage import label

out = np.zeros_like(data)

labels, N = label(data)
for i in range(N):
    mask = labels==i 1
    out[mask] = mask.sum()

output:

array([[0, 2, 2, 0],
       [1, 0, 0, 1],
       [0, 0, 3, 0],
       [1, 0, 3, 3]])
  • Related