'Clustering and deleting small cluster sizes using ndi.label

I am writing a code to cluster 2D image field of cloud mask(1s and 0s). I use ndi.label to detect all areas with marker =1 that are connected and give them a unique integer value. I use np.unique to calculate total number of clusters (2977) and size of each cluster(np.unique(return_counts). Now I want to delete the clusters that are less than 0.1* maximum cluster size. So first I have to find these clusters and then change their value in the field again to 0, but I dont know whats the best way to do that. Is it possible to do that with np.unique (return_inverse)?

    dumdat = dat2D_mask[:,:]

    labeled_obj,n_obj  = ndi.label(dumdat)

    labels, cluster_n,indices = np.unique(labeled_obj.ravel(),return_counts=True,return_inverse=True)   

    nclust = len(labels)
    if nclust>1:

      cluster_a = cluster_n * dx * dy
      cluster_l = np.sqrt( cluster_a )
      l_min_0 = np.nanmin(cluster_l[1:])   
      l_max_0 = np.nanmax(cluster_l[1:])


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source