package yi.iu.processor.seg.blob;

import yi.util.io.input.*;
import yi.util.io.output.*;
import yi.util.config.*;
import yi.iu.imgdb.learn.*;

/**
 * Blob world segmentation reference can be found:
 * Chad Carson, Serge Belongie, Hayit Greenspan, and Jitendra Malik,
 * "Blobworld: Image segmentation using Expectation-Maximization and its application to image querying",
 * http://elib.cs.berkeley.edu/carson/papers/pami.html
 *
 * class BlobworldSegmenter doesn't implement the algorithm itself,
 * although it is possible that the implementation can be added later.  This
 * class is cooked to take the advantage of the free source code written in
 * Matlab:
 * http://elib.cs.berkeley.edu/photos/blobworld/
 *
 * The running procedure is:
 * 1. run blobworld in matlab to produce the segmentations
 * 2. use this class to parse and re-generate the result
 */

public class BlobworldSegmenter implements RepresentableFeatureGenerator{

  static String scaled_suffix = ".s128.ppm";

  public BlobworldSegmenter() {
  }

  public FeatureRepresentable generateFeatureRepresentable(String feature_type, int[] pixels, int width, int height) {
    String img_name = Configuration.getParameter("SOURCE_NAME");
    String ft_path = Configuration.getParameter("FEATURE_PATH");

    if (img_name.indexOf("crystal") >=0) img_name = img_name.replaceFirst("pgm.png", "pgm.bmp");

    // support map file
    String support_map_file = ft_path + img_name + ".s192.ppm_support.map";
    // feature mean file
    String ft_file = ft_path + img_name + ".s192.ppm_ft.txt";

    try {
      double[][] support_map_double = yi.util.io.ReadArgu.readMatrix(
          support_map_file, true);
      int[] support_map = yi.util.data.Conversion.from2Dto1D(yi.util.data.
          Conversion.toInt(support_map_double), width, height);
      System.out.println("width = " + support_map_double[0].length +
                         ", height = " + support_map_double.length);
      System.out.println("max label = " +
                         yi.stat.StatUtil.maximum(support_map));
      double[][] ft_mean_without_0 = yi.util.io.ReadArgu.readMatrix(ft_file, true);
      // the feature mean read from file begins from index 1.  now make the space
      // for index 0
      double[][] ft_mean = new double[ft_mean_without_0.length + 1][];
      for (int i=0; i<ft_mean_without_0.length; i++) ft_mean[i+1] = ft_mean_without_0[i];

      FeatureRepresentable rst = new BlobworldLabeledRgnFts(ft_mean,
          support_map, width, height, width, height, true);
      return rst;

    } catch (java.io.IOException e) {
      e.printStackTrace();
      return null;
    }
  }


}
