DEV Community

Arthur031221
Arthur031221

Posted on

Matching rescanned pages to a damaged PDF with SIFT, and admitting when it can't

I had a scanned PDF with a few pages ruined by a coffee ring and a crease, plus fresh scans of those pages in no particular order. So I built Darnleaf, a local tool that suggests which page each rescan replaces and lets me check the evidence before it writes anything.

Darnleaf matching seven rescans to a 40-page booklet

Matching

Every page is rendered with PDFium and reduced to a working size. A cheap pass uses a spread-out subset of SIFT features to shortlist ten candidate pages per rescan. Each candidate is then verified with RANSAC under a similarity transform, and the transform has to be plausible: scale between 0.7 and 1.4, and a skew of at most 12 degrees from a right angle. That also gives the quarter turn the rescan needs. A one to one assignment resolves conflicts, so two rescans can't claim one page.

Saying "check"

A match is Clear only if it has enough consistent features, enough ink agreement after alignment and a big margin over the runner-up. Otherwise it's Check. Blank pages carry no evidence, so they're always Check. When OCR is installed, text can raise or lower a score, but it can't create a match on its own.

Export

Replaced pages are swapped in place with pikepdf. Untouched pages stay the original objects, and bookmarks and links that point at a replaced page still work. A JSON receipt records SHA-256 hashes of the original, the output and every rescan, plus the evidence for each swap.

Numbers

On 90 synthetic rescans over ten held-out seeds, 45 were Clear and none of those was wrong. With 45 trials the real wrong rate could still be about 6.7%. The right page was listed for 89 of 90. The original and the rescans are drawn from the same clean bitmap, so real scans will likely do worse.

Demo replay: https://arthur031221.github.io/Darnleaf/
Source: https://github.com/Arthur031221/Darnleaf

Top comments (0)