GetHistogram example for Delphi

The following code does a CMYK separation and uses a histogram to find the brightest and darkest intensities in the K plane of the bitmap. It then remaps the intensities to use the full range and merges the color planes to recreate the bitmap:

var
Brightest, Darkest, MyIndex, Offset, CurrentRange: Integer;

begin
Screen.Cursor := crHourglass;

{Do a CMYK color separation and copy the K plane to the bitmap}
LeadImage1.ColorSeparate(COLORSEP_CMYK);
LeadImage1.Bitmap := 0; {Free the bitmap}
LeadImage1.Bitmap := LeadImage1.ColorPlanes[3]; {Copy the K plane}

{Load the histogram}
LeadImage1.GetHistogram(CHANNEL_MASTER);

{Find the brightest and darkest intensities in the image}
MyIndex := 0;
Brightest := 0;
Darkest := -1;
While (MyIndex < 256) Do
begin
    If LeadImage1.HistogramTable[MyIndex] > 0 Then
    begin
        Brightest := MyIndex;
        If (Darkest = -1) Then Darkest := MyIndex;
    end;
    MyIndex := MyIndex + 1;
end;

LeadImage1.RemapTableSize := 256;
{Remap the intensities to use the full range}
MyIndex := Darkest;
CurrentRange := Brightest - Darkest;
If CurrentRange > 0 Then
begin
  While (MyIndex <= Brightest) do
  begin
      Offset := MyIndex - Darkest;
      LeadImage1.RemapTable[MyIndex] := round((255 * Offset) / CurrentRange);
      MyIndex := MyIndex + 1;
  end;
  LeadImage1.RemapIntensity(CHANNEL_MASTER);
end;

{Merge the color planes and free them from memory}
LeadImage1.ColorPlanes[3] := LeadImage1.Bitmap; {Update the K plane}
LeadImage1.ColorMerge(COLORSEP_CMYK);
LeadImage1.ColorPlanes[0] := 0;
LeadImage1.ColorPlanes[1] := 0;
LeadImage1.ColorPlanes[2] := 0;
LeadImage1.ColorPlanes[3] := 0;

{Set the image display size to match the LEAD control}
LeadImage1.SetDstRect(0, 0, LeadImage1.Width, LeadImage1.Height);
LeadImage1.SetDstClipRect(0, 0, LeadImage1.Width, LeadImage1.Height);
LeadImage1.ForceRepaint;
Screen.Cursor := crDefault;

end;