pip install airtest
pip install pytesseract
安裝完畢後可以在命令行輸入 pip list 檢查安裝結果:打開我們的AirtestIDE,在 選項--設置--自定義python.exe路徑 中設置我們剛才安裝好對應庫的python環境:以之前官網提供的 poco demo的界面為例,我們用 airtest 把紅框部分的截圖截取下來,然後再利用 tesseract 把截圖中的文字識別並列印出來:# -*- encoding=utf8 -*-
__author__ = "AirtestProject"
from airtest.core.api import *
from airtest.aircv import *
auto_setup(__file__)
from PIL import Image
import pytesseract
# 局部截圖
screen = G.DEVICE.snapshot()
local = aircv.crop_image(screen,(132,58,380,126))
# 保存局部截圖到指定文件夾中
pil_image = cv2_2_pil(local)
pil_image.save("D:/test/score0.png", quality=99, optimize=True)
# 讀取截圖並識別截圖中的文字
image = Image.open(r'D:/test/score0.png')
text = pytesseract.image_to_string(image)
print("-初始數據為----")
print(text)
① G.DEVICE.snapshot(),對當前設備畫面進行截圖並保存在內存中。② crop_image(),局部截圖的方法,需要傳入倆個參數,一個是內存中的截圖,就像這裡的 screen,另一個是截取偏移 [x_min, y_min, x_max ,y_max]。③ Image.open(),用來直接讀取給定路徑指向的圖片④ image_to_string(),用來解析圖片中的文字以下述驗證碼截圖為例,該截圖的保存路徑為 D:/test/7364.jpg :# 識別驗證碼
image2 = Image.open(r'D:/test/7364.jpg')
text2 = pytesseract.image_to_string(image2)
print("-驗證碼為----")
print(text2)
log("驗證碼為:"+text2)
識別中文的方法和識別數字與英文基本一致,但比較特別的是,我們需要在 image_to_string() 方法中 指定中文的語言參數(示例代碼中指定了簡體中文來識別截圖):# 識別中文
image3 = Image.open(r'D:/test/3.png')
text3 = pytesseract.image_to_string(image3,lang='chi_sim')
print("-識別出來的文字為:----")
print(text3)
log("識別出來的文字為:"+text3)