改进拖放PDF转换为图片在转换为TXT文件的程序

devtools/2024/9/23 22:11:19/

前段时间我写了Python识别拖放的PDF文件再转成文本文件-CSDN博客

最近有2点更新,一是有一些pdf文件转换出来的图片是横的,这样也可以识别文字,但是可能会影响效果,另一个是发现有一些文字识别不出来,看了关于提高PaddleOCR识别准确率的一些优化(一)_如何提高paddleocr识别准确率-CSDN博客发现是图片文件的尺寸太大了,为此将其缩小一半再识别。确实提高了识别率。

代码:

# -*- coding: utf-8 -*-
"""
Created on Sun Aug 25 10:42:39 2024@author: YBK
"""import tkinter as tk
import windnd
from tkinter.messagebox import showinfo
import os
from PIL import Image
import fitz
from fitz import Document as openPDF
import time
import re
from paddleocr import PaddleOCR
import subprocessdef dec_to_36(num):base = [str(x) for x in range(10)] + [chr(x) for x in range(ord('A'),ord("A")+26)]# 前者把 0 ~ 9 转换成字符串存进列表 base 里,后者把 A ~ Z 存进列表l = []if num<0:return "-"+dec_to_36(abs(num))while True:num,rem = divmod(num,36) # 求商 和 留余数l.append(base[rem])if num == 0:return "".join(l[::-1])def nowtime_to_str():#将当前时间戳转化为36进制,约6位字符,减少文件名长度unix_timestamp = int(time.time())return(dec_to_36(unix_timestamp))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)"# 打开pdfdoc = openPDF(path)# 图片计数imgcount = 0lenXREF = 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)# 如果不是对象也不是图片,则continueif not isXObject or not isImage:continueimgcount += 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" + str(imgcount).zfill(3) + ".png"# 如果pix.n<5,可以直接存为PNGif pix.n < 5:pix._writeIMG(os.path.join(pic_path, new_name),1,10)# 否则先转换CMYKelse:pix0 = fitz.Pixmap(fitz.csRGB, pix)pix0._writeIMG(os.path.join(pic_path, new_name),1,10)pix0 = None# 释放资源pix = Noneimage = Image.open(os.path.join(pic_path, new_name))#对于尺寸大于2000 * 2000的图像,缩放至(h * 0.5,w * 0.5)识别准确率有所提升if image.width > 2000 or image.height > 2000:new_image = image.resize((int(image.width * 0.5), int(image.height * 0.5)))new_image.save(os.path.join(pic_path, new_name))print("缩小图片尺寸")new_image.close()image = Image.open(os.path.join(pic_path, new_name))#对于图片宽度大于高度,左旋转if image.width > image.height: rotated_img = image.transpose(Image.ROTATE_90)print("左旋转")rotated_img.save(os.path.join(pic_path, new_name))           image.close()t1 = time.perf_counter()print("运行时间:{}s".format(t1 - t0))print("提取了{}张图片".format(imgcount))
def get_file_size(file_path):# 获取文件的大小(单位为字节)file_size = os.stat(file_path).st_sizereturn file_size
def dragged_files(files):fileurl = ''if len(files) > 1:# print("请拖放一个文件!")showinfo("提示","请拖放一个文件!")else:# print(files[0].decode('gbk'))fileurl = files[0].decode('gbk')# print(os.path.splitext(fileurl)[1])if fileurl != '' and os.path.splitext(fileurl)[1] == '.pdf':pdfpath = fileurlfilename0 = os.path.basename(fileurl).replace('.pdf','') + nowtime_to_str()# filename0 用于生成文件夹和文件名,为了不重复,在后面加入编码后的时间戳pic_path = f'e:\\临时文件夹\\{filename0}\\'if not os.path.exists(pic_path):os.mkdir(pic_path)m = pdf2pic(pdfpath, pic_path)pngpath = pic_pathouttxtpath = 'e:\\临时文件夹\\'+filename0+'.txt'ocr = PaddleOCR(use_angle_cls=True, lang="ch") # need to run only once to download and load model into memorylines = []for filename in os.listdir(pngpath):img_path = pngpath+filenameresult = ocr.ocr(img_path, cls=True)print(img_path)# image = Image.open(img_path).convert('RGB')if result[0] is not None:boxes = [detection[0] for line in result for detection in line] # Nested loop addedtxts = [detection[1][0] for line in result for detection in line] # Nested loop addedscores = [detection[1][1] for line in result for detection in line] # Nested loop addedfor box, txt, score in zip(boxes, txts, scores):if score > 0.7:# 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)subprocess.run(['notepad.exe', outtxtpath], check=True)if __name__ == '__main__':rootWindow = tk.Tk()rootWindow.title("拖放PDF文件识别文字")rootWindow.geometry("300x120")windnd.hook_dropfiles(rootWindow , func=dragged_files)rootWindow.mainloop()


http://www.ppmy.cn/devtools/116194.html

相关文章

把任务管理器里面的vmware usb arbitrition停了,虚拟机一直识别不到手机设备了

在设备管理器--服务 里面找到VMware usb arbitrition服务&#xff0c;点击“启用”就好了。 参考大佬的文章&#xff1a; 吐血经验&#xff01;&#xff01;&#xff01;解决虚拟机连不上USB&#xff01;最全&#xff01;_为什么vmware虚拟机不能连接上usb设备-CSDN博客

C#三目运算与随机数的应用

三目运算 是用来简化判断的 //所谓的三目 有三个表达式组成 //表达式一 条件表达式 返回的结果是布尔 //表达式二 条件表达式结果为true 时 返回的值 //表达式三 条件表达式结果为false 时 返回的值 /* int age …

Qt_多元素控件

目录 1、认识多元素控件 2、QListWidget 2.1 使用QListWidget 3、QTableWidget 3.1 使用QListWidget 4、QTreeWidget 4.1 使用QTreeWidget 5、QGroupBox 5.1 使用QGroupBox 6、QTabWidget 6.1 使用QTabWidget 结语 前言&#xff1a; 在Qt中&#xff0c;控件之间…

CleanMyMac X 4.15.6正式版 mac直装破解版

你知道 CleanMyMac是什么吗&#xff1f;它的字面意思为“清理我的Mac”&#xff0c;作为软件&#xff0c;那就是一款 Mac清理工具 &#xff0c;Mac OS X 系统下知名系统清理软件&#xff0c;是数以万计的Mac用户的选择。它可以流畅地与系统性能相结合&#xff0c;只需…

实操学习——题目的管理

实操学习——题目的管理 一、基础配置二、权限控制三、分页1. PageNumberPagination分页器2. LimitOffsetPagination分页器3.总结 四、题目操作模块1. 考试2. 题目练习——顺序刷题3. 模拟考试 补充&#xff1a;前端调用接口写法 本文主要讲解题目的管理案例 1.题目的基本增删改…

Python数据分析与可视化实战指南

在数据驱动的时代&#xff0c;Python因其简洁的语法、强大的库生态系统以及活跃的社区&#xff0c;成为了数据分析与可视化的首选语言。本文将通过一个详细的案例&#xff0c;带领大家学习如何使用Python进行数据分析&#xff0c;并通过可视化来直观呈现分析结果。 一、环境准…

Webshell机制绕过的个人理解总结

Webshell是指我们上传到网站的一些恶意后门程序或代码注入&#xff0c;这些Webshell能够使我们获得对网站的远程控制。而Webshell的核心就是那些危险函数&#xff0c;即系统命令执行函数和代码执行函数 常见的系统命令执行函数有system()&#xff0c;exec()&#xff0c;shell_…

React项目实战(React后台管理系统、TypeScript+React18)

### 项目地址:(线上发布) (1)别人的项目地址 gitgitee.com:zqingle/lege-react-management.git (2)我自己的项目地址 gitgitee.com:huihui-999/lege-react-management.git ### B站讲解视频地址 https://www.bilibili.com/video/BV1FV4y157Zx?p37&spm_id_frompageDrive…