Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading