package yi.iu.processor.edh;

import java.awt.*;
import java.util.*;
import yi.iu.processor.*;
import yi.iu.processor.canny.*;
import yi.iu.processor.channel.IntensityMaker;

import yi.util.config.*;
import yi.util.io.*;
import yi.util.io.input.*;
import yi.util.io.output.*;
import yi.util.log.*;

/**
 * Title:
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author
 * @version 1.0
 */

public class EdgeDirectionHistogram extends ImageProcessor {

  public int[] getProcessedPseudoColor(int[] image, Dimension d) {
    getProcessed(image, d);
    return null;
  }
  public int[] getProcessed(int[] source, Dimension d) {
    Object[] ref= new Object[1];
    getProcessed_ex(source, d, ref);
    return null;
  }
  public double[] getProcessed_ex(int source[], Dimension d, Object ref[]) {
    IntensityMaker im= new IntensityMaker();
    int[] image= im.getProcessed(source, d);

    CannyEdgeDector canny = new CannyEdgeDector();
    int[] edges = new int[image.length];
    double[] directions = new double[image.length];
    int[] magnitudes = new int[image.length];
    canny.canny(image, d, edges, directions, magnitudes);

    // make the edge direction histogram
    double[] edh = new double[73];
    int number_edge = 0;     // ne as defined in paper
    for (int i=0; i<image.length; i++) {
        if (edges[i] == CannyEdgeDector.EDGE) {
            int bin = (int) (directions[i]/5);
            if (bin < 0 || bin >= 72)
               System.err.println("Quantize out of range, index = " + i +
                                            " , bin = " + bin);
            edh[bin] ++;
            number_edge ++;
        }
    }
    // normalize the histogram
    for (int i=0; i<72; i++) edh[i] /= number_edge;
    edh[72] = (double)(image.length - number_edge) / image.length;
    ref[0] = edh;
    //yi.util.io.OutputResult.outputResult("edh", edh);
    return edh;
  }

  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);
    }

    // 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
    Configuration.setParameter("SOURCE_NAME", img_name);
    EdgeDirectionHistogram edh = new EdgeDirectionHistogram();
    double[] rst = edh.getProcessed_ex(pixels, d, null);

    // output result
    OutputResult.outputResult(img_name + "." + DOU.shortName(edh.getClass().getName()) + ".edh", rst);

    System.exit(0);
  }

}
