您的问题的一个答案是使用pdf2image 模块将PDF 视为图像,并使用pytesseract 提取其中的文本。这样,您就可以使用opencv 裁剪页眉和页脚,以仅保留文件的核心。但是它可能不是完美的方法,因为 pdf2image 方法 convert_from_path 可能需要很长时间才能运行。
如果你有兴趣,我在这里放一些代码。
首先确保您安装了所有必要的依赖项以及 Tesseract 和 ImageMagik。您可以在网站上找到有关安装的任何信息。如果您正在使用 Windows,那么有一篇很好的 Medium 文章 here。
使用 pdf2image 将 PDF 转换为图像:
如果您在 Windows 上工作,请不要忘记添加您的 poppler 路径。它应该看起来像 r'C:\<your_path>\poppler-21.02.0\Library\bin'
def pdftoimg(fic,output_folder, poppler_path):
# Store all the pages of the PDF in a variable
pages = convert_from_path(fic, dpi=500,output_folder=output_folder,thread_count=9, poppler_path=poppler_path)
image_counter = 0
# Iterate through all the pages stored above
for page in pages:
filename = "page_"+str(image_counter)+".jpg"
page.save(output_folder+filename, 'JPEG')
image_counter = image_counter + 1
for i in os.listdir(output_folder):
if i.endswith('.ppm'):
os.remove(output_folder+i)
裁剪图像页脚和页眉:
我不知道您的页脚和页眉的大小,但通过尝试多次裁剪您的图像,您应该能够找到要使用的正确尺寸。
然后,您可以使用 OpenCV 裁剪方法 new_head 是标题下方 y 轴上顶部像素的值,new_bottom 是底部像素来裁剪图像以保留 PDF 的正文在页脚开始的 y 轴上。
def crop_img(fic, output_folder):
img = cv2.imread(fic)
shape = img.shape
crop_img = img[new_head:new_bottom, 0:shape[1]]
cv2.imwrite(output_folder+name, crop_img)
从图像中提取文本:
您的 tesseract 路径将是这样的:r'C:\Program Files\Tesseract-OCR\tesseract.exe'
def imgtotext(img, tesseract_path):
# Recognize the text as string in image using pytesserct
pytesseract.pytesseract.tesseract_cmd = tesseract_path
text = str(((pytesseract.image_to_string(Image.open(img)))))
text = text.replace('-\n', '')
return text