Variable Area Threshold For Identifying Objects - Python
I have an array which contains information of the size and location a series of shapes: where the array is zero, there are no shapes, where the array is not zero there is a shape.
Solution 1:
You can use scipy.ndimage.label
to find the connected non-zero regions in your array, then use scipy.ndimage.sum
to find the area of each region:
from scipy import ndimage
labels, nshapes = ndimage.label(a)
areas = ndimage.sum(a, labels=labels, index=range(1, nshapes))
idx = np.argmax(areas)
biggest_shape = labels == (idx + 1)
In your example there happen to be two 'shapes' with the same area:
from matplotlib import pyplot as plt
fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
ax1.imshow(a, cmap=plt.cm.jet)
ax2.imshow(labels, cmap=plt.cm.jet)
ax3.imshow(biggest_shape, cmap=plt.cm.jet)
Update
The structure
argument passed to scipy.ndimage.label
determines which neighbouring elements are considered to be 'connected' (see the docs linked above). If you want diagonally adjacent elements to be considered as connected, you can pass a 3x3 array of ones:
labels, nshapes = ndimage.label(a, structure=np.ones((3, 3)))
Post a Comment for "Variable Area Threshold For Identifying Objects - Python"