To prepare a PDF for OCR, you can use a combination of image processing techniques to enhance the contrast and remove noise from the pages. Here's a Python script that uses the OpenCV library to perform these operations:
import cv2
import numpy as np
# Load the PDF file
with open('file.pdf', 'rb') as f:
pdf_pages = pd.read_pdf(f)
# Loop through each page
for page in pdf_pages:
# Convert the page to grayscale
gray = cv2.cvtColor(page, cv2.COLOR_BGR2GRAY)
# Apply thresholding to separate text from background
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# Remove noise by applying a median filter
med = cv2.medianBlur(thresh, 5)
# Apply adaptive thresholding to enhance contrast
adaptive_thresh = cv2.adaptiveThreshold(med, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
# Invert the thresholded image to get the text
text = cv2.bitwise_not(adaptive_thresh)
# Save the processed page as a new PDF file
cv2.imwrite('processed_page_{:d}.pdf'.format(page_num), text)
This script assumes that the PDF file contains a single page per file, and saves the processed pages as new PDF files with the same name but with a _processed suffix.
Here's a breakdown of the operations performed in the script:
- Load the PDF file using the
pd.read_pdf() function from the PyPDF2 library.
- Convert each page to grayscale using the
cv2.cvtColor() function with the cv2.COLOR_BGR2GRAY conversion code.
- Apply thresholding to separate text from background using the
cv2.threshold() function with the cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU flags. This will give us a binary image where text is white and background is black.
- Remove noise by applying a median filter using the
cv2.medianBlur() function with a 5-pixel radius.
- Apply adaptive thresholding to enhance contrast using the
cv2.adaptiveThreshold() function with the cv2.ADAPTIVE_THRESH_GAUSSIAN_C flag and a 11 x 11 kernel size. This will adjust the threshold value based on the local image intensity, which helps to improve contrast on varying backgrounds.
- Invert the thresholded image to get the text using the
cv2.bitwise_not() function.
- Save the processed page as a new PDF file using the
cv2.imwrite() function.
Note that the script assumes that the PDF pages are not rotated, and that the text is horizontal. If your pages are rotated, you'll need to rotate them before applying the thresholding operations. You can use the cv2.rotate() function to do this.
Also, this script is just a starting point, and you may need to adjust the parameters of the image processing operations (such as the threshold values, kernel size, etc.) to get the best results for your specific use case.