Python實現(xiàn)PDF轉換文本詳解
一、前言
對很多人來說,將PDF轉換為可編輯的文本是個剛需,卻苦于沒有簡單的方法。發(fā)現(xiàn) pdf 幻燈片,效果還不錯。
傳統(tǒng)的講座通常伴隨有很多pdf幻燈片。一般來說,想要對自己的講座做筆記,需要從pdf復制、補充大量內容。
最近,來自 K1 Digital 的高級機器工程師 Lucas Soares 一直在嘗試通過使用 CR(光學字符識別)自動 pdf 幻燈片,以便直接在 Markdown 文件中操作它們的內容,從而避免手動復制和粘貼 pdf 內容,實現(xiàn)這個過程的自動化。

圖為項目作者盧卡斯·蘇亞雷斯。
1.1、為什么不使用傳統(tǒng)的pdf 轉文本工具呢?
Lucas Soares 發(fā)現(xiàn)傳統(tǒng)工具往往會帶來更多的問題,需要花時間解決。他曾嘗試使用傳統(tǒng)的 Python 軟件包,但遇到了很多問題(例如必須使用復雜的正則表達式模式解析最終輸出等),因此決定嘗試使用目標檢測和 OCR 來解決。
二、實現(xiàn)過程
基本過程可分為以下幾個步驟:
- 將 pdf 轉換為圖片;
- 檢測和識別圖像中的文本;
- 展示示例輸出。
2.1、基于深度學習的 OCR 將 pdf 為文本
2.1.1、將 pdf 轉換為圖像
Soares 使用的 pdf 幻燈片來自于 David Silver 的增長學習(參見以下 pdf 幻燈片地址)。使用「pdf2image」包將每張幻燈片轉換為 png 圖像格式。

pdf 幻燈片示例。
地址:https://www.davidsilver.uk/wp-content/uploads/2020/03/intro_RL.pdf
代碼如下:
from pdf2image import convert_from_path
from pdf2image.exceptions import (
PDFInfoNotInstalledError,
PDFPageCountError,
PDFSyntaxError
)
pdf_path = "path/to/file/intro_RL_Lecture1.pdf"
images = convert_from_path(pdf_path)
for i, image in enumerate(images):
fname = "image" + str(i) + ".png"
image.save(fname, "PNG")
經過處理后,所有的pdf幻燈片都轉換成png格式的圖片:

2.1.2、檢測和識別圖像中的文本
為了檢測和識別png圖像中的文本,Soares使用ocr.pytorch庫中的文本檢測器。按照說明下載模型保存模型保存在檢查點文件夾中。
ocr.pytorch 庫地址:https://github.com/courao/ocr.pytorch
代碼如下:
# adapted from this source: https://github.com/courao/ocr.pytorch
%load_ext autoreload
%autoreload 2
import os
from ocr import ocr
import time
import shutil
import numpy as np
import pathlib
from PIL import Image
from glob import glob
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import pytesseract
def single_pic_proc(image_file):
image = np.array(Image.open(image_file).convert('RGB'))
result, image_framed = ocr(image)
return result,image_framed
image_files = glob('./input_images/*.*')
result_dir = './output_images_with_boxes/'
# If the output folder exists we will remove it and redo it.
if os.path.exists(result_dir):
shutil.rmtree(result_dir)
os.mkdir(result_dir)
for image_file in sorted(image_files):
result, image_framed = single_pic_proc(image_file) # detecting and recognizing the text
filename = pathlib.Path(image_file).name
output_file = os.path.join(result_dir, image_file.split('/')[-1])
txt_file = os.path.join(result_dir, image_file.split('/')[-1].split('.')[0]+'.txt')
txt_f = open(txt_file, 'w')
Image.fromarray(image_framed).save(output_file)
for key in result:
txt_f.write(result[key][1]+'\n')
txt_f.close()
設置輸入和輸出文件夾,接著遍歷所有輸入圖像(轉換后的pdf幻燈片),然后通過single_pic_proc()函數(shù)運行OCR模塊中的檢測和識別模型,最后將輸出保存到輸出文件夾。
從檢測繼承(inherit)了Pytorch CTPN,識別了Pytorch CRNN,模型都存在于OCR模塊中。
2.1.3、示例輸出
代碼如下:
import cv2 as cv
output_dir = pathlib.Path("./output_images_with_boxes")
# image = cv.imread(str(np.random.choice(list(output_dir.iterdir()),1)[0]))
image = cv.imread(f"{output_dir}/image7.png")
size_reshaped = (int(image.shape[1]),int(image.shape[0]))
image = cv.resize(image, size_reshaped)
cv.imshow("image", image)
cv.waitKey(0)
cv.destroyAllWindows()
下圖左為原始pdf 幻燈片,圖右為腦后的輸出文本,準確率非常高。

文本識別輸出如下:
filename = f"{output_dir}/image7.txt"
with open(filename, "r") as text:
for line in text.readlines():
print(line.strip("\n"))
通過上述方法,最終可以得到一個非常強大的工具來討論文檔,從檢測和識別手寫筆記到檢測和識別照片中的隨機。
擁有文本的 OCR 工具來處理一些文本內容,這比依賴外部軟件來說明文檔要好得多。
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
相關文章
PyQt5 QLineEdit輸入的子網(wǎng)字符串校驗QRegExp實現(xiàn)
這篇文章主要介紹了PyQt5 QLineEdit輸入的子網(wǎng)字符串校驗QRegExp實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04
Ubuntu中配置TensorFlow使用環(huán)境的方法
這篇文章主要介紹了Ubuntu中配置TensorFlow使用環(huán)境的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04
Django連接數(shù)據(jù)庫并實現(xiàn)讀寫分離過程解析
這篇文章主要介紹了Django連接數(shù)據(jù)庫并實現(xiàn)讀寫分離過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11
python pyinstaller打包exe報錯的解決方法
這篇文章主要給大家介紹了關于python pyinstaller打包exe報錯的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者使用python具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-11-11

