pdf转图片后识别文字后转txt文件

比较实用的代码,不用花钱去买会员,文字识别是采用paddle GPU版本

# -*- coding: utf-8 -*-
"""
Created on Sat Jun  8 19:35:53 2024

@author: Ybk
"""

import fitz
from fitz import Document as openPDF
import time
import re
import os
from paddleocr import PaddleOCR, draw_ocr
from PIL import Image

def pdf2pic(path, pic_path):
    '''
    # 从pdf中提取图片
    :param path: pdf的路径
    :param pic_path: 图片保存的路径
    :return:
    '''
    t0 = time.perf_counter()
    # 使用正则表达式来查找图片
    checkXO = r"/Type(?= */XObject)"
    checkIM = r"/Subtype(?= */Image)"

    # 打开pdf
    doc = openPDF(path)
    # 图片计数
    imgcount = 0
    lenXREF = doc.xref_length()

    # 打印PDF的信息
    print("文件名:{}, 页数: {}, 对象: {}".format(path, len(doc), lenXREF - 1))

    # 遍历每一个对象
    for i in range(1, lenXREF):
        # 定义对象字符串
        text = doc.xref_object(i)
        isXObject = re.search(checkXO, text)
        # 使用正则表达式查看是否是图片
        isImage = re.search(checkIM, text)
        # 如果不是对象也不是图片,则continue
        if not isXObject or not isImage:
            continue
        imgcount += 1
        # 根据索引生成图像
        pix = fitz.Pixmap(doc, i)
        # 根据pdf的路径生成图片的名称
        # new_name = path.replace('\\', '_') + "_img{}.png".format(imgcount)
        # new_name = new_name.replace(':', '')
        new_name = os.path.basename(path).replace('.pdf', '_') + "img{}.png".format(imgcount)
        # 如果pix.n<5,可以直接存为PNG
        if pix.n < 5:
            pix._writeIMG(os.path.join(pic_path, new_name),1,10)
        # 否则先转换CMYK
        else:
            pix0 = fitz.Pixmap(fitz.csRGB, pix)
            pix0._writeIMG(os.path.join(pic_path, new_name),1,10)
            pix0 = None
        # 释放资源
        pix = None
        t1 = time.perf_counter()
        print("运行时间:{}s".format(t1 - t0))
        print("提取了{}张图片".format(imgcount))

if __name__=='__main__':
    # pdf路径
    filename = '2905.pdf'
    filename0 = filename.replace('.pdf','')
    pdfpath = r'e:/8888/'+filename
    pic_path = r'e:/8888/'+filename0+'/'
    # 创建保存图片的文件夹
    if not os.path.exists(pic_path):
        os.mkdir(pic_path)
    m = pdf2pic(pdfpath, pic_path)
    pngpath = pic_path
    outtxtpath = r'e:/8888/'+filename0+'.txt'
    ocr = PaddleOCR(use_angle_cls=True, lang="ch") # need to run only once to download and load model into memory
    lines = []
    for filename in os.listdir(pngpath):
        print(filename)
        img_path = pngpath+filename
        result = ocr.ocr(img_path, cls=True)
        
        image = Image.open(img_path).convert('RGB')
        boxes = [detection[0] for line in result for detection in line] # Nested loop added
        txts = [detection[1][0] for line in result for detection in line] # Nested loop added
        scores = [detection[1][1] for line in result for detection in line] # Nested loop added
        for box, txt, score in zip(boxes, txts, scores):
            if score > 0.75:
                # lines.append(txt.replace('\n',''))
                lines.append(txt+'\n')
        lines.append('\n')

    with open(outtxtpath, 'w', encoding='utf-8') as f:
        f.writelines(line for line in lines)
    

score 是识别度大于0.75,lines注释那个是按不按pdf的文字进行换行

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值