public static int[] calculateVectorSpace(BufferedImage image) { clusters = createClusters(image); int[] vectorSpace = new int[IMAGE_WIDTH * IMAGE_HEIGHT]; Arrays.fill(vectorSpace, -1); boolean refineNeeded = true; int loops = 0; while (refineNeeded) { refineNeeded = false; loops++; for (int y = 0; y < IMAGE_HEIGHT; y++) { for (int x = 0; x < IMAGE_WIDTH; x++) { int pixel = image.getRGB(x, y); Cluster cluster = getMinCluster(pixel); if (vectorSpace[IMAGE_WIDTH * y + x] != cluster.getId()) { if (vectorSpace[IMAGE_WIDTH * y + x] != -1) { clusters[vectorSpace[IMAGE_WIDTH * y + x]].removePixel(pixel); } cluster.addPixel(pixel); refineNeeded = true; vectorSpace[IMAGE_WIDTH * y + x] = cluster.getId(); } } } } System.out.println("Took " + loops + " loops."); return vectorSpace; }
@Override protected void map(WritableComparable<?> key, Text point, Context context) throws IOException, InterruptedException { Cluster nearestCluster = null; double nearestDistance = Double.MAX_VALUE; Vector pointv = parse.parseVector(point.toString()); if (pointv == null) { return; } pointv.setNumPoints(1); for (Cluster cluster : clusters) { Vector clusterCenter = cluster.getCenter(); boolean isDeny = pointv.Deny(clusterCenter); if (isDeny) { continue; } double distance = clusterCenter.distiance(pointv); context.getCounter("Clustering", "similar").increment(1); if (distance <= nearestDistance || nearestCluster == null) { nearestCluster = cluster; nearestDistance = distance; } } if (nearestCluster != null) { context.write(new Text(String.valueOf(nearestCluster.getId())), pointv); } }
protected void cleanup(Context context) throws IOException, InterruptedException { for (Cluster cluster : clusters) { Vector clusterCenter = cluster.getCenter(); clusterCenter.setNumPoints(0); context.write(new Text(String.valueOf(cluster.getId())), clusterCenter); } }