How to count the adjacent values with values of 1 in a geotiff array

Question:

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]])
Asked By: emax

||

Answers:

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]])
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.