/** * Applies the palette to <code>image</code> using the KdTree to find the nearest neighbor. * Returned Image is a ColorImage. <code>image</code> is not modified. * * @param image ColorImage to apply palette to * @return ColorImage */ protected Image apply(ColorImage image) { RealColorImage realImage = ImageConverter.toRealColor(image); ColorImage newImage = new ColorImage(realImage.X(), realImage.Y()); float[] total = null; float[] best = null; int[] temp = new int[3]; for (int x = 0; x < realImage.X(); x++) { for (int y = 0; y < realImage.Y(); y++) { tree2.getValues().removeAllElements(); do { total = realImage.get(x, y); tree2.findNearest(total, tree2.getRoot(), threshold); threshold += 2; } while (tree2.getValues().size() == 0); threshold = 8; if (tree2.getValues().size() != 1) best = findBest(total); else best = (float[]) tree2.getValues().elementAt(0); temp[0] = (int) best[0]; temp[1] = (int) best[1]; temp[2] = (int) best[2]; newImage.set(x, y, temp); } } System.out.println("Done with the apply"); return newImage; }
/** Utility methode for apply() */ private float[] findBest(float[] best) { float dist = 999999; float[] val = new float[3]; float tempDist = 0; int location = 0; if (exact != -999) return (float[]) tree2.getValues().elementAt(exact); else { for (int x = 0; x < tree2.getValues().size(); x++) { val = (float[]) tree2.getValues().elementAt(x); tempDist = (((val[0] - best[0]) * (val[0] - best[0])) + ((val[1] - best[1]) * (val[1] - best[1])) + ((val[2] - best[2]) * (val[2] - best[2]))); if (tempDist <= dist) { dist = tempDist; location = x; } } } return (float[]) tree2.getValues().elementAt(location); }
/** * Creates a new instance of Nearest. Note, this function uses a KdTree which is calculated in * this constructor. * * @see KdTree */ public Nearest(RealColorImage paletteImage) { tree2 = new KdTree(3); tree2.buildTreePalette(paletteImage); }