package yi.iu.processor.morph;

import java.awt.*;
import yi.iu.processor.channel.IntensityMaker;
import yi.iu.processor.morph.*;
import yi.util.io.ReadArgu;
import yi.util.io.OutputResult;
import yi.util.config.*;
import yi.util.io.input.*;
import yi.util.io.output.*;
import yi.util.log.*;
import yi.iu.processor.canny.*;


public class Threshold {
  int m_threshold;
  public static int THRESHOLD = 128;

  public Threshold(int t) {
    m_threshold = t;
  }

  /**
   * Threashold the source image.  The value in source array must in gray level
   * already. Return 1 if p >= threshold; else 0.
   * @param source
   * @param d
   * @return
   */
  public int[] getProcessed(int source[], Dimension d) {
    int[] binary = new int[source.length];
    for (int i=0;i<source.length;i++) {
      int intensity = source[i]&0xff;
      binary[i] = (intensity>= m_threshold)?1:0;
    }
    return binary;
  }

  public static void main(String[] args) {
    // init configuration
    Configuration.init(args);

    // get the image name
    String img_name = ReadArgu.getOption('i', args);
    if (img_name == null) {
      System.err.println("Usage: -i image_name");
      System.exit(1);
    }

    int threshold = THRESHOLD;
    String t_str = ReadArgu.getOption('t', args);
    if (t_str != null) threshold = Integer.parseInt(t_str);
    System.out.println("threshold = " + threshold);

    // read in image
    Image image = null;
    Dimension d = new Dimension();
    int[] pixels = null;
    try {
      image = yi.util.io.ImageReader.readImageFile(img_name);
      pixels = yi.util.io.ImageReader.getPixels(image, d);
    }
    catch (java.io.IOException e) {
      System.err.println("Can't read image " + img_name);
      e.printStackTrace();
      System.exit(2);
    }


    // process
    // intensity
    Configuration.setParameter("SOURCE_NAME", img_name);
    IntensityMaker in = new IntensityMaker();
    int[] intensity = in.getProcessed(pixels, d);
//    int[] gray = yi.util.ImageUtil.makeNewImageFromGray(intensity);
//    OutputResult.outputGIFImage(img_name + "." + DOU.shortName(in.getClass().getName()) + ".gif", gray, d.width, d.height);
    // threshlod
    Threshold t = new Threshold(threshold);
    int[] binary = t.getProcessed(intensity, d);
    yi.util.ImageUtil.makeImageFromBinary(binary);
    OutputResult.outputGIFImage(img_name + "." + DOU.shortName(t.getClass().getName()) + ".gif", binary, d.width, d.height);
    System.exit(0);
  }

}