sort jpegs by average saturation in csharp

Here's the step-by-step approach to sort JPEGs by average saturation in C#:

  1. Import the necessary namespaces and assemblies
main.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using AForge.Imaging;
using AForge.Imaging.Filters;
141 chars
7 lines
  1. Define a function to calculate the average saturation of an image.
main.cs
private static double GetSaturation(Bitmap image)
{
    HSLFiltering filter = new HSLFiltering();
    filter.Saturation = 1.0;
    filter.ApplyInPlace(image);

    HSL hsl;
    double saturationSum = 0;

    for (int x = 0; x < image.Width; x++)
    {
        for (int y = 0; y < image.Height; y++)
        {
            hsl = new HSL(image.GetPixel(x, y));
            saturationSum += hsl.Saturation;
        }
    }

    return saturationSum / (image.Width * image.Height);
}
479 chars
21 lines
  1. Create a list of file paths for JPEGs to be sorted.
main.cs
List<string> filePaths = new List<string>();
string directoryPath = @"C:\Images\MyJpegs";

foreach (string filePath in Directory.GetFiles(directoryPath, "*.jpg"))
{
    filePaths.Add(filePath);
}
196 chars
8 lines
  1. Loop through the list of file paths, calculate the average saturation for each JPEG and store the values in a dictionary.
main.cs
Dictionary<string, double> saturationDict = new Dictionary<string, double>();
foreach (string filePath in filePaths)
{
    Bitmap image = new Bitmap(filePath);
    double saturation = GetSaturation(image);
    saturationDict[filePath] = saturation;
}
251 chars
8 lines
  1. Sort the dictionary by values in ascending or descending order.
main.cs
var sortedDict = saturationDict.OrderBy(x => x.Value); // ascending order
var sortedDict = saturationDict.OrderByDescending(x => x.Value); // descending order
159 chars
3 lines
  1. Loop through the sorted dictionary and output the file paths in the desired order.
main.cs
foreach (KeyValuePair<string, double> entry in sortedDict)
{
    Console.WriteLine(entry.Key);
}
97 chars
5 lines

This code uses AForge.NET library which can be installed via NuGet Package Manager in Visual Studio.

gistlibby LogSnag