Is there a built-in method to get the 16 most frequent colors from a TImageEnView image in a TColor array?
In the meantime, I have created my own function to get the most frequent colors:
function GetMostFrequentColors(Image: TImageEnView; Count: Integer): TArray<TColor>;
// get the most frequent colors in a TImageEnView image
var
Bitmap: Vcl.Graphics.TBitmap;
x, y: Integer;
Color: TColor;
Dict: TDictionary<TColor, Integer>;
PairList: TList<TPair<TColor, Integer>>;
Pair: TPair<TColor, Integer>;
begin
Dict := TDictionary<TColor, Integer>.Create;
try
// Use the internal bitmap of ImageEnView directly
Bitmap := Image.IEBitmap.VclBitmap;
// Process each pixel to calculate color frequency
for y := 0 to Bitmap.Height - 1 do
begin
for x := 0 to Bitmap.Width - 1 do
begin
Color := Bitmap.Canvas.Pixels[x, y];
if Dict.ContainsKey(Color) then
Dict[Color] := Dict[Color] + 1
else
Dict.Add(Color, 1);
end;
end;
// Prepare to find the most common colors
PairList := TList<TPair<TColor, Integer>>.Create;
try
for Pair in Dict do
PairList.Add(Pair);
// Sort by frequency:
PairList.Sort(System.Generics.Defaults.TComparer<TPair<TColor, Integer>>.Construct(
function(const L, R: TPair<TColor, Integer>): Integer
begin
Result := R.Value - L.Value;
end));
// Extract the top 'Count' colors:
SetLength(Result, PAMin(Count, PairList.Count));
for x := 0 to High(Result) do
begin
Result[x] := PairList[x].Key;
// Log each color to CodeSite for debugging:
CodeSite.SendColor('Common Color ' + IntToStr(x+1) + ': ', PairList[x].Key);
end;
finally
PairList.Free;
end;
finally
Dict.Free;
end;
end;
Is there a better function for this purpose in ImageEn?