您好,欢迎访问一九零五行业门户网

python怎么实现图片转文字

python图片转文字用python+tesseract-ocr做了一个图片转文字的小工具,gui设计使用tkinter库的控件
界面及效果见下图:
#进一步优化 1. 底部添加label 2.对识别后的文本处理,去空格from pil import image as pimagefrom pil import imagetkimport pytesseractfrom tkinter import *from tkinter import filedialogfrom tkinter.scrolledtext import scrolledtextimport re# 将图片内容翻译为文字,显示在文本框内def trans(): contents.delete('1.0', end) transtxt = pytesseract.image_to_string(pimage.open(filepath.get()),lang='chi_sim') #对transtxt进行处理 去空格,换行符去重 transtxt = transtxt.strip('\n\r') #无参数可以删除开头结尾的空格\n\t\r print(transtxt) contents.insert( insert, transtxt.replace(' ','').replace('\n\n','\n').replace('\r',''))#打开图片文件,显示路径,并将图片展现def openfile(): filename.delete('1.0', end) filepath.set(filedialog.askopenfilename()) filename.insert(1.0,filepath.get()) org_img = pimage.open(filepath.get()) #调整图片显示大小 600*800 w,h = org_img.size if w>600: h=int(h*600/w) w=600 if h>800: w=int(w*800/h) h=800 img = imagetk.photoimage(org_img.resize((w,h))) showpic.config(image=img) showpic.image = img #保持一个引用才能显示图片,tkinter的bug #设置主窗口top = tk()top.title("ocr图片转文字 引擎:tesseract-ocr made by: kaivis")#top.iconbitmap("./pic/y1.ico")top.geometry("1200x800")filepath=stringvar()bt_img1 = imagetk.photoimage( file= "./pic/outbox1.png")bt_img2 = imagetk.photoimage( file= "./pic/bt_img2.png")#第一个窗体frame1 = frame (top, relief=raised, borderwidth=2)frame1.pack(side=top, fill=both, ipady=5, expand=0)label(frame1,height=1,text="图片路径:").pack(side=left)filename = text(frame1,height=2)filename.pack(side=left,padx=1, pady=0,expand=true, fill=x)button(frame1,text="打开文件", image=bt_img1, command=openfile).pack(side=left,padx=5, pady=0)button(frame1,text="中文识别", image=bt_img2, command=trans).pack(side=left,padx=5, pady=0)#第二个窗体frame2 = frame (top, relief=raised, borderwidth=2)frame2.pack (side=left, fill=both, expand=1)label(frame2,text='图片显示:',borderwidth=5).pack(side=top,padx=20,pady=5)showpic = label(frame2,text='图片显示区')showpic.pack(side=bottom,expand=1,fill=both)#第三个窗体frame3 = frame (top)frame3.pack (side=right, fill=both, expand=1)#contents = scrolledtext(frame3)label(frame3,text='识别结果:',borderwidth=5).pack(side=top,padx=20,pady=10)contents = text(frame3,font=('arial',15))contents.pack(side=top,expand=1,fill=both)label(frame3,text='copyright 2021 baidu.com all rights reserved',borderwidth=5).pack(side=bottom,padx=20,pady=10)top.mainloop()
存在的问题:
识别率不高,对紧密型的汉字更是难以做到较高的准确率,有没有更好的ocr引擎呢
识别后的文字已经做了去空格处理 ,文本可以进一步优化,特别是多余的换行符需要处理
python截图转文字功能由于在网上找资料时,经常遇到文章无法复制的情况,为了能够快速copy想要的文字,于是就想写一个python程序去实现截图转文字的功能。
1. 思路首先要有记录键盘的功能(让程序知道你在截图) - keyboard库截图后需要接收图像 - imagegrab库获取图像后要进行文字识别 - 百度ai文字识别api
2. 实现2.1 导入相关库
2.2 创建类,并编写实现截图保存的函数
由于我使用的是win10自带的截图软件,所以截图热键为‘win+shift+s’,大家可以根据截图软件的不同自由更改。
2.3 编写图片转文字的函数
先去百度智能云官网申请一个图像识别的api。
将参数写入程序:
编写转文字函数:
2.5 运行
使用时创建类,调用两个函数即可:
2.6 效果
运行程序,随意在百度文库的一篇文章里截一张图:
结果如下:
注意:
由2.6运行结果可知,效果还是不错的。完美解决了我当前的需求。
以上就是python怎么实现图片转文字的详细内容。
其它类似信息

推荐信息