思路:利用 pymupdf+pytesseract
通過pymupdf提取pdf文件中的圖片,並寫入到本地,然后利用tesseract-ocr去處理
1、安裝pymupdf
pip install pymupdf
雖然安裝的庫為pymupdf,實際上調用的包名為fitz
2、示例:提取pdf文件圖片中的俄文
# coding:utf-8 import os import time import fitz import pytesseract from PIL import Image class TestHandler: def __init__(self): self.dir_path = './imgs' def run(self): if not os.path.exists(self.dir_path): os.mkdir(self.dir_path) start_time = time.time() text = self.extract_text('./russia.pdf') print(text) print(f'總耗時:{time.time()-start_time}秒') def extract_text(self,file_name): extract_text = '' # 用於存儲提取的文本 doc = fitz.open(file_name) # 遍歷每一頁pdf for i in range(len(doc)): img_list = doc.get_page_images(i) # 提取該頁中的所有img # 遍歷每頁中的圖片, for num, img in enumerate(img_list): img_name = f"{self.dir_path}/{i + 1}_{num + 1}.png" # 存儲的圖片名 pix = fitz.Pixmap(doc, img[0]) # image轉pixmap if pix.n - pix.alpha >= 4: # 如果差值大於等於4,需要轉化后才能保存為png pix = fitz.Pixmap(fitz.csRGB, pix) pix.save(img_name) # 存儲圖片 pix = None # 釋放Pixmap資源 image = Image.open(img_name) text = pytesseract.image_to_string(image,'rus') # 調用tesseract,使用俄語庫 extract_text += text # 寫入文本 os.remove(img_name) return extract_text if __name__ == '__main__': TestHandler().run()