package yi.iu.processor.color.reg;

import yi.util.label.Label;
import yi.iu.processor.color.ColorUtil;

public class ColorRegionUtil {
  /**
   * Calculate mean colors for regions
   *
   * @param rgb
   * @param labels
   * @param minValidLabel invalid labels will be considered as background.  Eg
   *                      if background is labeled as zero, it should be set
   *                      as 1.
   * @param bgColor background color
   * @return mean colors in RGB
   */
  public static int[] getMeanColors(int[] rgb, int[] labels, int minValidLabel, int bgColor)
  {
    int maxLabel = Label.getMax(labels);

    int[][] means = new int[maxLabel+1][3];

    // calculate the sum and count for every region
    long[][] sum  = new long[maxLabel+1][3];
    int[] count   = new int[maxLabel+1];
    for (int i=0; i<rgb.length; i++) {
      if (labels[i]<minValidLabel) continue;
        sum[labels[i]][0] += (rgb[i]>>16) & 0xff;
        sum[labels[i]][1] += (rgb[i]>> 8) & 0xff;
        sum[labels[i]][2] += rgb[i] & 0xff;
        count[labels[i]] ++;
    }

    for (int i=minValidLabel; i<=maxLabel; i++) {
      if (count[i]==0) {
        means[i][0] = means[i][1] = means[i][2] = 0;
        continue;
      }
      //System.err.println("index="+i+",count="+count[i]);
      means[i][0] = (int)(sum[i][0]/count[i]);
      means[i][1] = (int)(sum[i][1]/count[i]);
      means[i][2] = (int)(sum[i][2]/count[i]);
    }

    int[] packed_means = new int[maxLabel+1];
    for (int i=0; i<minValidLabel; i++) packed_means[i] = bgColor;
    for (int i=minValidLabel; i<=maxLabel; i++) {
      packed_means[i] = ColorUtil.packRGB(means[i][0],means[i][1],means[i][2]);
    }

    return packed_means;
  }
}