Skip to content Skip to sidebar Skip to footer

Python - Efficient Way To Find The Largest Area Of A Specific Value In A 2d Numpy Array

I have a 2D numpy array where some values are zero, and some are not. I'm trying to find an efficient way to find the biggest clump of zeros in the array (by returning the number o

Solution 1:

You're almost there, you just need to combine ndimage.label with numpy.bincount:

import numpy as np
from scipy import ndimage

array = np.random.randint(0, 3, size=(200, 200))

label, num_label = ndimage.label(array == 0)
size = np.bincount(label.ravel())
biggest_label = size[1:].argmax() + 1
clump_mask = label == biggest_label

Once you have clump_mask you can compute the centroid or use some other method to get the center.

Post a Comment for "Python - Efficient Way To Find The Largest Area Of A Specific Value In A 2d Numpy Array"