Python實戰:截圖識別文字,過萬使用量版本!(附源碼!!)


前人栽樹后人乘涼,以不造輪子為由

使用百度的圖片識字功能,實現了一個上萬次使用量的腳本。

  系統:win10

  Python版本:python3.8.6

  pycharm版本:pycharm 2021.1.2(Professional Edition)

 完整代碼下載:Baidu_Ocr.py-Python

 

 

一、獲取百度智能雲token

百度智能雲 登錄后找到人工智能界面下的文字識別->管理界面創建應用文字識別。

創建應用完成后記錄下,后台界面提供的AppIDAPI keySecret Key的信息

接下來根據 官方提供的文檔獲取使用Token

# encoding:utf-8
import requests
# client_id 為官網獲取的AK, client_secret 為官網獲取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=wgEHks0l6MCpalbs3lPuFX1U&client_secret=Z4Rn4ghBx9k06fUYPmSEIRbCFvWFxLyQ'
response = requests.get(host)
if response:
    print(response.json()['access_token'])

二、百度借口調用

使用獲取后token調用百度接口對圖片進行識別提取文字

# encoding:utf-8

import requests
import base64
'''
通用文字識別(高精度版)
'''
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
# 二進制方式打開圖片文件
f = open('圖片.png', 'rb')
img = base64.b64encode(f.read())
params = {"image":img}
# 獲取后的Token的調用
access_token = '24.0d99efe8a0454ffd8d620b632c58cccc.2592000.1639986425.282335-24065278'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
if response:
    print (response.json())

獲取后的tokenjson格式的數據

 

此處步驟我們可以看出識別后的文件是以json的格式返回的所以要想達到取出文字的效果就需要對json格式的返回值進行解析

三、搭建窗口化的程序以便於使用

實現窗口可視化的第三方類庫是Tkinter。可在終端輸入 pip install tkinter 自行下載安裝

導入tkinter模塊包 構建我們的可視化窗口,要是實現的功能有截圖識別文字,中英文分離,文字識別后自動發送給剪切板

from tkinter import *
# 創建窗口
window = Tk()
# 窗口名稱
window.title('qcc-tnw')
# 設置窗口大小
window.geometry('400x600')
# 窗口標題設置
l=Label(window,text='百度API調用', bg='green', fg='white', font=('Arial', 12), width=30, height=2)
l.pack()
# 設置文本接收框
E1 = Text(window,width='100',height='100')
# 設置操作Button,單擊運行文字識別  "window窗口,text表示按鈕文本,font表示按鈕本文字體,width表示按鈕寬度,height表示按鈕高度,command表示運行的函數"
img_txt = Button(window, text='文字識別', font=('Arial', 10), width=15, height=1)
# 設置操作Button,單擊分割英文
cut_en = Button(window, text='英文分割', font=('Arial', 10), width=15, height=1)
# 設置操作Button,單擊分割中文
cut_cn = Button(window, text='中文分割', font=('Arial', 10), width=15, height=1)
# 參數anchor='nw'表示在窗口的北偏西方向即左上角
img_txt.pack(anchor='nw')
cut_en.pack(anchor='nw')
cut_cn.pack(anchor='nw')
# 使得構建的窗口始終顯示在桌面最上層
window.wm_attributes('-topmost',1)
window.mainloop()

 

四、實現截圖的自動保存

通過上述對百度接口的解析發現接口是不支持提取剪切板中的文件的

所以通過PIL庫截取的圖片從剪切板保存到本地,在調用百度的接口實現圖片中文字的識別

PIL的安裝 終端輸入 pip install PIL

from PIL import ImageGrab

#取出剪切板的文件保存至本地

image = ImageGrab.grabclipboard()
s= 'xxx.png'
image.save(s)
#百度接口調用
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
f = open(s, 'rb')
img = base64.b64encode(f.read())
params = {"image": img}
access_token = '24.ee0e97cbc00530d449464a563e628b8d.2592000.1640228774.282335-24065278'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
for i in response.json()['words_result']:
    print(i['words'])

完成后可以使用qq或微信等的截圖功能截圖並運行程序

 

五、將識別到的文字輸出顯示在窗口文本框中並將文字發送到剪切板

if response:
    for i in response.json()['words_result']:
        # 接受識別后的文本
        E1.insert("insert", i['words'] + '\n')
        E1.pack(side=LEFT)
    # 將識別后的文字寫入剪切板
    pyperclip.copy(E1.get("1.0","end"))

六、提取識別后文字中的中(英)文

此處的判斷相對簡單將 if len(''.join(re.findall(r'[A-Za-z]', i['words'])))<1: 中的<’改為‘>’即為中文

E1.delete('1.0','end')
for i in response.json()['words_result']:
#判斷是否存在英文
    if len(''.join(re.findall(r'[A-Za-z]', i['words'])))<1:
        #將識別正則過濾后的文本在文本框中顯示
        E1.insert("insert", i['words'] + '\n')
        E1.pack(side=LEFT)
    #復制到剪切板
    pyperclip.copy(E1.get("1.0", "end"))

最后將方法封裝為函數形式傳遞至我們定義好的窗口按鈕中

# 設置操作Button,單擊運行文字識別  "window窗口,text表示按鈕文本,font表示按鈕本文字體,width表示按鈕寬度,height表示按鈕高度,command表示運行的函數"
img_txt = Button(window, text='文字識別', font=('Arial', 10), width=15, height=1,command=img_all)
# 設置操作Button,單擊分割英文
cut_en = Button(window, text='英文分割', font=('Arial', 10), width=15, height=1,command=img_en)
# 設置操作Button,單擊分割中文
cut_cn = Button(window, text='中文分割', font=('Arial', 10), width=15, height=1,command=img_cn)
# 參數anchor='nw'表示在窗口的北偏西方向即左上角
img_txt.pack(anchor='nw')
cut_en.pack(anchor='nw')
cut_cn.pack(anchor='nw')
window.wm_attributes('-topmost',1)

 

 

Auto Copied
Auto Copied


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM