Calculate the perimeter of a numpy array

I want to calculate the perimeter of a given structure of a numpy array. With perimeter, I mean the exact perimeter of the structure in the numpy array. The structure may include holes.

My current aproach looks something like this:

import numpy a = numpy.zeros((6,6), dtype=numpy.int) a[1:5, 1:5] = 1;a[3,3] = 0 # Way 1 s = ndimage.generate_binary_structure(2,1) c = ndimage.binary_dilation(a,s).astype(a.dtype) b = c - a numpy.sum(b) # The result, however the hole is calculated as 1, although there are 4 edges # Way 2 b = ndimage.distance_transform_cdt(a == 0,metric='taxicab') == 1 b = b.astype(int) numpy.sum(b) # same as above 

enter image description here

As you can see, it displays all neighboring cells, but their sum is not equal to the perimeter of the patch. The hole in the example array is calculated as 1, although it correctly has 4 edges. There are similar problems with large holes of various shapes.

I asked similar questions in the past, but all the solutions provided that were somehow not resolved in the correct output values โ€‹โ€‹at the end. Does anyone have an idea how to do this? No other packages besides numpy, scipy and base packages, please.

+6
source share
2 answers

Do you mean, in the image, the total number of edges of length-1 that highlight the blue colors from the red plates? In the figure above, this number will be 28. In the example that you give in the code (which is slightly different without 4 angles different from the rest of the boundary plates), this will be 20.

If this is what you want to calculate, you can do something like:

numpy.sum(a[:,1:] != a[:,:-1]) + numpy.sum(a[1:,:] != a[:-1,:])

+4
source

Count the number of edges inside and around (takes a binary image):

 n_interior = abs(diff(a, axis=0)).sum() + abs(diff(a, axis=1)).sum() n_boundary = a[0,:].sum() + a[:,0].sum() + a[-1,:].sum() + a[:,-1].sum() perimeter = n_interior + n_boundary 

You can leave n_boundary if the image is correctly filled with zeros.

+5
source

All Articles