python如何提取pdf文件图片中的文字?

思路:利用 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()

 

posted @ 2022-02-18 18:01  eliwang  阅读(2647)  评论(0编辑  收藏  举报