def filter_isolated_cells(array, struct):
    """ Return array with completely isolated single cells removed
    :param array: Array with completely isolated single cells
    :param struct: Structure array for generating unique regions
    :return: Array with minimum region size > 1
    """
filtered_array = np.copy(array)
id_regions, num_ids = ndimage.label(filtered_array, structure=struct)
id_sizes = np.array(ndimage.sum(array, id_regions, list(range(num_ids + 1))))
area_mask = id_sizes == 1
filtered_array[area_mask[id_regions]] = 0
return filtered_array
filtered_array = filter_isolated_cells(square, struct=np.ones((3, 3)))
plt.imshow(filtered_array, cmap=plt.cm.gray, interpolation='nearest')
Removing completely isolated cells from Python array?