Technical Article

Built-In Template-Matching OCR in Delphi with HotPDF

In Arial, a capital I and a lowercase l rasterise to the same solid vertical bar, so the word Ill on a scanned page is three identical shapes in a row. A recogniser that only compares glyph shapes has eight possible spellings and no evidence for any of them. The way out is to stop looking at the glyph and look at the line it sits on: its height bands, its gaps, and how close the second-best guess came. That is where most of the work in a small template-matching OCR engine actually goes

How the built-in engine turns a page into words

HotPDF ships a template-matching OCR engine written entirely in Object Pascal, and ApplyLoadedOCRTextLayer uses it by default to put a searchable, invisible text layer over scanned pages, with no external OCR runtime involved. The engine binarises the rendered page, cuts the ink into glyph boxes, scores each box against cached templates, and returns words with pixel coordinates. To get the engine as an object, HPDFCreateBuiltInOCREngine in the HPDFBuiltInRecognition unit returns it as an IHPDFOCREngine whose Name is HotPDF bounded ASCII OCR

Pixel to text pipeline inside the HotPDF built-in OCR engine: render the page at a 300 DPI text-layer setting, read pixels through GetDIBits with one deliberate bottom-up flip into greyscale, binarise with Otsu or a 31 by 31 local window, label 8-connected glyph boxes, score them against cached 16 by 24 templates, and write an invisible 3 Tr layer via ApplyLoadedOCRTextLayer
The bounded pipeline turns rendered pixels into an invisible text layer in six stages, and OCR quality stays bounded above by render quality because every later stage works on the raster it is handed

The envelope is narrow on purpose: high-contrast, machine-printed ASCII letters and digits (62 characters) in typefaces close to the template fonts, in axis-aligned lines, so deskew scans first. Each call takes a bitmap of at most 4096 by 4096 and 4,194,304 pixels and must finish within 2000 ms, a budget that includes building the template cache on the first call in a process. Cancellation goes through THPDFCancellationToken

Why can a pixel reader pass its tests while upside down?

A pixel reader can be vertically inverted and still match perfectly, as long as the templates were read through the same inverted path. TBitmap.ScanLine indexes rows in display order, while a DIB with a positive biHeight stores them bottom-up, and code that mixes the two conventions flips the image. Render an M upside down, compare it with a template that is also upside down, and the L1 difference is exactly what the correct comparison would give. Every glyph matches. None of them is right side up

That symmetry makes the mistake hard to dig out: fix only the target read, or only the template read, and recognition collapses to noise. No partial repair keeps the tests green, which is why the engine reads every bitmap, templates and pages alike, through one routine: GetDIBits against an explicitly declared BITMAPINFOHEADER, where a positive biHeight means bottom-up rows by contract, followed by exactly one flip while copying into the grey buffer

The second trap belongs to Windows itself. The Win32 documentation for GetDIBits says the bitmap must not be selected into a device context when you call it, and a VCL bitmap is selected into its own canvas DC. Passing Bitmap.Canvas.Handle may appear to work in one process and fail in another, with the call returning zero scan lines and the page reading as blank. A throwaway screen DC from GetDC(0) owes nothing to any bitmap, and the routine below, written for your own code, follows the same rules as the engine

procedure BitmapToGray(Bitmap: TBitmap; out Gray: TBytes);
var
  Work: TBitmap;
  Info: TBitmapInfo;
  Buffer: TBytes;
  DC: HDC;
  P: PByte;
  Stride, X, Y: Integer;
begin
  Work := TBitmap.Create;
  try
    Work.Assign(Bitmap);
    Work.PixelFormat := pf24bit;
    Stride := ((Work.Width * 24 + 31) div 32) * 4;
    SetLength(Buffer, Stride * Work.Height);
    FillChar(Info, SizeOf(Info), 0);
    Info.bmiHeader.biSize := SizeOf(BITMAPINFOHEADER);
    Info.bmiHeader.biWidth := Work.Width;
    Info.bmiHeader.biHeight := Work.Height;   // positive => bottom-up rows
    Info.bmiHeader.biPlanes := 1;
    Info.bmiHeader.biBitCount := 24;
    Info.bmiHeader.biCompression := BI_RGB;
    DC := GetDC(0);            // never Work.Canvas.Handle: Work is selected there
    if DC = 0 then
      raise EInvalidOperation.Create('Bitmap pixels could not be read');
    try
      if GetDIBits(DC, Work.Handle, 0, Work.Height,
        @Buffer[0], Info, DIB_RGB_COLORS) <> Work.Height then
        raise EInvalidOperation.Create('Bitmap pixels could not be read');
    finally
      ReleaseDC(0, DC);
    end;
    SetLength(Gray, Work.Width * Work.Height);
    for Y := 0 to Work.Height - 1 do
    begin
      P := @Buffer[(Work.Height - 1 - Y) * Stride];   // the one deliberate flip
      for X := 0 to Work.Width - 1 do
        Gray[Y * Work.Width + X] :=
          (Integer(P[X * 3]) * 29 + Integer(P[X * 3 + 1]) * 150 +
           Integer(P[X * 3 + 2]) * 77) shr 8;
    end;
  finally
    Work.Free;
  end;
end;

Under Free Pascal and Lazarus the engine takes a different route and reads pixels through a TLazIntfImage snapshot, because changing the pixel format of an assigned LCL bitmap can discard its pixels

Thresholds and glyph boxes

The engine binarises with a single global Otsu threshold and keeps a local-window threshold in reserve. A page whose grey values span fewer than 16 levels is reported as having no high-contrast foreground and produces no words. When more than half of the pixels fall on the dark side of the Otsu cut, the grey buffer is inverted first, so light text on a dark band segments the same way as dark text on paper. If the global threshold still yields no ink, each pixel is compared against the mean of its 31 by 31 neighbourhood minus a bias of 6 grey levels, using running column sums so the cost stays linear in pixel count

Glyph boxes come from 8-connected labelling driven by an explicit stack, since a recursive flood fill over a full-page mask can blow a Delphi thread stack. Components under 9 pixels are dropped as speckle, and any component wider and taller than three fifths of the image is dropped as a frame or rule. A merge pass then joins boxes whose horizontal overlap is at least a quarter of the narrower box and which nearly touch vertically, which reunites the dot of an i or j with its stem. The raster itself comes from the renderer described in rendering a loaded PDF page to a bitmap in Delphi, so a blurry render caps recognition quality before any template is compared

What decides between capital I and lowercase l?

Line context decides, because the pixels cannot. The engine groups glyph boxes into lines by vertical overlap, then asks whether each line has two height bands: a short x-height band and a tall band for capitals and ascenders. A line with a real x-height band is treated as lowercase context, and a tall bar on it leans toward l; on a line without one, the same bar leans toward I. The heights also restrict which templates a box may match: short boxes only compete against acemnorsuvwxz, boxes that drop below the baseline only against gjpqy, and tall boxes against capitals, digits and the ascender letters

The obvious way to find the two bands is a fixed ratio, and it fails on the most common font in office documents. Arial's x-height is about 0.72 of its cap height, right between the 0.70 and 0.75 that most people try first, so nudging the constant by a hundredth flips whole pages of body text. The engine sorts the line's glyph heights instead, tries every cut point, and keeps the cut with the smallest within-cluster sum of squared deviations, a one-dimensional k=2 split. The cut becomes a property of the page. A second check keeps the split honest: the line only counts as lowercase context when the mean short height is at most 0.80 of the mean tall height

Height clustering that separates the pixel-identical I and l bars in HotPDF: line glyph heights are sorted and cut with a k equals 2 variance-minimising split, SmallMean over TallMean at or below 0.80 confirms a real x-height band, and a tall bar on a line with that band is biased toward l while on a line without it the bar is biased toward I
A fixed ratio threshold lands exactly on Arial's x-height to cap-height ratio, so the cut becomes a property of the page: every split point is tried and the least within-cluster variance wins

Lines with a single height band carry no internal evidence. An all-caps heading and an all-lowercase caption look alike in isolation, so the engine compares the line's median height with the page-level x-height taken from lines that did split. A ratio of 1.10 or less marks lowercase context, 1.18 or more marks capitals, and anything in between stays unconstrained. The context then applies a 0.03 bonus to the agreeing case during matching

That bonus is a deliberate bet. A capital I at the start of Illinois in a body-text line will read as l, because in running English text a tall bar is far more often a lowercase l than a capital I, and the bonus is larger than the ambiguity margin described below. Getting the common case right is worth more than hedging on the rare one, and all-caps headings still keep their I

Why a 16 by 24 grid, and why ambiguous words are dropped

A 16 by 24 template grid keeps the open side of a c visible after resampling, and a 12 by 18 grid does not. Each glyph box is resampled into coverage values from 0 to 255, so a cell that is a third ink reads as about 85 rather than snapping to black or white. At 12 by 18 the gap of a c spans barely one cell column, averaging washes it out, and the c and o scores land a few thousandths apart. At 16 by 24 the gap survives

The score is the normalised L1 distance between the two coverage grids plus 0.30 times a log aspect-ratio penalty and 0.16 times an ink-density penalty. Any template whose aspect ratio differs by more than a factor of 2.6 is skipped before scoring. Templates are rendered once per process at 40 points from Arial, Times New Roman, Courier New, Tahoma and Segoe UI, each in regular, bold, italic and bold italic, which gives up to 1,240 templates shared by every later call

The constant that matters most is the smallest one. When the runner-up character scores within 0.018 of the winner, the glyph's confidence is clamped to 0.5, below the 0.55 acceptance gate, and the glyph is not recognised. A word is only published when every glyph in it was recognised, so one ambiguous letter removes the whole word from the layer. That is the right default for a search layer. A missing word is easy to notice and re-key; a wrong word sits invisibly under the image, where nobody reviewing the scan will ever see it

Fail-closed ambiguity gate in the HotPDF template matcher: normalised L1 scoring over 16 by 24 coverage grids with aspect and density penalties picks a winner and runner-up, a runner-up within 0.018 clamps the glyph confidence to 0.5, which falls below the 0.55 acceptance gate, so the ambiguous glyph is dropped rather than guessed into the searchable text layer
The clamp is a deliberate fail-closed cut: a bounded engine that guesses produces a text layer that does not match the image, and a wrong word is invisible to the person reviewing the scan

Word boundaries come from the same line statistics, because a fixed "gap wider than 0.75 of the mean advance" rule falls apart once digits and narrow letters share a line. The engine sorts the inter-glyph gaps on the line and looks for the largest jump between neighbours. It accepts that jump as the word-space boundary only if the jump is at least 0.22 of the average glyph width, the first gap above it is at least 0.32, and the last gap below it is at most 0.65; otherwise the whole line becomes one word. Merging two words is the cheaper error here, since InvoiceTotal still contains Total for a substring search, while a split in the middle of a word breaks it for every search

Writing the text layer and reading back what happened

ApplyLoadedOCRTextLayer writes recognised words in text rendering mode 3, which neither fills nor strokes (ISO 32000-1 §9.3.6). The content stream opens with BT and 3 Tr, and each word gets a text matrix built from its baseline, its height converted from pixels at the request DPI, and a horizontal scale that stretches the run to the measured word width. It copies and searches like ordinary text and paints nothing. Recognition and content construction finish before the document is touched, so an engine failure, budget overrun or cancellation leaves the loaded document as it was

The 300 DPI default in THPDFOCRTextLayerOptions.Default needs adjusting for the built-in engine on full pages. For a US Letter page, 300 DPI means a 2550 by 3300 raster, 8,415,000 pixels, about twice the engine's limit, and the call ends with otlsEngineError. Set DPI to 200 for Letter and A4 pages (1700 by 2200 and 1654 by 2339 pixels). The call also returns True when it simply found nothing, so check AcceptedWordCount instead of the Boolean alone

uses
  HPDFDoc;

procedure AddSearchLayer(const SourceFile, TargetFile: string);
var
  Doc: THotPDF;
  Options: THPDFOCRTextLayerOptions;
  Info: THPDFOCRTextLayerInfo;
  Pages: array of Integer;
  I: Integer;
begin
  Doc := THotPDF.Create(nil);
  try
    Doc.AutoLaunch := False;
    if Doc.LoadFromFile(SourceFile) < 1 then
      Exit;
    SetLength(Pages, Doc.LoadedPageCount);
    for I := 0 to High(Pages) do
      Pages[I] := I;
    Options := THPDFOCRTextLayerOptions.Default;
    Options.DPI := 200;                     // Letter and A4 stay under 4,194,304 px
    Options.SkipPagesWithText := True;      // the default; born-digital pages are left alone
    Options.UseOptionalContentGroup := True;
    Options.OptionalContentGroupName := 'OCR Text Layer';
    // no engine argument: the built-in recogniser is used
    if not Doc.ApplyLoadedOCRTextLayer(Pages, Options, Info) then
      Writeln('Not applied (', Ord(Info.Status), '): ', string(Info.Diagnostic))
    else if Info.AcceptedWordCount = 0 then
      Writeln('Nothing recognized: ', string(Info.Diagnostic))
    else
    begin
      Writeln(Info.AcceptedWordCount, ' words on ', Info.RecognizedPageCount,
        ' pages, ', Info.DroppedWordCount, ' dropped below MinimumConfidence');
      Doc.SaveLoadedDocument(TargetFile);
    end;
  finally
    Doc.Free;
  end;
end;

Words are filtered twice. The engine never emits a glyph under its 0.55 gate, and MinimumConfidence (0.5 by default) then drops whole words whose average confidence is lower; those show up in DroppedWordCount. The layer uses a shared, unembedded Type0 font, enough for search and copy, while ISO 19005 requires embedded fonts, so PDF/A output needs a conforming font embedded separately. The layer also carries geometry only, so for pages that already have real tagged text, structure-order text extraction driven by the tag tree answers a different question

Seeing what the engine saw on each page

When a page yields nothing, Info.Diagnostic only says that no words were accepted. The per-page reason, such as Built-in OCR found no high-contrast foreground or Built-in OCR found no unambiguous ASCII words, comes back through the Diagnostic out-parameter of IHPDFOCREngine.Recognize. A small wrapper class logs those reasons next to the bitmap size. The request bitmap is borrowed for the duration of the call, so read it inside Recognize and never keep the reference

uses
  System.SysUtils, System.Classes, HPDFDoc, HPDFBuiltInRecognition;

type
  // Your own decorator: forwards to the built-in engine and logs each page
  TLoggingOCREngine = class(TInterfacedObject, IHPDFOCREngine)
  private
    FInner: IHPDFOCREngine;
    FLog: TStrings;
  public
    constructor Create(ALog: TStrings);
    function GetName: AnsiString;
    function Recognize(const Request: THPDFOCRRequest;
      out Words: THPDFOCRWords; out Diagnostic: AnsiString): boolean;
  end;

constructor TLoggingOCREngine.Create(ALog: TStrings);
begin
  inherited Create;
  FInner := HPDFCreateBuiltInOCREngine;
  FLog := ALog;
end;

function TLoggingOCREngine.GetName: AnsiString;
begin
  Result := FInner.Name;
end;

function TLoggingOCREngine.Recognize(const Request: THPDFOCRRequest;
  out Words: THPDFOCRWords; out Diagnostic: AnsiString): boolean;
begin
  Result := FInner.Recognize(Request, Words, Diagnostic);
  FLog.Add(Format('page %d, %dx%d px at %d DPI: %d words %s',
    [Request.PageIndex, Request.Bitmap.Width, Request.Bitmap.Height,
     Request.DPI, Length(Words), string(Diagnostic)]));
end;

// usage: keep the engine in an interface variable so reference counting frees it
//   Engine := TLoggingOCREngine.Create(Memo1.Lines);
//   Doc.ApplyLoadedOCRTextLayer(Pages, Engine, Options, Info);

The same three-argument overload is the seam for a different recogniser. Implement Recognize against any engine you like and return words in bitmap pixel coordinates; coordinate mapping, page rotation, Unicode validation, budgets and the all-or-nothing commit stay exactly as they are. To confirm a layer landed, reload the saved file and run the ordinary text path from extracting text from a loaded PDF in Delphi: if the words come back, the layer is real

Rendering, recognition, the invisible layer and the extraction that checks it all live in one native VCL component, with no OCR runtime or extra DLL to deploy. For document capture or archive search over scanned PDFs in Delphi and C++Builder, the HotPDF Delphi PDF component covers that path from page bitmap to searchable file