告別「複製+貼上」,基於深度學習的OCR,實現PDF轉文字

選自Towardsdatascience

作者:Lucas Soares

機器之心編譯

編輯:陳萍

對很多人來說,將 PDF 轉換為可編輯的文字是個剛需,卻苦於沒有簡單方法。在本文介紹的專案中,來自 K1 Digital 的高階機器學習工程師 Lucas Soares,嘗試使用 OCR(光學字元識別)自動轉錄 pdf 幻燈片,轉錄效果還不錯。

傳統的講座通常伴隨著一組 pdf 幻燈片。一般來說,想要對此類講座做筆記,需要從 pdf 複製、貼上很多內容。

最近,來自 K1 Digital 的高階機器學習工程師 Lucas Soares 一直在嘗試透過使用 OCR(光學字元識別)自動轉錄 pdf 幻燈片,以便直接在 markdown 檔案中操作它們的內容,從而避免手動複製和貼上 pdf 內容,實現這一過程的自動化。

告別「複製+貼上」,基於深度學習的OCR,實現PDF轉文字

左為專案作者 Lucas Soares。

專案地址:https://github。com/EnkrateiaLucca/ocr_for_transcribing_pdf_slides

為什麼不使用傳統的 pdf 轉文字工具呢?

Lucas Soares 發現傳統工具往往會帶來更多的問題,需要花時間解決。他曾經嘗試使用傳統的 Python 軟體包,但是遇到了很多問題(例如必須使用複雜的正則表示式模式解析最終輸出等),因此決定嘗試使用

目標檢測和 OCR

來解決。

基本過程可分為以下步驟:

將 pdf 轉換為圖片;

檢測和識別影象中的文字;

展示示例輸出。

基於深度學習的 OCR 將 pdf 轉錄為文字

將 pdf 轉換為影象

Soares 使用的 pdf 幻燈片來自於 David Silver 的增強學習(參見以下 pdf 幻燈片地址)。使用「pdf2image」包將每張幻燈片轉換為 png 影象格式。

告別「複製+貼上」,基於深度學習的OCR,實現PDF轉文字

pdf 幻燈片示例。

地址:https://www。davidsilver。uk/wp-content/uploads/2020/03/intro_RL。pdf

程式碼如下:

from pdf2image import convert_from_pathfrom 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 格式的影象:

告別「複製+貼上」,基於深度學習的OCR,實現PDF轉文字

檢測和識別影象中的文字

為了檢測和識別 png 影象中的文字,Soares 使用 ocr。pytorch 庫中的文字檢測器。按照說明下載模型並將模型儲存在 checkpoints 資料夾中。

ocr。pytorch 庫地址:https://github。com/courao/ocr。pytorch

程式碼如下:

# adapted from this source: https://github。com/courao/ocr。pytorch%load_ext autoreload%autoreload 2import osfrom ocr import ocrimport timeimport shutilimport numpy as npimport pathlibfrom PIL import Imagefrom glob import globimport matplotlib。pyplot as pltimport seaborn as snssns。set()import pytesseractdef single_pic_proc(image_file):    image = np。array(Image。open(image_file)。convert(‘RGB’))    result, image_framed = ocr(image)    return result,image_framedimage_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() 函式執行 OCR 模組中的檢測和識別模型,最後將輸出儲存到輸出資料夾。

其中檢測繼承(inherit)了 Pytorch CTPN 模型,識別繼承了 Pytorch CRNN 模型,兩者都存在於 OCR 模組中。

示例輸出

程式碼如下:

import cv2 as cvoutput_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 幻燈片,圖右為轉錄後的輸出文字,轉錄後的準確率非常高。

告別「複製+貼上」,基於深度學習的OCR,實現PDF轉文字

文字識別輸出如下:

filename = f“{output_dir}/image7。txt”with open(filename, “r”) as text:    for line in text。readlines():        print(line。strip(“\n”))

透過上述方法,最終你可以得到一個非常強大的工具來轉錄各種文件,從檢測和識別手寫筆記到檢測和識別照片中的隨機文字。擁有自己的 OCR 工具來處理一些文字內容,這比依賴外部軟體來轉錄文件要好的多。

原文連結:https://towardsdatascience。com/faster-notes-with-python-and-deep-learning-b713bbb3c186