Scan preprocessing and structured OCR

HPDFScanPreprocess accepts a caller-owned Graphics.TBitmap and returns a private corrected image plus invertible geometry; HPDFScanOCRWorkflow uses an existing IHPDFOCREngine to return mapped words and semantic layout

The shipped acceptance profile uses Delphi and Windows FPC/Lazarus; the Tesseract OSD process adapter uses Windows APIs and is not part of the native Linux headless document profile

Corrections and evidence

The correction order is caller-supplied perspective quad, clockwise orientation, and continuous-angle deskew, with bilinear inverse sampling and white fill outside the supplied source region

Explicit orientation supports 0, 90, 180, and 270 degrees clockwise; automatic orientation requires a detector and rejects insufficient or malformed evidence

HPDFScanOrientationTesseract supplies an actual Windows Tesseract OSD adapter using an explicit executable and a tessdata directory containing osd.traineddata; it launches --psm 0 -l osd --dpi 300 directly in a hidden process without a shell

The default raw orientation margin threshold is 15; LastOrientationScore retains the actual Tesseract score and normalized confidence is the score divided by 15, clamped to [0, 1]; this normalization is an evidence scale, not a calibrated probability

Automatic deskew samples actual dark pixels and compares row-projection concentration over a bounded angle range; the default range is ±10 degrees in 0.25-degree steps, with an evidence threshold of 0.2; insufficient evidence keeps the explicit angle and records DeskewAccepted = False

Explicit deskew accepts any continuous angle from -180 through 180 degrees; automatic search supports a radius up to 45 degrees, and the step must be between 0.1 and 5 degrees

Perspective correction requires a finite convex quad ordered top-left, top-right, bottom-right, bottom-left inside the source raster and explicit target dimensions; automatic quad detection is not provided

Cleanup and finite budgets

Defaults normalize tile-local shadows, remove contiguous dark edge rows and columns, and preserve grayscale output; optional 3 by 3 median denoising and binary output can be enabled

Cleanup whites edge pixels without changing the coordinate origin; RemovedBorderPixels reports affected pixels and uniform blank rasters skip OCR

Default bounds are 32768 pixels per dimension, 16777216 input and output pixels, a conservative 512 MiB working allocation estimate, 500000000 work units, and 20000 deskew samples; source pixels must additionally fit a signed integer index

The estimate covers owned raster clones, grayscale arrays, output storage, samples, and histograms; it does not cap the caller source bitmap, operating-system graphics allocations, or an arbitrary external OCR engine

Tesseract OSD separately bounds pixels and combined stdout/stderr, polls cancellation and output size every 25 milliseconds, and terminates the child on timeout, cancellation, or output overflow; timeout must be between 1 and 3600000 milliseconds and output limit between 1024 and 1048576 bytes

Ownership and rollback

HPDFPreprocessScan never edits the source bitmap; on success the caller frees OutputBitmap, while failure returns nil and a status with diagnostic evidence

A detector receives a private copy; cancellation is cooperative at row, candidate-angle, process-wait, and word-processing boundaries; a supplied OCR engine must honor the request token and its own process and output limits

The workflow clears words, semantic layout, and line quads after every failure; the adapter maintains mutable last-report state and should be used serially

Geometry and structured OCR

Raster coordinates use an upper-left origin and pixel centers; the homogeneous matrix acts on the column vector (X, Y, 1), with division by its third coordinate; transform multiplication A × B applies B first

SourceToOutput and OutputToSource preserve the complete affine or projective operation; map separate input and output records when using the public helpers

The OCR wrapper provides the corrected raster with unrotated temporary PDF bounds to the engine, validates UTF-16 and finite word rectangles, drops insufficient-confidence or unmappable words, and maps rectangles, baselines, and four corners back to the original raster

PageQuad and semantic bounds account for the incoming PDF page box, DPI, and page rotation of 0, 90, 180, or 270 degrees; reading order is analyzed in the corrected upright frame before geometry is mapped back

Character intervals are interpolated from OCR word boxes and remain approximate; line quadrilaterals preserve rotation and perspective that axis-aligned bounds cannot represent

HPDFScanOCRLayoutToDOM creates an owned editable stack in analyzed order, using heading nodes for detected headings and text nodes for other lines

Example

Options := HPDFDefaultScanOCRWorkflowOptions;
Options.Preprocess.AutoOrientation := True;
Detector := HPDFCreateTesseractOrientationDetector(
  TesseractExecutable, OSDModelDirectory,
  HPDFDefaultTesseractOrientationOptions);
Adapter := HPDFCreateScanPreprocessingOCREngine(
  ExistingOCREngine, Options, Detector);
if Adapter.Recognize(Request, Words, Diagnostic) then
begin
  Report := Adapter.LastReport;
  DOM := HPDFScanOCRLayoutToDOM(Report);
  try
    // Consume the editable semantic output here
  finally
    DOM.Free;
  end;
end;

Verification

The non-GUI Delphi suite checks explicit orientation, reversible continuous angles through ±179.25 degrees, real Tesseract automatic 0/90/180/270 orientation and blank rejection, real five-degree automatic skew correction, noise and shadow cleanup, perspective corners, budgets, cancellation, source immutability, and real English OCR on six raster variants including a 37.5-degree scan

Every accepted word corner in the actual OCR cases is mapped back through the inverse transformation and checked within 1e-6 corrected-raster pixels; the FPC smoke suite additionally executes real deskew, cancellation, allocation limits, 180-degree and blank OSD, and real English OCR layout

The generated public headers compile under C++Builder Win32 and Win64x, including managed OCR reports, default interface arguments, geometry transforms, and DOM ownership

Set HOTPDF_TESSERACT_EXE, HOTPDF_TESSDATA for the OSD model, and HOTPDF_OCR_TESSDATA for the English model to enable external-engine verification; missing optional runtime settings do not establish real OCR acceptance