From da80d3f3545e80325b9ce87ed3c352a7fd6cb553 Mon Sep 17 00:00:00 2001 From: "James R. Barlow" Date: Mon, 7 May 2018 17:37:46 -0700 Subject: [PATCH] Add unconditional (for now) whiteout of text areas --- src/ocrmypdf/pdfinfo.py | 11 ++++++++++- src/ocrmypdf/pipeline.py | 32 +++++++++++++++++++++++++++++--- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/ocrmypdf/pdfinfo.py b/src/ocrmypdf/pdfinfo.py index eef720ee..bef0f60b 100644 --- a/src/ocrmypdf/pdfinfo.py +++ b/src/ocrmypdf/pdfinfo.py @@ -654,7 +654,7 @@ class PageInfo: @property def has_text(self): - return self._pageinfo['has_text'] + return self._pageinfo['has_text'] @property def width_inches(self): @@ -687,6 +687,15 @@ class PageInfo: def images(self): return self._pageinfo['images'] + def get_textareas(self): + if not fitz: + raise NotImplementedError("no impl without fitz") + doc = fitz.open(self._infile) + page = doc[self._pageno] + text = page.getText('dict') + for block in text['blocks']: + yield block['bbox'] + @property def xres(self): return self._pageinfo.get('xres', None) diff --git a/src/ocrmypdf/pipeline.py b/src/ocrmypdf/pipeline.py index 9df1b032..9f659c66 100644 --- a/src/ocrmypdf/pipeline.py +++ b/src/ocrmypdf/pipeline.py @@ -583,11 +583,37 @@ def select_ocr_image( log, context): """Select the image we send for OCR. May not be the same as the display - image depending on preprocessing.""" + image depending on preprocessing. This image will never be shown to the + user.""" - # For the moment this is always the .pp-clean.png image image = infiles[0] - re_symlink(image, output_file, log) + pageinfo = get_pageinfo(image, context) + + with Image.open(image) as im: + from PIL import ImageColor + from PIL import ImageDraw + from decimal import Decimal + white = ImageColor.getcolor('#ffffff', im.mode) + draw = ImageDraw.ImageDraw(im) + + for bbox in pageinfo.get_textareas(): + # Calculate resolution based on the image size and page dimensions + # without regard whatever resolution is in pageinfo (may differ or + # be None) + xres = im.width / pageinfo.width_inches + yres = im.height / pageinfo.height_inches + log.debug('calculated resolution %r %r', xres, yres) + + pixcoords = [Decimal(bbox[0]) / Decimal(72) * xres, + Decimal(bbox[1]) / Decimal(72) * yres, + Decimal(bbox[2]) / Decimal(72) * xres, + Decimal(bbox[3]) / Decimal(72) * yres] + pixcoords = [int(c) for c in pixcoords] + log.debug('blanking %r', pixcoords) + draw.rectangle(pixcoords, fill=white) + + del draw + im.save(output_file) def ocr_tesseract_hocr(