package com.aluxoft.earrecognition;

import com.aluxoft.earrecognition.utils.OpenCvUtils;
import com.google.gson.Gson;

import org.opencv.core.Mat;
import org.opencv.core.MatOfKeyPoint;
import org.opencv.features2d.DescriptorExtractor;
import org.opencv.features2d.FeatureDetector;
import org.opencv.highgui.Highgui;

import java.util.ArrayList;

/**
 * Created by josejuliomartinez on 06/10/15.
 */
public class EarIdentifier {

    private EarDatabase database;

    public EarIdentifier(EarDatabase _database) {
        this.database = _database;
    }

    public void setDatabase(EarDatabase _database) {
        this.database = _database;
    }

    /**
     * Do the ear identification process.
     * @param feature The result of the identification.
     * @return
     */
    public EarIdentifierResult identify(EarFeature feature) {
        return null;
    }


    public String computeFeatures(String imagePath) {

        Mat image, descriptors;
        MatOfKeyPoint keypoints;

        descriptors = new Mat();
        keypoints = new MatOfKeyPoint();

        image = Highgui.imread(imagePath, Highgui.CV_LOAD_IMAGE_GRAYSCALE);

        OpenCvUtils.resizeMat(image, 160, 120);

        FeatureDetector detector = FeatureDetector.create(FeatureDetector.SIFT);
        detector.detect(image, keypoints);
        DescriptorExtractor extractor = DescriptorExtractor.create(DescriptorExtractor.SIFT);
        extractor.compute(image, keypoints, descriptors);

        ArrayList<ArrayList<Integer>> features = new ArrayList<>();
        for (int i=0;i<descriptors.rows();++i) {
            ArrayList<Integer> feature = new ArrayList<>();
            for (int j=0;j<descriptors.cols();++j) {
                feature.add((int)descriptors.get(i, j)[0]);
            }
            features.add(feature);
        }
        Gson gson = new Gson();
        return gson.toJson(features);
    }

    static {
        System.loadLibrary("opencv_java");
        System.loadLibrary("nonfree");
    }

}
