sort a folder of jpgs based on similarity to a given image in csharp

To sort a folder of jpg images based on how similar they are to a given image, you can follow these steps:

  1. Load the given image into a Bitmap object in C#.
main.cs
Bitmap givenImage = new Bitmap("path/to/given/image.jpg");
59 chars
2 lines
  1. Loop through all the jpg files in the folder and load each of them into a Bitmap object.
main.cs
string folderPath = "path/to/folder/";
string[] jpgFiles = Directory.GetFiles(folderPath, "*.jpg");

List<Bitmap> images = new List<Bitmap>();

foreach(string filePath in jpgFiles) {
    Bitmap image = new Bitmap(filePath);
    images.Add(image);
}
249 chars
10 lines
  1. For each image in the folder, compute the similarity score with the given image. Here, we will use the mean squared error as the similarity score.
main.cs
double ComputeMSE(Bitmap image1, Bitmap image2) {
    if (image1.Width != image2.Width || image1.Height != image2.Height)
        throw new ArgumentException("Images must have the same dimensions");

    double mse = 0.0;

    for (int i = 0; i < image1.Width; i++) {
        for (int j = 0; j < image1.Height; j++) {
            Color pixel1 = image1.GetPixel(i, j);
            Color pixel2 = image2.GetPixel(i, j);
            double deltaR = pixel1.R - pixel2.R;
            double deltaG = pixel1.G - pixel2.G;
            double deltaB = pixel1.B - pixel2.B;
            mse += deltaR * deltaR + deltaG * deltaG + deltaB * deltaB;
        }
    }

    mse /= (image1.Width * image1.Height * 3);
    return mse;
}

List<double> similarityScores = new List<double>();

foreach(Bitmap image in images) {
    double mse = ComputeMSE(image, givenImage);    
    similarityScores.Add(mse);
}
892 chars
28 lines
  1. Sort the list of jpg file paths based on the similarity scores.
main.cs
Array.Sort(similarityScores.ToArray(), jpgFiles);
50 chars
2 lines

Now, jpgFiles array contains the file paths to jpg images sorted based on their similarity scores to the given image.

gistlibby LogSnag