package collage.utils;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.util.List;
import collage.image.FeatureSet;
public class NearestNeighbour {
/**
* Simple brute-force NN search over candidates.
*
* @param srcImg - source solution
* @param candidates - candidate solutions
* @param gridDim - dimension of sub-picture
* @return closest candidate solution to source solution
*/
public FeatureSet find(BufferedImage srcImg, List<FeatureSet> candidates, Dimension gridDim) {
FeatureCollector fc = new FeatureCollector();
return this.find(fc.gather(srcImg, "", gridDim), candidates);
}
public FeatureSet find(FeatureSet srcFeature, List<FeatureSet> candidates) {
double minDist = Double.POSITIVE_INFINITY;
double curDist;
FeatureSet bestCand = null;
for (FeatureSet cand : candidates) {
curDist = this.MSE(srcFeature, cand);
if (curDist < minDist) {
minDist = curDist;
bestCand = cand;
}
}
return bestCand;
}
/**
* Calculates distance of the closest candidate, using MSE.
*
* @param srcFeature - FeatureSet representing one image A's cell
* @param candidates - Image Bi's FeatureSets (one of them will be the closest)
* @return Distance to the closest candidate
*/
public double getNearestDistance(FeatureSet srcFeature, List<FeatureSet> candidates) {
double minDist = Double.POSITIVE_INFINITY;
double curDist;
for (FeatureSet cand : candidates) {
curDist = this.MSE(srcFeature, cand);
if (curDist < minDist) {
minDist = curDist;
}
}
return minDist;
}
/**
* Mean-squared error
*
* @param src
* @param dst
* @return sum of MSEs of grids
*/
private double MSE(FeatureSet src, FeatureSet dst) {
Color[] srcColors = src.getColors();
Color[] dstColors = dst.getColors();
double distance = 0;
Color srcCol, dstCol;
for (int i = 0; i < srcColors.length; i++) {
srcCol = srcColors[i];
dstCol = dstColors[i];
distance += (Math.pow(srcCol.getRed()-dstCol.getRed(), 2) +
Math.pow(srcCol.getGreen()-dstCol.getGreen(), 2) +
Math.pow(srcCol.getBlue()-dstCol.getBlue(), 2))/3.0;
}
return distance;
}
}