Map OCR Boxes Back After Scaling and Cropping

The bounding box returned by OCR is very accurate on the local image, but when rendered back into the PDF, it is offset overall. Do not immediately suspect the

If you run OCR on a scanned page and the boxes land in the wrong place once they are drawn back onto the PDF, this guide is for you. The box is usually accurate on the processed image, but the whole overlay looks offset. That makes the problem hard to trace, because it seems to point at the recognition engine.

Most of the time the cause is the preprocessing pipeline, not OCR. Cropping, scaling and adding borders each change the coordinates, so the mapping back has to undo those steps in reverse order.

Below you will find the transformation order to check, a deterministic way to invert it, a round-trip test for non-integer coordinates, and manual anchor checks for the final display. These steps help you keep highlights aligned with the source text in translation and proofreading workflows.

How do you map OCR boxes back correctly? The short answer

Record every preprocessing step and apply its inverse in reverse order, using saved parameters rather than guessed offsets.

Your situationWhat to doWhy
Boxes are offset across the whole pageCheck the order of cropping, scaling and paddingEach step changes the coordinates, so the inverse must reverse them
Scale factors differ horizontally and verticallyStore the horizontal and vertical scales separatelyA single scale value would distort the mapping
Images are rotated or corrected for perspectiveMap all four corners and keep the quadrilateralTwo points cannot describe a rotated or warped result
Coordinates are fractionalKeep floating-point values and round only at final renderingEarly rounding adds drift
You want to show source locations in a translation toolValidate coordinate links alongside content linksWrong highlights make correct translations look unreliable

Why the boxes shift: check the preprocessing order

The bounding box returned by OCR is very accurate on the local image. When it is rendered back into the PDF, though, the overlay is offset overall. Do not suspect the recognition engine first. Check your preprocessing sequence instead:

  • Was cropping performed first?
  • Was the image then scaled?
  • Was an additional white border added?

Each step alters the coordinates, so the inverse transformation must undo them in the reverse order.

Use a deterministic transformation, not a guessed offset

Work from the forward transformation. The original image points are:

  1. Reduced by the cropping origin.
  2. Multiplied by the scaling factor.
  3. Increased by the padding.

The inverse runs in the opposite direction:

  1. Subtract the padding.
  2. Divide by the scaling factor.
  3. Add back the cropping origin.

If the horizontal and vertical scales differ, store them separately. This also means that stretching an image arbitrarily will alter the shape of the text, so keep the aspect ratio unless you have a specific reason to change it.

Test round trips with non-integer coordinates

from math import isclose

origin = (100.0, 40.0)
scale = (2.0, 1.5)
padding = (8.0, 12.0)

def forward(point):
    return tuple((point[i] - origin[i]) * scale[i] + padding[i]
                 for i in range(2))

def inverse(point):
    if any(s <= 0 for s in scale):
        raise ValueError("positive scale required")
    return tuple((point[i] - padding[i]) / scale[i] + origin[i]
                 for i in range(2))

for point in [(100, 40), (125.5, 62.25), (200, 90)]:
    restored = inverse(forward(point))
    assert all(isclose(a, b) for a, b in zip(point, restored))
assert forward((100, 40)) == padding
assert inverse((58, 42)) == (125.0, 60.0)

The example code was checked with synthetic samples in an isolated environment, and no OCR was run. It verifies the geometric formula only. Image resampling involves pixel centres and rounding conventions. To map to the true bounding box, use either unified continuous coordinates or explicit pixel-boundary rules.

Do not round floating-point coordinates early. Apply your rounding rules once, at the final rendering stage.

Boxes are not always rectangles

Each transformation needs different information saved so that you can map it back.

transformationneeds to savemapping note
croppingorigin offsetrestored to which version of the original image
scalingaspect ratioprevents loss of precision in integer division
rotatesrotation center and matrixmaps the four corners and then preserves the quadrilateral
perspective correctionhomographyA two-point rectangle is insufficient to represent the result

Check the display with manual anchor points

Mark known corner points on several anonymised samples. Then check whether they still coincide with their original positions after preprocessing and remapping.

Passing unit tests for the maths rules out some computational errors. It does not rule out bias from page rotation, display scaling or the PDF coordinate system. Those can still shift the result, so check the rendered PDF as well.

Keep trusted locations for bilingual highlighting

If you are building a proofreading tool for translations, and you want to show source locations, validate the coordinate links alongside the content links. Highlights on the wrong lines can make even correct translations look unreliable.

Keep a record of your transformations. This is easier to maintain than temporary compensations applied at the front end. You can find the product details on the OmniDoc product page.

For the sizing and transformation methods used in the examples, see the Pillow Image Size and Transformation Interface reference.

Before you process important files, keep the original copies. Then verify the results against your own boundaries and acceptance criteria. The examples here do not guarantee results for every real file or product.

📊 At a glance

transformationwhat to savehow to map it back
CroppingOrigin offsetRestore the crop origin
ScalingAspect ratio, separate horizontal and vertical scalesDivide by the scale factor
RotationRotation centre and matrixMap the four corners and keep the quadrilateral
Perspective correctionHomographyMap with the homography; two points are not enough

🎯 Which approach fits you?

If your boxes are shifted across the whole page

Check the order of cropping, scaling and padding first, then invert them in reverse.

If your image was scaled unevenly

Store the horizontal and vertical scales separately, and avoid stretching that changes the shape of text.

If your page was rotated or corrected for perspective

Map all four corners so the quadrilateral is preserved.

If you are building a bilingual proofreading tool

Validate coordinate links with the content links, and keep a record of every transformation.

❓ FAQ

1. Is the OCR engine causing the offset?

Usually not. The box is accurate on the processed image, so check your preprocessing steps and the order in which you undo them first.

2. Why not just round the coordinates as you go?

Early rounding adds drift. Keep floating-point values and apply explicit rounding rules once, at final rendering.

3. Can two points describe a transformed box?

Not in every case. Rotated boxes need their four corners mapped, and perspective correction needs a homography.

4. Do passing unit tests prove the mapping is correct?

No. They rule out some calculation errors, but page rotation, display scaling and the PDF coordinate system can still shift the result. Check anchor points on the rendered output.

📝 Summary

Map OCR boxes back by recording each preprocessing step and inverting them in reverse order. Verify the result with anchor points on the rendered PDF, and keep your original files for comparison.

Try it now: upload a document and get it translated with the layout intact

Updated 2026-11-04