# Sort images by difference

I can use ImageDistance to get the Euclidean distance between two images. But, I have list of (~100) images, and I want to sort them such that the average ImageDistance between any two consecutive images is minimized. I feel like there has to be a better solution than going through every permutation.

I think you can use FindHamiltonianPath for this. Unfortunately, unlike FindShortestTour, FindHamiltonianPath doesn't support a DistanceFunction, so you need to enter a graph object instead of a list of elements with a DistanceFunction. At any rate, here is a list of image:

images = ExampleData /@ ExampleData["TestImage"];
Length[images]


50

The graph object is a weight graph where the weights are the distances between each image:

g = WeightedAdjacencyGraph[
DistanceMatrix[images, DistanceFunction->ImageDistance]
]; //AbsoluteTiming


{1.44155, Null}

Now, use FindHamiltonianPath:

path = FindHamiltonianPath[g]; //AbsoluteTiming
path


{0.435027, Null}

{35, 36, 44, 3, 4, 2, 13, 17, 25, 26, 24, 1, 16, 37, 22, 43, 21, 33, 39, 9, 7, 48, 46, 41, 47, 12, 38, 18, 49, 14, 19, 5, 28, 32, 27, 15, 8, 29, 10, 50, 42, 11, 6, 40, 31, 20, 23, 30, 34, 45}

For my example set of images, the result is then:

images[[path]]