Select the image we send for OCR. May not be the same as the display
    image depending on preprocessing. This image will never be shown to the
    user.

def select_ocr_image(infiles, output_file, log, context):
    """Select the image we send for OCR. May not be the same as the display
    image depending on preprocessing. This image will never be shown to the
    user."""

    image = infiles[0]
    options = context.get_options()
    pageinfo = get_pageinfo(image, context)

    with Image.open(image) as im:
        from PIL import ImageColor
        from PIL import ImageDraw

        white = ImageColor.getcolor('#ffffff', im.mode)
        # pink = ImageColor.getcolor('#ff0080', im.mode)
        draw = ImageDraw.ImageDraw(im)

        xres, yres = im.info['dpi']
        log.debug('resolution %r %r', xres, yres)

        if not options.force_ocr:
            # Do not mask text areas when forcing OCR, because we need to OCR
            # all text areas
            mask = None  # Exclude both visible and invisible text from OCR
            if options.redo_ocr:
                mask = True  # Mask visible text, but not invisible text

            for textarea in pageinfo.get_textareas(visible=mask, corrupt=None):
                # Calculate resolution based on the image size and page dimensions
                # without regard whatever resolution is in pageinfo (may differ or
                # be None)
                bbox = [float(v) for v in textarea]
                xscale, yscale = float(xres) / 72.0, float(yres) / 72.0
                pixcoords = [
                    bbox[0] * xscale,
                    im.height - bbox[3] * yscale,
                    bbox[2] * xscale,
                    im.height - bbox[1] * yscale,
                ]
                pixcoords = [int(round(c)) for c in pixcoords]
                log.debug('blanking %r', pixcoords)
                draw.rectangle(pixcoords, fill=white)
                # draw.rectangle(pixcoords, outline=pink)

        if options.mask_barcodes or options.threshold:
            pix = leptonica.Pix.frompil(im)
            if options.threshold:
                pix = pix.masked_threshold_on_background_norm()
            if options.mask_barcodes:
                barcodes = pix.locate_barcodes()
                for barcode in barcodes:
                    decoded, rect = barcode
                    log.info('masking barcode %s %r', decoded, rect)
                    draw.rectangle(rect, fill=white)
            im = pix.topil()

        del draw
        # Pillow requires integer DPI
        dpi = round(xres), round(yres)
        im.save(output_file, dpi=dpi)