package yi.iu.processor.morph;

public class SmallRegionRemover {
  /**
   * remove the small regions.  (if the region size < min_size).  those pixels
   * in the small regions will be labeled as 0.  0 is treated as background
   * @param labels the labels.
   * @param w
   * @param h
   * @param min_size
   * @return the mapping from old label to new label
   */
  public static int[] removeSmallRegions(int[] labels, int w, int h, int min_size) {
    int max_label = yi.stat.StatUtil.maximum(labels);
    int[] counts = new int[max_label + 1];
    for (int i=0; i<labels.length; i++) counts[labels[i]]++;
    counts[0] = 0;
    int new_label = 1;
    for (int i=1; i<counts.length; i++) {
      if (counts[i]<min_size) counts[i] = 0;
      else counts[i] = new_label++;
    }
    for (int i=0; i<labels.length; i++) labels[i] = counts[labels[i]];
    return counts;
  }
}