For 24-bit-per-pixel images you can try the code below, which will make available the most frequently used color, how many times it is used, and also make available a list of the top ten most frequently used colors, and how many times they are used.
Disclaimer: this code is presented for educational purposes only; I developed it quickly (in a few hours), and it is not fully tested for accuracy. You use this code at your own risk.
To use this code you need to have a file-path to a 24 bit-per-pixel image:
private string filep = @"C:\Users\You\Desktop/SomeFileName.jpg";
And then turn the file reference into a Bitmap object and call the main method of the Class like this:
Bitmap bMap = Bitmap.FromFile(filep) as Bitmap;
if (bMap == null) throw new FileNotFoundException("Cannot open picture file for analysis");
YourNameSpace.PictureAnalysis.GetMostUsedColor(bMap);
Set a breakpoint after the call to 'GetMostUsedColor, and examine the results in the four public variables the Class exposes: MostUsedColor, MostUsedColorIncidence, TenMostUsedColors, TenMostUsedColors, TenMostUsedColorIncidences.
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
namespace YourNameSpace
{
public static class PictureAnalysis
{
public static List<Color> TenMostUsedColors {get; private set;}
public static List<int> TenMostUsedColorIncidences {get; private set;}
public static Color MostUsedColor {get; private set;}
public static int MostUsedColorIncidence {get; private set;}
private static int pixelColor;
private static Dictionary<int, int> dctColorIncidence;
public static void GetMostUsedColor(Bitmap theBitMap)
{
TenMostUsedColors = new List<Color>();
TenMostUsedColorIncidences = new List<int>();
MostUsedColor = Color.Empty;
MostUsedColorIncidence = 0;
dctColorIncidence = new Dictionary<int, int>();
for (int row = 0; row < theBitMap.Size.Width; row++)
{
for (int col = 0; col < theBitMap.Size.Height; col++)
{
pixelColor = theBitMap.GetPixel(row, col).ToArgb();
if (dctColorIncidence.Keys.Contains(pixelColor))
{
dctColorIncidence[pixelColor]++;
}
else
{
dctColorIncidence.Add(pixelColor, 1);
}
}
}
var dctSortedByValueHighToLow = dctColorIncidence.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
foreach (KeyValuePair<int, int> kvp in dctSortedByValueHighToLow.Take(10))
{
TenMostUsedColors.Add(Color.FromArgb(kvp.Key));
TenMostUsedColorIncidences.Add(kvp.Value);
}
MostUsedColor = Color.FromArgb(dctSortedByValueHighToLow.First().Key);
MostUsedColorIncidence = dctSortedByValueHighToLow.First().Value;
}
}
}
Note: For possible issues with ordering a Generic Dictionary see discussion here: [
^].