比较实用的代码,不用花钱去买会员,文字识别是采用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的文字进行换行